需要帮助将我的代码循环回到更早的代码行

时间:2014-11-26 09:40:34

标签: python

我目前的代码是:

#Imports the random module
import random

#Asks the user to input there name
print("What's your name ?")
name = input()
#Resets the score
score = 0

#Loops ten times for ten questions

for i in range(1, 11):

    #Generates two numbers and an operator
    x = random.randint(1, 20)
    y = random.randint(1, 20)
    opIndex = random.randint(1, 3)

    #Checks the opIndex, gives an operator and calculates the result
    if opIndex == 1:
        op = '+'
        ans = x + y
    elif opIndex == 2:
        op = '-'
        ans = x - y
    else:
        op = '*'
        ans = x * y

#asks the user if they want to take the test
start = input("Are you ready to take the test? (y/n):")
while start.lower() =='y':

    #Prints out the question for user input (Too much concatenation)
    inp = input('Question ' + str(i) + ': ' + str(x) + op + str(y) + '= ')

    #Checks if the input is the same as the answer to the sum
    if int(inp) == int(ans):

        #Tells the user that they were correct and adds 1 to their score
        print('Correct answer, well done!\n')
        score += 1
    elif start.lower() =='n':
        print ("take your time to prepare")
        start = input ("Are you ready now ? [y/n]")
    else:
        print('Incorrect answer, bad luck!\n')

#After the 'for' loop the final score is printed
print('\n' + name + ' your final score was ' + str(score) + ' out of 10!')

但如果用户使用'n'回答,我需要它回到您准备好开始的问题。

谢谢,如果你能提供帮助。

1 个答案:

答案 0 :(得分:0)

while True:
start = raw_input("Are you ready to take the test? (y/n): ")
if start=="n":
    print("take your time to prepare")

start=raw_input("Are you ready now?[y/n]: ")
if start=="n":
    continue

<强>此处