我是编程新手。 基本思想是,当用户输入数据时,代码应该检查数据。如果数据不是数字。它应该显示"请仅输入数字!"而不是显示价值误差。消息。
number1 = int(input("Enter "))
try:
temp = number1/1
except ValueError:
msg = "Please enter only numbers!"
print(msg)
但是代码没有按预期工作并显示出来 错误:
Traceback (most recent call last):
File "test.py", line 1, in <module>
number1 = int(input("Enter "))
ValueError: invalid literal for int() with base 10: 'aa'
请告诉我哪里出错了?
答案 0 :(得分:0)
try
仅在其范围内捕获错误,在代码中引发错误的行不在try
块中,执行此操作:
try:
number1 = int(input("Enter "))
temp = number1/1
except ValueError:
msg = "Please enter only numbers!"
print(msg)