[英]Why my code (Python adding and subtracting) does not work?
Here is what I need coded:这是我需要编码的内容:
My code is:我的代码是:
import random
i = 1
while i < 6:
answer1 = input("Hello, please type \"add\" for adding, or \"sub\" for subtracting")
first_number = random.randrange(1, 9)
second_number = random.randrange(1, first_number)
one = str(first_number)
two = str(second_number)
if answer1 == "add":
the_answer = first_number + second_number
the_answer_actual = str(the_answer)
user_answer = int(input(one + " + " + two + " = "))
if the_answer == user_answer:
print("The answer is correct!")
i += 1
elif the_answer != user_answer:
print("Wrong answer. The correct answer was " + the_answer_actual)
i += 1
else:
continue
elif answer1 == "sub":
the_answer = first_number - second_number
the_answer_actual = str(the_answer)
user_answer = int(input(one + " - " + two + " = "))
if the_answer == user_answer:
print("The answer is correct!")
i += 1
elif the_answer != user_answer:
print("Wrong answer. The correct answer was " + the_answer_actual)
i += 1
else:
continue
elif answer1 == "end" or i < 6:
print("Goodbye.")
break
else:
pass
======================================================================== Problem: This error code appears when the 5th round is over: ==================================================== ====================== 问题:第5轮结束时出现此错误代码:
You just need to convert the answer to an integer before comparing it:您只需在比较之前将答案转换为 integer :
if answer2 == int(user_answer):
and then it works perfectly (naturally you must do it for subtraction as well)然后它完美地工作(当然你也必须做减法)
EDIT: and you need to add a break after the correct answer编辑:你需要在正确答案后添加一个休息
print("The answer is correct!")
break
You need to do this in both add and sub as it doesn't work in either:您需要在 add 和 sub 中执行此操作,因为它在任何一个中都不起作用:
if str(answer2) == useranswer:
or或者
useranswer = int(input("..."))
as else you will be comparing a string with an int which will never work.否则,您会将字符串与永远不会工作的 int 进行比较。 the first solution converts the number you calculated to a string, the second solution converts the input you get from the user to an int.
第一个解决方案将您计算的数字转换为字符串,第二个解决方案将您从用户获得的输入转换为 int。 Both work, but you cannot compare a String with an int.
两者都有效,但您不能将 String 与 int 进行比较。
If you want to do more comparisons with the userinput (like checking if the result was bigger/lower than what you entered) i would reccomend the first solution, as you will alwats have the userinput as an int until you compare it.如果您想与用户输入进行更多比较(例如检查结果是否大于/小于您输入的内容),我会推荐第一个解决方案,因为您将始终将用户输入作为 int 进行比较,直到您进行比较。
You might need to use if ans2 == user_answer:
instead of if answer2 == user_answer:
since it is a string comparison.您可能需要使用
if ans2 == user_answer:
而不是if answer2 == user_answer:
因为它是字符串比较。
EDIT: You might also want to use i += 1
instead to make sure it stops after the specified number of iterations.编辑:您可能还想使用
i += 1
来确保它在指定的迭代次数后停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.