如何输入和使用ValueError(Python 3.7)
这是我计算机科学课的代码。我添加了一个功能来确保用户不输入非int/float。我试图访问用户条目以重复它,因此它是这样的:如何输入和使用ValueError(Python 3.7),python,python-3.x,Python,Python 3.x,这是我计算机科学课的代码。我添加了一个功能来确保用户不输入非int/float。我试图访问用户条目以重复它,因此它是这样的: Enter your first number: > not_a_valid_float_or_int "not_a_valid_float_or_int" is not a valid number, try again. 因此,基本上我试图用用户输入的内容替换“您输入的内容” print("Hello!\n") while True: try:
Enter your first number:
> not_a_valid_float_or_int
"not_a_valid_float_or_int" is not a valid number, try again.
因此,基本上我试图用用户输入的内容替换“您输入的内容”
print("Hello!\n")
while True:
try:
firstnumber = float(input("Enter your first number:\n"))
except ValueError:
print("\nWhat you have entered is not a valid number, try again.")
else:
break
print()
while True:
try:
secondnumber = float(input("Enter your second number:\n"))
except ValueError:
print("\nWhat you have entered is not a valid number, try again.")
else:
break
print("\nThe first number is:", str(firstnumber).rstrip("0").rstrip(".") , "\nThe second number is:", str(secondnumber).rstrip("0").rstrip("."), "\nThe sum is:", str(firstnumber + secondnumber).rstrip("0").rstrip("."), "\nThe product is:", str(firstnumber * secondnumber).rstrip("0").rstrip("."))
非常感谢
大卫
请注意,我对编码场景非常了解。为了让您了解评论的含义
while True:
firstnumber_raw = input("Enter your first number:\n")
try:
firstnumber = float(firstnumber_raw)
except ValueError:
print("\n'" + firstnumber_raw "' is not a valid number, try again.")
else:
break
作为旁注,因为您标记了Python 3.7,所以f-string是您的朋友。将输入字符串作为变量存储在
try/except
块之外,然后try
使用float()
,如果捕获到错误,则可以在错误打印中使用该字符串。