Предыстория: для моего урока информатики нас попросили создать программу, которая помогала бы детям начальной школы изучать основную математику.
Они выбирали, какую операцию они хотели бы выучить (сложение, вычитание, умножение или деление), или выберите случайный, который выберет одну из этих операций случайным образом.
После выбора операции пользователю будет задан вопрос, а затем ввести ответ, если он верен, программа задаст другой вопрос, до 4Всего вопросов, и затем программа вернется в меню.
Если ответ неправильный, он просит пользователя ввести ответ снова, до трех раз, если ответ все еще неправильный, будет отображаться правильный ответзатем задали бы другой вопрос (если квота из 4 вопросов не была соблюдена) или вернитесь в меню, если других вопросов нет.
Проблема: у меня все записано, и когда я запускаю программув бездействии все, кажется, работает, но после операцииПо какой-то причине программа выбрана, программа застряла в бесконечном цикле и не вернется в меню после 4 вопросов.
Сначала я использовала цикл for для удовлетворения квоты из 4 вопросов, и это не сработало, поэтомуЯ попытался цикл while, который читает while x<4: etc etc
, определяя x как x = 0 перед циклом while, а затем в конце функции, добавляя x=x+1
.
снова из чтения кода, похоже, что ондолжно работать для каждой функции, но после запуска я все еще застрял в бесконечном цикле.
вот код:
def show_instructions():
"""
Displays a greeting to the user and provides instructions on how to use the
program. [PURPOSE]
"""
print " "
print "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"
print " Math Mania"
print " "
print "Welcome to Math Mania! This program is designed to help you learn basic"
print "math skills in addition, subtraction, multiplication, and division."
print "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"
print " "
print "To learn a skill, type the first letter of that skill."
print " "
print "a for addition"
print "s for subtraction"
print "m for multiplication"
print "d for division"
print "r for random"
print "q to quit"
print " "
def add():
"""
generates display two random numbers and sums them, then prompts the user
to input the correct sum, if the input is incorrect, it prompts the user
to try again.
[PURPOSE]
"""
x=0
while x<4:
num1 = random.randint(1,20)
num2 = random.randint(1,20)
print num1, "+", num2, '= ?'
answer = input ('Enter your answer: ')
count1=0
while answer != num1+num2 and count1<3:
count1=count1 +1
print 'Incorrect, please try again.'
print
print num1, '+', num2, '= ?'
answer = input ('Enter your answer: ')
if count1==3:
print "Sorry, that's incorrect."
print "The correct answer is ",num1+num2
else:
print "That's correct!"
print
x=x+1
def sub():
"""
generates and displays two random numbers and subtracts the smaller of the
two from the larger one. It then prompts the user to input the correct
answer, if the input is incorrect, it prompts the user to try again.
[PURPOSE]
"""
x=0
while x<4:
num1 = random.randint(1,20)
num2 = random.randint(1,20)
if num1>num2:
print num1, "-", num2, '= ?'
answer = input('Enter your answer: ')
count1=0
while answer != num1 - num2 and count1<3:
count1=count1+1
print 'Incorrect, please try again.'
print
print num1, "-", num2, '= ?'
answer = input ('Enter your answer: ')
if count1==3:
print "Sorry, that's incorrect."
print "The correct answer is ",num1-num2
else:
print "That's correct!"
print
x=x+1
else:
print num2, "-", num1, '= ?'
answer = input ('Enter your answer')
count1=0
while answer!= num2-num1 and count1<3:
count1=count1+1
print 'Incorrect, please try again.'
print
print num2, "-", num1, '= ?'
answer = input ('Enter your answer: ')
if count1==3:
print "Sorry, that's incorrect."
print "The correct answer is ",num2-num1
else:
print 'Thats correct!'
print
x=x+1
def mult():
"""
generates and displays two random numbers and finds the product of the two.
It then prompts the user to input the correct product of the two numbers, if
the input is incorrect, it prompts the user to try again.
[PURPOSE]
"""
x=0
while x<4:
num1 = random.randint(1,20)
num2 = random.randint(1,20)
print num1, "x", num2, '= ?'
answer = input ('Enter your answer: ')
count1=0
while answer != num1*num2 and count1<3:
count1=count1+1
print 'Incorrect, please try again.'
print
print num1, 'x', num2, '= ?'
answer = input ('Enter your answer: ')
if count1==3:
print "Sorry, that's incorrect."
print "The correct answer is ", num1*num2
else:
print "That's correct!"
print
x=x+1
def div():
"""
generates and displays the quotient of two numbers, and then prompts the
user to input the correct answer, if the input is incorrect, it then prompts
the user to try again.
[PURPOSE]
"""
x=0
while x<4:
num1 = random.randint(1,20)
num2 = random.randint(1,20)
while (num1%num2!=0):
num2 = random.randint(1,20)
num1 = random.randint(1,20)
print num1, "/", num2, '= ?'
answer = input ('Enter your answer: ')
count1=0
while answer != num1/num2 and count1<3:
count1=count1 +1
print 'Incorrect, please try again.'
print num1, '/', num2, '= ?'
answer = input ('enter your answer:')
if count1==3:
print "Sorry, that's incorrect."
print "The correct answer is ",num1/num2
else:
print "That's correct!"
print
x=x+1
def rand():
"""
picks a arithmetic function at random for the user to to try
[PURPOSE]
"""
num=random.randint(1,4)
if num==1:
add()
if num==2:
sub()
if num==3:
mult()
if num==4:
div()
def main():
"""
main function that brings it all together
[PURPOSE]
"""
show_instructions()
selection = raw_input ('Please select the skill you want to learn: ')
while selection != "q":
if selection == "a":
add()
elif selection == "s":
sub()
elif selection == "m":
mult()
elif selection == "d":
div()
elif selection == "r":
rand()
print "The program will now quit."
quit()
main()`
Заранее благодарю за любую помощь, которую может оказать кто-либо здесь!