Python fundamentals
Input and type conversion
Ask for input, understand that input() returns text, and convert a whole-number response with int().
Lesson 11 of 63
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Beginner
On this page4 sections
The input() function displays a prompt and waits for the user to type a response and press Enter. It returns a string, even when the user types digits.
name = input("Your name: ")
print(f"Hello, {name}!")Your name: Sam Hello, Sam!
Convert numeric input
Use int() when you expect a whole number. The example asks for a positive whole number such as 3. If the response is not a valid integer, Python raises ValueError; handling that case comes later in the roadmap.
sessions_text = input("How many sessions? ")
sessions = int(sessions_text)
print(f"You planned {sessions + 1} sessions if you add one more.")How many sessions? 3 You planned 4 sessions if you add one more.
You can also convert a valid decimal response with float(), such as float("1.5"). Choose int() for the whole-number inputs in the chapter project.
Why this works
input() always returns text. Convert that text only when you need numeric work, and store the converted value separately when it helps you inspect the result. int() accepts a valid whole-number string such as "3" but raises ValueError for text such as "three".
Practice
Ask for a name and a positive whole number of study sessions. Convert the session response with int(), then print an f-string containing both values. Run the program twice with different answers.
What type does input() return when someone types 3?
Reveal answer
It returns the string "3". Use int() to turn it into the integer 3 before arithmetic.
Try another case
Why does int(input("Sessions: ")) need a valid whole-number response?
Check your answer
Reveal answer
input() returns a string, and int() must be able to parse that string as an integer before arithmetic can use it.
Your progress
Reveal the check answer or reach the end to complete this lesson.