Sample Header Ad - 728x90

Python 3 - problem converting keyboard input to integer

0 votes
1 answer
37 views
I'm having a problem using the int() function on a user input from the keyboard in Python 3 (latest version from website). The actual program will perform various numerical calculations, but I have written a short test program that shows the problem. The int() function works fine for values embedded in the code, but crashes if the same number/format is entered via the keyboard. 1. dummy_num = (2.5) #just an example float number 2. dummy_num = int(dummy_num) #converts 2.5 to integer 2 3. print (f"{dummy_num}") #verifies result of "2" 4. variable_test = input ("type 2.5 please:") 5. print (f"{variable_test}") #verifies 2.5 is actually entered 6. variable_test = int(variable_test) The program runs as expected for lines 1 to 5. If 2.5 is entered via the keyboard in line 4, line 5 prints 2.5, but then line 6 crashes the program. An error message is generated as follows: variable_test = int(variable_test) ValueError: invalid literal for int() with base 10: '2.5' I don't understand why the int() function works fine for the value "2.5" in line 2, but crashes in line 6 - even though line 5 shows that the number entered is indeed 2.5 and the same program instruction works fine in line 2. Sorry if this is a newbie error, but I have run out of ideas. Note that I put a few #comments in the above code just for the purpose of this question.
Asked by Cliff Merry (3 rep)
Mar 31, 2025, 10:05 AM
Last activity: Mar 31, 2025, 11:44 AM