If input is empty then assign None

Viewed 246

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'
3 Answers

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)

Explanation:

The first line is asking for the user input

And if the user input is an empty string (i.e., '') Python also sees an empty string as a boolean object (which is actually False for an empty string)

As the first case is False (i.e., the empty user input) according to Python, it automatically assigns the other value to the parameter of the int function as its because of the or keyword

Tell me if its not working...

You can use try-except

try:
    number = int(input('Type an integer: '))
    if number == 0:
        number = None 
except ValueError:
    number = None
print(number)

There are three distinct operations here:

  1. Read an input.
  2. Convert that input to an int, if possible, or 0 if not.
  3. Replace 0 with None.

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.

Related