28
loading...
This website collects cookies to deliver better user experience
int()
function with string argument which Python cannot parse and throws ValueError: invalid literal for int() with base 10: ”number= input("What is your weight:")
kilos=int(number)
print ("The weight of the person is:" + str(kilos))
# Output
What is your weight:55.5
Traceback (most recent call last):
File "c:\Projects\Tryouts\listindexerror.py", line 2, in <module>
kilos=int(number)
ValueError: invalid literal for int() with base 10: '55.5'
int()
function uses the decimal number system as base conversion, meaning base=10 is the default value for transformation. Therefore it can only convert the string representation of int, not the decimal or float or chars.float()
method, parse the decimal digits, and convert them again into an integer, as shown below.number= input("What is your weight:")
kilos=int(float(number))
print ("The weight of the person is:" + str(kilos))
# Output
What is your weight:55.5
The weight of the person is:55
isdigit()
method, which returns true in case of a numeric value and false if it’s non-numeric.number= input("What is your weight:")
if number.isdigit():
kilos=int(float(number))
print ("The weight of the person is:" + str(kilos))
else:
print("Error - Please enter a proper weight")
# Output
What is your weight:test
Error - Please enter a proper weight
try except
number= input("What is your weight:")
try:
kilos=int(float(number))
print ("The weight of the person is:" + str(kilos))
except:
print("Error - Please enter a proper weight")
# Output
What is your weight:test
Error - Please enter a proper weight
float()
method to convert entered decimal input and then use the int()
method to convert your number to an integer. Alternatively, you can use the*isdigit()
* method to check if the entered number is a digit or not, and the final way is to use try/except
to handle the unknown errors.