How to Fix: ValueError: invalid literal for int() with base 10

3D illustration of a text string failing to fit into an integer slot, representing a Python ValueError.

Encountering a ValueError: invalid literal for int() can be a bit confusing at first. This error is a mouthful, but it’s actually very simple. It means: “You tried to turn a string into an integer, but the string didn’t look like a whole number”. When This Error appears, it usually indicates a conversion problem.

The Cause

You are using the int() function on a string that contains letters, special characters, or even a decimal point, which can trigger a specific error known as ValueError with an invalid integer literal.

Problem Code 1 (Letters):

val = int("hello")
# CRASH! 'hello' is not a number.

Problem Code 2 (Empty String):

user_input = input("Enter a number: ") # User just hits ENTER
val = int(user_input)
# CRASH! An empty string "" is not a valid number.

Problem Code 3 (Decimals – TRICKY!):

val = int("12.5")
# CRASH!

Wait, why? 12.5 is a number! Yes, but it’s not an integer (whole number). The int() function is strict. It only wants whole numbers. Attempting to use it incorrectly can result in an invalid attempt to turn the string into an integer.

The Fixes

Fix 1: For Decimals, use float() first

If your string might have a decimal, turn it into a float first. You can then turn that float into an int if you want to round it down. This approach helps prevent encountering a ValueError that suggests an invalid literal for int().

val = float("12.5") # Works! val is 12.5
val_int = int(val)  # Works! val_int is 12

Fix 2: Use try/except for User Input

Never trust user input. Always wrap it in a try/except block to avoid instances that lead to ValueError indicating an invalid int literal. In other words, use try/except for error handling when converting a string to an integer.

user_input = input("Enter a whole number: ")
try:
    val = int(user_input)
    print(f"Success! You entered {val}")
except ValueError:
    print("That was not a valid whole number!")

This prevents your programme from crashing if the user types “ten” instead of “10”.

Similar Posts

Leave a Reply