My program is supposed to print 10 questions and when it has finished it asks if the user would like to play again, if they press yes then the program is supposed to print 10 questions again but instead it prints 20. I have tried to fix this but it has been to no avail.
score = 0
def mainmenu():
print('What difficulty would you like to play on?')
print('1. Easy')
print('2. Medium') #Three difficulties are shown from which the user can choose
print('3. Hard')
print('4. Quit')
selection = int(input('Choose a number: '))
if selection == 1:
choice = input('Are you sure you want to play on easy? [Y/N] ')
if choice.lower() == 'y' or choice.lower() == 'yes':
easy() #The user is asked to confirm if the difficulty they chose is the one they want
if choice.lower() == 'n' or choice.lower() == 'no':
print('Pick another difficulty') #If they say no they will be returned to the mainmenu using the define function
mainmenu()
if selection == 2:
choice2 = input('Are you sure you want to play on medium? [Y/N] ')
if choice2.lower() == 'y' or choice2.lower() == 'yes':
medium()
if choice2.lower() == 'n' or choice2.lower() == 'no':
print('Pick another difficulty')
mainmenu()
if selection == 3:
choice3 = input('Are you sure you want to play on hard? [Y/N] ')
if choice3.lower() == 'y' or choice3.lower() == 'yes':
hard()
if choice3.lower() == 'n' or choice3.lower() == 'no':
print('Pick another difficulty')
mainmenu()
if selection == 4:
exit()
def easy(): #Easy is defined to allow for smoother access from the mainmenu
global score
print('Heres come the questions!')
for i in range(10): #This process is repeated 10 times
int_a = random.randint(0,10)
int_b = random.randint(0,10) #Random numbers are generated through the use of the random module
operators = ['+'] #The operators are made into a key to allow for them to be chosen randomly
operators_value = random.choice(operators)
question = str(int_a) + ' ' + str(operators_value) + ' ' + str(int_b) #The two random numbers and the randomly chosen operators are made into a question
answerEasy = eval(question) #The answer to the question is then found using the eval function
question += ': '
questionsEasy.update({question:str(answerEasy)}) #The question and answer are put into a key to allow them to be matched up
for s in questionsEasy.keys():
useranswer = input(s)
if questionsEasy.get(s) == str(useranswer): #If the user enters the correct answer 1 point is added to the score
score += 1
print('You got it Correct!')
else:
print('You got it incorrect :(')
print('Nice ' + name + '!' + ' You got ' + str(score) + ' out of 10!')
you should define questionsEasy
in easy
function. The reason your program is printing 20 questions in second go is that questionsEasy
is defined outside the easy function and is retaining its previous values and you are adding 10 more each time
If you are new to programming you can visualize your program using http://www.pythontutor.com/live.html#mode=edit