How to Fix "ValueError: invalid literal for int() with base 10: '' Error in Python?

python

The "ValueError: invalid literal for int() with base 10: ''" error in Python occurs when you try to convert an empty string or a non-numeric string into an integer using the int() function. To fix this error, you can use the following methods:

  1. Check for empty or non-numeric strings:

You can check if the string is empty or non-numeric before trying to convert it into an integer. You can use the isnumeric() function to check if the string is numeric or not.

Example:

num = input("Enter a number: ")

if num.isnumeric():
  num = int(num)
  print(num)
else:
  print("Invalid input")
  1. Use Try-Except block:

You can use a try-except block to catch the ValueError. In the except block, you can print an error message or perform any other action.

Example:

num = input("Enter a number: ")

try:
  num = int(num)
  print(num)
except ValueError:
  print("Invalid input")

In both examples, we are checking if the input is numeric or not, and if it is not numeric, we are printing an error message.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?