gpt4 book ai didi

python - python2/3中input()的区别

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:35 26 4
gpt4 key购买 nike

这是一个简单的数学程序,可以帮助我的 child 学习算术。

但是,IF语句在Python3中不起作用,但在Python2中起作用!

请问发生了什么变化(因为我似乎找不到答案)?

#import from library     
import random
import sys

#display the python version
print(sys.version)

#computer selects two random numbers between 1 and 10
x = random.randint(1,10)
y = random.randint(1,10)

#print x and y values
print("For x =", x, "and y =", y)

#calculate the correct answer to the sum of the two numbers and store it in the variable named "correct"
correct = x + y

#ask the user what is the sum of the two random numbers and provide a response
answer = input("What is the sum of x plus y ? ")
if answer == correct:
print("well done")
else:
print("Incorrect. The correct answer is", correct)

最佳答案

答案的数据类型是string,改成int后就可以正常工作了

import random
import sys

#display the python version
print(sys.version)

#computer selects two random numbers between 1 and 10
x = random.randint(1,10)
y = random.randint(1,10)

#print x and y values
print("For x =", x, "and y =", y)

#calculate the correct answer to the sum of the two numbers and store it in the variable named "correct"
correct = x + y

#ask the user what is the sum of the two random numbers and provide a response
answer = input("What is the sum of x plus y ? ")
if(int(answer)==correct):
print("well done")
else:
print("Incorrect. The correct answer is", correct)

关于python - python2/3中input()的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com