我试图学习用Python编写,并试图制作一个计算器。为此,我使用输入来选择要计算的数字类型,然后输入要计算的数字。
print ("1. add ; 2. subtract ; 3. multiply ; 4. divide " )
print ("wat is your choise")
choise = input()
if choise == 1 :
num_1_1 = input()
num_2_1 = input()
anwsr_add = (num_1_1 + num_2_1)
print (anwsr_add)
并重复其余选项。
然而,这会返回anwsr_add
无法打印,因为它没有定义。它让我相信第二个输入无效,没有任何东西等于anwsr_add
。
在if流中是否有这些输入函数的额外代码,或者我是否完全跟踪这种方法?
这取决于您使用的是哪个版本的python。
如果你使用的是python 3,那么input()将返回一个'str'类型,这会导致你的错误。要测试这个理论,请尝试print(type(choice))并查看它返回的类型。如果它返回str,则有你的罪魁祸首。如果没有,请回复我们,以便我们继续调试。我已经在python 3中发布了我的方法来解决你的问题,所以你有一个参考,以防万一我无法回复。如果您想自己编写,请随意忽略它。
choice = int(input('Enter 1 to add, 2 to subtract, 3 to multiply, 4 to divide\n'))
if 1 <= choice <= 4:
num1 = int(input('What is the first number? '))
num2 = int(input('What is the second number? '))
if choice == 1:
answer = num1 + num2
elif choice == 2:
answer = num1 - num2
elif choice == 3:
answer = num1 * num2
elif choice == 4:
# In python 3, the answer here would be a float.
# In python2, it would be a truncated integer.
answer = num1 / num2
else:
print('This is not a valid operation, goodbye')
print('Your answer is: ', answer)
我发现的主要问题是您正在将char数据类型与int数据类型进行比较。当您要求用户输入时,默认情况下会将其存储为字符串。字符串无法与整数进行比较,这是您尝试使用if
块进行的操作。如果将输入包装在int()
调用中,它会将char转换为int数据类型,然后可以与== 1
语句进行正确比较。另外,在你的if
声明中,你可以两次调用input()
,它也会给你一个字符串。这意味着如果您输入1
和1
,您将获得11
(如a + b = ab
)。要解决这个问题,还可以使用input()
调用包装那些int()
语句。我在下面的代码中解决了这些问题:
choice = int(input())
if choice == 1:
num_1_1 = int(input())
num_2_1 = int(input())
anwsr_add = (num_1_1 + num_2_1)
print(anwsr_add)
嘿Dalek我复制了你的代码并得到了这个结果:
1. add ; 2. subtract ; 3. multiply ; 4. divide
What's your choise?
1
Traceback (most recent call last):
File "C:\Users\timur\AppData\Local\Programs\Python\Python36-32\Game.py", line 10, in <module>
print (anwsr_add)
NameError: name 'anwsr_add' is not defined
发生NameError是因为程序在执行anwsr_add
下面的代码时尝试调用if choise == ...
您可以使用此代码。有用。你的代码不起作用的原因是你不在anwr_add
方法中调用if choise == ...
:
choise = input("1. add ; 2. subtract ; 3. multiply ; 4. divide. What's your choise?")
if str(choise) == '1':
print('First_num:')
num_1_1 = input()
print('Second_num:')
num_2_1 = input()
anwsr_add = (int(num_1_1) + int(num_2_1))
print (anwsr_add)