Submitted by raddleboy in programming (edited )
nulloperation wrote (edited )
Reply to comment by Twoeyes in How to create an infinite attempt password message box in pyautogui? by raddleboy
You could also do stuff with an array or some lists to contain it all in the one loop, but I don't know the syntax well enough to write it off the top of my head.
Here's my attempt at that. If you want to add more questions, just add them to the questions
list.
questions=[
{"q":"famous blue anti-civ hedgehog?","a":"sonic"},
{"q":"blue men who live in mushrooms?","a":"smurfs"}
]
def ask(question):
print(question["q"])
return input().lower() == question["a"].lower()
def ask_all(questions):
if questions:
if ask(questions[0]):
return ask_all(questions[1:])
else:
return False
else:
return True
if ask_all(questions):
print('succes')
else:
print('fail')
@kokoaitu You should really use code blocks for pasting code, especially a language like Python with whitespace sensitive syntax. Also, I think your do ... until
construct is not really quite Python.
@raddleboy If you're new to Python or programming in general, I'd suggest sticking with plain Python (without GUI libraries) while you're getting to know the language. Using time.sleep()
in the same thread as the GUI can be problematic as it can lock up the GUI.
Extra points if anyone can do this
- Add one more question-answer pair. (easy)
- Explain how my code is looping through the questions without using
for
orwhile
. (medium) 😉 Hint: Is any function calling itself? - Modify the program so that when a question is answered wrong then the player gets a chance to answer again rather than the program exiting. (medium)
Change
return False
toreturn ask_all(questions)
. - Add an
ask_gui
method that displays a graphical dialog box with the question and a text field for answering. (medium) Just to repeat: You do not want to be using pyautogui for this. For GUI bindings, look up tkinter or pygtk or pygame. - Add an optional parameter to the
ask_all
function where you can pass which asking function to use, likeask
orask_all
. (difficult) Hint: You have to extendask_all
to be a higher-order function taking an optional argument which is a function. - This implementation of the quiz program is written in functional style, with
ask_all
being a pure function without side-effects. Try changing the program to an imperative style using a mutable stack for the questions. (medium) - Try changing the quiz-program to be written in Object Oriented style. (easy/hard?)
Viewing a single comment thread. View all comments