Taking Input and Type Conversion

40 min read Getting Started with Python

This is a free course. Log in to run the code exercises and track your progress.

Taking Input and Type Conversion

input() waits for the user to type a line and returns it as a string, always. Even if the user types 25, you get the text "25". Adding two such strings joins them: "25" + "5" is "255".

To do arithmetic, convert the text with int() or float(). This is called type conversion (or type casting). str() converts a number back to text.

a = int(input("First number: "))
b = int(input("Second number: "))
print("Sum:", a + b)
price = float(input())   # 99.5 stays a decimal number

To read several values typed on one line, split the line into words first: x, y = input().split(), then convert each one. map(int, input().split()) converts all of them in one go.

Python exercise

Read two whole numbers, each on its own line, and print their sum as a number (not the two strings joined together).

a = input()
b = input()
print(a + b)  # this joins the text: convert a and b first

Log in to edit and run this code.