【发布时间】:2022-01-10 15:36:18
【问题描述】:
如果number 变量是整数,则等于零的输入应变为“无”,任何其他值应保持不变。下面的代码有效,但出于学习目的,我想看看如何以不同的方式实现?
while True:
try:
number = int(input('Type an integer: '))
if type(number) == int: # If the value is an integer, it proceeds.
if number == 0: # Here is another 'if' in case the value is zero which has to turn to the 'None' value
number = None
break
else: # For any other case it should just keep the value from the input above
break
except ValueError:
print("Type an integer")
print(number)
【问题讨论】:
-
有无数种不同的方式来实现这一目标。例如,您可以反转
if语句的条件并交换if和else部分。 -
你不需要 `if type(number) == int' 因为你的异常已经处理了
标签: python if-statement while-loop