我对编码很新,我想让我的计算器计算功率,但是如果输入的数字太高,程序将返回错误,说明数字太大。因此,我想这样做,如果用户输入的第二个数字等于或大于30,它将打印“数字太高”并让他们输入一个新数字。这是我的代码:
if choice == '5' and num2 >= '30':
print("Second number too high")
num2 = float(input("Enter second number: "))
当我运行它并输入30作为第二个数字输入时,我收到以下错误消息: Traceback(最近一次调用最后一次): 文件“python”,第41行,in 在'float'和'str'
的实例之间不支持TypeError:'> ='以下是我的计算器的所有代码:
import time
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def power(x, y):
return x ** y
print("Welcome to the Calculator App!")
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.To the Power of")
choice = input("Enter choice(1, 2, 3, 4 or 5):")
while choice not in ("1","2","3","4","5"):
print("Invalid Input")
choice = input("Enter choice(1, 2, 3, 4 or 5):")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '5' and num2 >= '30':
print("Second number too high")
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
print(num1,"**",num2,"=", power(num1,num2))
else:
print("Invalid input")
time.sleep(10)
答案 0 :(得分:0)
Python对数字使用不同的表示法(在本例中为浮点数)与字符串。像'30'
这样的字符串是用单引号('30'
)或双引号("30"
)编写的。 30
或30.0
等数字不带引号。尝试将数字与字符串进行比较将导致错误。这就是Python所说的TypeError: '>=' not supported between instances of 'float' and 'str'
尝试这样的事情:
if choice == '5' and num2 >= 30:
(无关评论:如果用户第二次输入的数字太大,会发生什么?考虑使用某种循环来保持请求输入,直到输入有效数字。)
答案 1 :(得分:0)
更改此if
声明
if choice == '5' and num2 >= '30':
print("Second number too high")
num2 = float(input("Enter second number: "))
到while
循环
像这样
while choice == '5' and num2 >= 30:
print "invalid input - enter a number < 30"
num2 = float(input("Enter 2nd number: "))
现在,您正在针对数值测试num2并重新请求num2的值,直到您收到低于30的值