python计算器出错,我疯了

2024-03-29 12:57:49 发布

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

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

Tags: ortheansweryoulognumberforinput
3条回答

你必须这么做

z = raw_input()

同样输入在python2.x中以int的形式返回。所以使用raw_input读取str,然后像print('The answer is ' + y**x)一样到处输入print('The answer is ' + str(y**x))

您的代码有错误

  1. 使用raw\u input()获取字符串输入,而不是input()
  2. 使用int(raw_input())接受整数输入,这不是一个错误,但这是一个很好的实践。你知道吗
  3. 你试图用字符串除int。你知道吗
  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)))

这里有几个问题:

  1. z应该用^{}输入,而不是input。你知道吗
  2. 在除法的情况下,您将除法y/z,而不是y/x。你知道吗

相关问题 更多 >