我做的python计算器出错

时间:2016-03-25 11:45:05

标签: python python-2.7 calculator

我试图在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

3 个答案:

答案 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)

这里有几个问题:

  1. z应输入raw_input,而不是input
  2. 在除法案例中,您要划分y/z而不是y/x

答案 2 :(得分:1)

您的代码有错误

  1. 使用raw_input()获取字符串输入而不是input()
  2. 使用int(raw_input())来获取整数输入,这不是错误,但这是一种很好的做法。
  3. 你试图用字符串划分int。
  4. 您尝试连接字符串和整数。
  5. 您的代码应该是这样的。

    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)))