Try-except or Exceptions in Python



我是编程新手,我正在努力让我的Try-except函数工作。我希望用户能够只使用数字写一个数字,当他们输入一个字母或符号时,我希望except语句开始。我该怎么办?非常感谢!

while True:
try:
x = int(input("Please write your phone number to receive a confirmation: "))

except: 
print("Obs!")
break

print("You did not write a real number : {0}".format(x))
print("No symbols or letters allowed!!")

您希望将所有这些警告打印放在异常处理程序中。假设您想要保持提示,直到输入一个数字,在成功转换后执行break

int失败时,跳过对x的赋值,其值在异常中不可用。因为您希望将错误的选择回显给用户,所以将文本值保存到一个中间变量中。

while True:
try:
answer = input("Please write your phone number to receive a confirmation: ")
x = int(answer)
break

except ValueError: 
print("Obs!")    
print("You did not write a real number : {0}".format(answer))
print("No symbols or letters allowed!!")

不需要使用try/except语句。一种更python化的方法是简单地将其包装在while语句中并使用x.s isnumeric()。这样做的好处是可以在

之后继续执行。
done = False
while not done:
x = input('Please write your phone number to receive a confirmation: ')
if x.isnumeric():
done = True
x = int(x)
else:
print("Obs!")    
print("You did not write a real number : {0}".format(x))
print("No symbols or letters allowed!!")
# anything else here

为什么你想要负数??它是一个电话号码,使用我的解决方案,您可以轻松地编辑它并添加条件。Try/except应该是一个回退,而不是默认值。

最新更新