(向下滚动查看更改)
我知道很多人可能已经问过这个,但我已经看了几个解决其他人问题的方法,而且我尝试过的任何问题都没有用。 我对编码很新,我必须为学校编写计算器代码。我有以下代码接受来自用户的数字输入:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
当我输入一封信时,我收到以下错误消息:
追踪(最近一次通话): 文件“python”,第40行,in ValueError:无法将字符串转换为float:'d'
有人可以帮助我做到只接受号码吗?这是我的其余代码:
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!\n")
print("Select operation.\n")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.To the Power of\n")
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: "))
while choice == '5' and num1 >= 1000000000:
print("\nFirst number too high\n")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
while choice == '5' and num2 >= 30:
print("\nSecond number too high")
num2 = float(input("Enter second number: "))
while choice == '4' and num2 == 0:
print("\nCannot divide by zero")
num2 = float(input("Enter second number: "))
if choice == '1':
print(" ")
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(" ")
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(" ")
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(" ")
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
print(" ")
print(num1,"**",num2,"=", power(num1,num2))
else:
print("\nInvalid input")
time.sleep(10)
这是我现在该部分的代码:
num1 = float(input("Enter first number: "))
while True:
try:
num1 = float(input("Enter first number: "))
except ValueError:
print("Please enter only a number")
continue
else:
break
当我运行并故意输入字母g时,我收到以下错误消息:
Traceback (most recent call last):
File "python", line 32 in <module>
ValueError: could not convert string to float: 'g'