我正在创建一个程序,它将教我的小弟弟数学。但是例如,当程序说2 + 2时,我输入4就说“不正确!”。我做错了什么?
import random
import math
def addition():
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")#this is the line with problem
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()
答案 0 :(得分:5)
result
是整数(例如,4),并且输入的猜测是字符串(例如,' 4')。您需要将它们转换为相同的类型才能进行比较。 E.g:
result = str(num1 + num2)
答案 1 :(得分:1)
将答案包裹到int
guess = int(input(str(num1) + " + " + str(num2) + " = "))
答案 2 :(得分:1)
将input
转换为int
:
import random
import math
def addition():
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")
guess = int(guess) #input is string and it must be typecast to int
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()