If the number
variable is an integer, an input that is equal to zero should become 'None' and any other value should stay as is. The code below works but for learning purposes I would like to see how this can be achieved differently?
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)
CodePudding user response:
Try
number = number if number != 0 else None
CodePudding user response:
No need to check for the type(number) == int
because you already passed it to int
, which did not raise a ValueError
. If this line of code is reached, it must be an int already at this point.
Breaking logic is often hard to follow. IMO this logic would be better suited to a method where you return
it, making it more clear what the result of the loop will eventually be.
The prompt for incorrect text is confusing, you should comment that it was incorrect.
The return logic could use an if/else expression to reduce the code.
def ask_for_int():
while True:
try:
number = int(input('Type an integer: '))
return None if number == 0 else number
except ValueError:
print("Invalid input. Try again")
print(ask_for_int())