0

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.

1 Answer 1

0

It's not an Apple question. Nevertheless it's always good idea to use Python built-in help:

>>> help(int)
Help on class int in module builtins:

class int(object)
 |  int([x]) -> integer
 |  int(x, base=10) -> integer
 |
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating-point
 |  numbers, this truncates towards zero.
 |
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
/.../

To pinpoint: If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base

Simple test:

>>> int("2.5")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2.5'
>>> int("2")
2

Line #2 float is converted into int, on line #6 string 2.5 (which doesn't represent integral literal) is attempted to convert.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.