Python中制作计算器, 这个方法可行吗?

2024-10-02 08:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力学习用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流中是否有这些输入函数的额外代码,或者我是否完全不支持这种方法


Tags: add类型inputifis数字nummultiply
3条回答

嘿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 你可以使用这个代码。它起作用了。代码不起作用的原因是调用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) 

这取决于您使用的python版本。

如果您使用的是python3,那么input()is将返回一个类型为'str',这将导致您的错误。要测试这个理论,请尝试print(type(choice))并查看它返回什么类型。如果它返回str,那么就是你的罪魁祸首。如果没有,请与我们联系,以便我们可以继续调试。我已经在下面的python3中发布了解决您问题的方法,以便您在我无法回复的情况下提供参考。请随时忽略它,如果你想写这一切你自己

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()两次,还将得到一个字符串。这意味着如果您输入11,您将得到11(如a + b = ab)。要解决这个问题,还可以用int()调用包装那些input()语句。我在下面的代码中修复了这些问题:

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) 

相关问题 更多 >

    热门问题