How to Solve Python TypeError: int() argument must be a string, a bytes-like object or a number, not ‘NoneType’

by | Programming, Python, Tips

Introduction

The error TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' often occurs when dealing with user input or missing data in Python. This error occurs when you try to convert a None value into an integer, which Python cannot handle. In this post, we’ll explore an example and show you how to solve this issue efficiently.

Example

Let’s consider a scenario where you are processing user input from a form that is expected to return numbers. However, due to some missing input, you get a None value instead. Here’s a typical example:

# Function that simulates getting user input
def get_user_age(user_data):
    return user_data.get('age')  # May return None if 'age' is missing

# Simulate a user dictionary where 'age' field is missing
user_data = {'name': 'Alice'}

# Attempt to convert age to an integer
age = int(get_user_age(user_data))
print(f"User's age is: {age}")

Error Message

When you run the above code, you will encounter the following error:

TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'

In this case, since the key 'age' is missing from the user_data dictionary, the get_user_age() function returns None. The int() function cannot convert None into an integer, which leads to this error.

Solution

To handle this error, you need to check for None before passing the value to the int() function. This can be done by setting a default value or raising an informative error.

Solution 1: Provide a Default Value

In cases where a default value makes sense (e.g., 0 for missing age), you can check if the value is None and return the default.

def get_user_age(user_data):
    age = user_data.get('age')
    if age is None:
        return 0  # Provide default value if age is missing
    return int(age)

# Example usage
user_data = {'name': 'Alice'}  # 'age' is missing
age = get_user_age(user_data)
print(f"User's age is: {age}")  # Output: User's age is: 0

Here, if the 'age' key is missing, the code returns a default value of 0, preventing the error.

Solution 2: Validate and Raise an Error

You can raise a custom error message if you want to ensure that None is not accepted as valid input.

def get_user_age(user_data):
    age = user_data.get('age')
    if age is None:
        raise ValueError("Age is missing from user data")
    return int(age)

# Example usage
user_data = {'name': 'Alice'}  # 'age' is missing
try:
    age = get_user_age(user_data)
except ValueError as e:
    print(e)  # Output: Age is missing from user data

In this case, the code raises a ValueError when the 'age' key is missing, making it clear that the input is invalid.

Conclusion:

The error int() argument must be a string, a bytes-like object or a number, not 'NoneType' is common when working with missing or incomplete data. By ensuring you handle None values before converting them to integers, either by setting a default value or raising an error, you can easily resolve this issue and make your code more robust.

Congratulations on reading to the end of this tutorial!

For further reading on TypeErrors in Python, go to the articles:

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨