我试图在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
答案 0 :(得分:1)
你必须做
z = raw_input()
同样输入在int
中以python2.x
的形式返回。因此,请使用raw_input
作为str
,然后将所有地方print('The answer is ' + y**x)
改为print('The answer is ' + str(y**x))
答案 1 :(得分:1)
这里有几个问题:
z
应输入raw_input
,而不是input
。y/z
而不是y/x
。答案 2 :(得分:1)
您的代码有错误
您的代码应该是这样的。
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)))