If input is empty or zero it should get None.
This is what has been attempted:
The int
is necessary.
number = int(input('Type an integer: ') or None )
number = number if number != 0 else None
print(number)
How to avoid this issue:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
CodePudding user response:
Try this code
Just change None
to '0'
in the line 1
So that, If the input is empty or zero, It is assigned as None
number = int(input('Type an integer: ') or '0' )
number = number if number != 0 else None
print(number)
Tell me if its not working...
CodePudding user response:
There are three distinct operations here:
- Read an input.
- Convert that input to an
int
, if possible, or0
if not. - Replace
0
withNone
.
Each of these should be done independently.
x = input("...")
try:
number = int(x)
except ValueError:
number = 0
if number == 0:
number = None
It's not clear why 0
is so special that it should be replaced with a value of a different type.
CodePudding user response:
You can use try-except
try:
number = int(input('Type an integer: '))
if number == 0:
number = None
except ValueError:
number = None
print(number)