Lesson 8 of 4020%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Input and Output
Learn how to get input from the user and print output to the console.
Input and Output
What You’ll Learn
You will learn how to make your programs interactive by getting input from the user and displaying output.
Printing Output (print)
We use the print() function to output data to the console.
print("Hello, World!")
print(100)
name = "Alice"
print("Hello", name)
Getting Input (input)
Python provides the input() function to read a line of text from standard input (the keyboard).
name = input("What is your name? ")
print("Nice to meet you, " + name + "!")
The Input Type Gotcha
The input() function always returns a string, even if the user types a number!
If you want to do math with user input, you must convert the string to a number using int() or float().
# Correct way to handle numeric input
age_text = input("How old are you? ")
age = int(age_text)
next_year = age + 1
print("Next year you will be", next_year)
Alternatively, do it on one line:
age = int(input("How old are you? "))
Common Mistakes
- Forgetting type conversion: If you write
age = input("Age: ")and then try to calculateage + 5, you will get a TypeError because you cannot add a string and an integer.