while True:
num = input("pls type the number: ")
# check if it's int or string
number = int(num)
except ValueError:
print("error try again !!")
continue # if it was wrong go back
# check if it's even or odd
if number % 2 == 0:
result = number * 2
print("it's even" , number)
print("The End")
else:
result = number + 1
print("its odd",number)
print("The End")
break
SyntaxError: invalid syntax
怎么了 ?
你的
try...except
块的缩进有误。
except ValueError:
行需要与
number = int(num)
行缩进一致。
以下是已更正的代码:
while True:
num = input("pls type the number: ")
# 检查是否是整数或字符串
try:
number = int(num)
except ValueError:
print("error try again !!")
continue # 如果错误则返回
# 检查是偶数还是奇数
if number % 2 == 0:
result = number * 2
print("it's even" , number)
print("The End")
else:
result = number + 1
print("its odd",number)
print("The End")
break
此更正确保了
except ValueError:
块与
try
块正确关联,从而解决了语法错误。