我正在努力学习用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流中是否有这些输入函数的额外代码,或者我是否完全不支持这种方法
嘿Dalek我复制了你的代码得到了这个结果:
发生NameError是因为程序在执行下面的代码时试图调用
anwsr_add
你可以使用这个代码。它起作用了。代码不起作用的原因是调用anwr_add
而不是在if choise == ...
方法中:这取决于您使用的python版本。
如果您使用的是python3,那么input()is将返回一个类型为'str',这将导致您的错误。要测试这个理论,请尝试print(type(choice))并查看它返回什么类型。如果它返回str,那么就是你的罪魁祸首。如果没有,请与我们联系,以便我们可以继续调试。我已经在下面的python3中发布了解决您问题的方法,以便您在我无法回复的情况下提供参考。请随时忽略它,如果你想写这一切你自己
我发现的主要问题是比较char数据类型和int数据类型。当您请求用户输入时,默认情况下它存储为字符串。不能将字符串与整数进行比较,这就是您试图对
if
块执行的操作。如果将输入包装在int()
调用中,它将把char转换为int数据类型,然后可以与== 1
语句进行适当比较。另外,在if
语句中调用input()
两次,还将得到一个字符串。这意味着如果您输入1
和1
,您将得到11
(如a + b = ab
)。要解决这个问题,还可以用int()
调用包装那些input()
语句。我在下面的代码中修复了这些问题:相关问题 更多 >
编程相关推荐