Course contentsShow
← Python
Lesson 51 of 1,0601. Foundations and EnvironmentFree lesson

Converting Input Types for Mathematical Operations

Learners will be able to cast string-based input into numeric types to perform calculations and process user-provided data effectively.

In this lesson, you will learn how to bridge the gap between user-provided text input and mathematical calculations by converting string data into numeric types.

The Input Problem

When you use the input() function, Python captures everything the user types as a string (text), even if the user types a number like "42". If you try to perform arithmetic directly on that input, such as input() + 10, Python will raise a TypeError because you cannot add an integer to a string.

To perform math, you must first "cast" (convert) the string into a numeric type, such as an int for whole numbers or a float for numbers with decimals.

Performing the Conversion

You can wrap the input() function inside the int() or float() constructor to handle this conversion immediately.

# Capturing input and converting to an integer
age_input = input("Enter your age: ")
age = int(age_input)

# Now we can perform math
next_year = age + 1
print(f"Next year you will be {next_year}.")

If you expect the user might enter a decimal, use float() instead:

# Capturing input and converting to a float
price = float(input("Enter the item price: "))
total = price * 1.05  # Adding 5% tax
print(f"The total price with tax is {total}.")

Why This Matters

Computers treat "5" and 5 as fundamentally different objects. The string "5" is just a sequence of characters, while the integer 5 is a value that supports arithmetic operations. By converting the type, you enable your program to transform raw, static text into dynamic, processed data. Always remember to convert your data before applying operators like +, -, *, or / to ensure your mathematical logic functions as intended.

Key Takeaway: Because input() always returns a string, you must use int() or float() to convert that text into a number before you can perform any mathematical calculations.