Kahibaro
Discord Login Register

Converting input to numbers

Why input is text by default

When you use input() in Python, whatever the user types is returned as text, also called a string (str), even if it looks like a number.

age = input("How old are you? ")
print(age)
print(type(age))   # <class 'str'>

If you try to do math with this text directly, you’ll get errors or unexpected behavior. So you need to convert the text to a number.

Converting to integers with `int()`

Use int() when you expect whole numbers (no decimal point).

age_text = input("Enter your age: ")
age = int(age_text)          # convert text to an int (integer)
print(age + 1)               # now this is real math

You can also convert directly in one step:

age = int(input("Enter your age: "))
print("Next year you will be", age + 1)

Common valid integer inputs:

Invalid for int() (will cause an error):

If the text cannot be turned into an integer, Python raises a ValueError. Handling such errors is covered in the errors/debugging chapter; for now, just know that the input must look like a normal whole number.

Converting to decimal numbers with `float()`

Use float() if you expect decimal numbers, like prices, measurements, or averages.

price_text = input("Enter the price: ")
price = float(price_text)
print("Price with tax:", price * 1.2)

Valid float inputs:

Also invalid for float():

Again, if the text is not a valid decimal number, Python raises a ValueError.

Choosing between `int()` and `float()`

Ask yourself what kind of number makes sense:

Examples:

# Asking for a whole number
friends = int(input("How many friends do you have? "))
# Asking for a decimal number
temperature = float(input("What is the temperature in °C? "))

Combining input conversion with calculations

Here are some small examples that show why conversion is important.

Without conversion: string concatenation

x = input("Enter a number: ")   # suppose the user types 5
y = input("Enter another: ")    # suppose the user types 7
print(x + y)   # prints "57", not 12

x and y are strings, so + combines them as text.

With conversion: numeric addition

x = int(input("Enter a number: "))      # user: 5
y = int(input("Enter another: "))       # user: 7
print(x + y)   # prints 12

Or with decimal numbers:

length = float(input("Enter length in meters: "))
width = float(input("Enter width in meters: "))
area = length * width
print("Area:", area, "square meters")

Converting back to text for output

When printing results, Python can usually handle mixing types, but using string formatting (covered more in another subsection) is common. For now, remember:

age = int(input("Enter your age: "))
message = "You are " + str(age) + " years old."
print(message)

If you forget str(), this kind of concatenation will give an error.

Typical beginner mistakes with input conversion

  1. Forgetting to convert at all
   x = input("First number: ")
   y = input("Second number: ")
   print(x * y)   # error: can't multiply two strings
  1. Trying to convert something that isn’t numeric
   number = int(input("Enter a number: "))
   # user types: hello
   # ValueError: invalid literal for int() with base 10: 'hello'
  1. Using int() when the user might type decimals
   height = int(input("Enter your height in meters: "))
   # user types: 1.75  -> ValueError

If you allow decimals, use float() instead.

  1. Assuming commas are allowed in numbers
   value = float(input("Enter a decimal number: "))
   # user types: 3,5  -> ValueError
   # correct input: 3.5

Practical mini-examples

Add two numbers from the user

a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
result = a + b
print("The sum is", result)

Simple age check using conversion

age = int(input("Enter your age: "))
if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult yet.")

(Details of if and comparison operators are covered in the conditions chapter; here the focus is on int() converting the input so comparisons make sense.)


When reading user input, always ask: “Do I need this as a number?”
If yes, convert it with int() or float() before doing any calculations.

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!