我制作的 python 个计算器出错

Error in python calculator I made

我试图在 python 中编写一个程序,该程序使用几种不同的操作进行计算(可能效率极低,但我离题了)。但是,运行 时出现了一个我无法弄清楚的错误。我认为这需要定义变量的类型。 节目:

import math
print('Select a number.')
y = input()
print('Select another number.')
x = input()
print('Select what operation you wish to perform. (e for exponentiation, d for division, m for multiplication, a for addition, s for subtraction, mo for modulo, l for log (the base is the first number you entered), r for root)')
z = input()
if z == 'e' or z == 'E':
    print('The answer is ' + y**x)
elif z == 'd' or z == 'D':
    print('The answer is ' + y/z)
elif z == 'm' or z == 'M':
    print('The answer is ' + y*x)
elif z == 'a' or z == 'A':
    print('The answer is ' + y+x)
elif z == 's' or z == 'S':
    print('The answer is ' + y-x)
elif z == 'mo' or z == 'Mo':
    print('The answer is ' + y%x)
elif z == 'l' or z == 'L':
    print('The answer is ' + math.log(x,y))
elif z == 'r' or z == 'R':
    print('The answer is ' + y**(1/x))

出现在 shell 中的错误:

Traceback (most recent call last):
  File "C:/Users/UserNameOmitted/Downloads/Desktop/Python/Calculator.py", line 7, in <module>
    z = input()
  File "<string>", line 1, in <module>
NameError: name 'd' is not defined

你必须做

z = raw_input()

python2.x中也输入returns为int。所以用raw_input读为str然后到处像print('The answer is ' + y**x)变成print('The answer is ' + str(y**x))

你这里有几个问题:

  1. z应该输入raw_input,而不是input
  2. 在除法的情况下,您除以 y/z 而不是 y/x

您的代码有错误

  1. 使用 raw_input() 来获取字符串输入而不是 input()
  2. 使用 int(raw_input()) 获取整数输入,这不是错误,但这是一个很好的做法。
  3. 您尝试将 int 与 string 相除。
  4. 您试图连接字符串和整数。

你的代码应该是这样的。

import math
print('Select a number.')
y = int(raw_input())
print('Select another number.')
x = int(raw_input())
print('Select what operation you wish to perform. (e for exponentiation, d for division, m for multiplication, a for addition, s for subtraction, mo for modulo, l for log (the base is the first number you entered), r for root)')
z = raw_input()
if z == 'e' or z == 'E':
    print('The answer is %d'  %(y**x))
elif z == 'd' or z == 'D':
    print('The answer is %d'  %(y/x))
elif z == 'm' or z == 'M':
    print('The answer is %d'  %(y*x))
elif z == 'a' or z == 'A':
    print('The answer is %d'  %(y+x))
elif z == 's' or z == 'S':
    print('The answer is %d'  %(y-x))
elif z == 'mo' or z == 'Mo':
    print('The answer is %d'  %(y%x))
elif z == 'l' or z == 'L':
    print('The answer is %d'  %(math.log(x,y)))
elif z == 'r' or z == 'R':
    print('The answer is %d'  %(y**(1/x)))