operandList = [0,0,0,0,0]
operatorList = ['','','','']
operatorDict ={1:'+', 2:'-', 3:'*',4:'**'}
for index in range(0,5):
operandList[index] = randint(1,9)
for index in range(0, 4):
if index > 0 and operatorList[index-1] != '**':
operator = operatorDict[randint(1, 4)]
else:
operator = operatorDict[randint(1, 3)]
operatorList[index] = operator
questionString = str (operandList[0])
for index in range(1, 5):
questionString = questionString + operatorList[index-1] + str(operandList[index])
result = eval(questionString)
questionString = questionString.replace("**", "^")
print ('\n' + questionString)
userResult = input('Answer: ')
while True:
try:
if int(userResult) == result:
print ("So Smart")
return 1
else:
print ("Sorry, wrong answer. The correct answer is",result)
return 0
except Exception as e:
print ("You did not enter a number. Please try again.")
userResult = input('Answer: ')
Getting error at if else loop and return value as mentioned in the code. Program details : you should use an if statement to evaluate the answer and display the correct message. If the user gets it correct, we’ll compliment the user and return the value 1. If the user gets it wrong, we’ll display the correct answer and return the value 0. Recall that the input() function returns user input as a string? Hence, when you compare the user’s input with the correct answer ), you have to do some type casting to change the user input to an integer. When changing the user input to an integer, you should use a try, except statement to check if the user typed in a number. If the user typed in a string instead, the program should inform the user of the error and prompt the user to type in a number. You can use a while True loop to keep prompting the user for a number as long as he/she fails to do so. Writing while True is equivalent to writing something like while 1==1 . Since 1 is always equals to 1 (hence always True ), the loop will run indefinitely. Here’s a suggestion on how you can use a while True loop for this exercise. while True: try: cast user’s answer to an integer and evaluate the answer return user score based on the answer except: print error message if casting fails prompt user to key in the answer again The while True loop will keep looping since the while condition is always True . The loop will exit only when the try block executes correctly and reaches the return statement.
Aucun commentaire:
Enregistrer un commentaire