Python Input-Output
Talking to Your Program: Understanding Inputs and Outputs
Programs often need to interact with the world outside of their code. They might need to show results to a user, display messages, or get information from the user, like a name or a choice.
How does a program communicate? It uses Input and Output.
- Output is when the program shows information to you (usually on the screen).
- Input is when the program gets information from you (usually from the keyboard).
Without Input and Output, your program would run silently and couldn't respond to anything you do, making it hard to use!
Output: Showing Information with print()
The main way to show information from your Python program to the user is using the built-in print()
function.
Basic Printing
You can print text directly by putting it inside quotes within the parentheses of print()
.
print("Hello from Python!")
print("This message appears on the screen.")
Each print()
call usually puts the output on a new line.
Printing Variables
You can print the value that a variable is currently pointing to.
score = 150
player_name = "Hero"
print(score) # Output: 150
print(player_name) # Output: Hero
Printing Multiple Items
You can print several things at once by separating them with commas inside the print()
parentheses. By default, print()
puts a space between each item.
item = "Sword"
price = 75
print("Item:", item, "costs", price, "gold.")
# Output: Item: Sword costs 75 gold.
Controlling Output Appearance (sep
and end
)
The print()
function has special options you can use to control how things look.
-
The
sep
(separator) option lets you choose what goes between items printed on the same line. The default is a space (' '
).print("Day", "Month", "Year", sep="/") # Output: Day/Month/Year print("Email", "Address", sep="@") # Output: Email@Address
-
The
end
option lets you choose what goes at the very end of the printed line. The default is a newline character (\n
), which makes the nextprint()
start on a new line. Settingend
to something else, like an empty string""
or a space, keeps the next print on the same line.print("Loading...", end="") # Prints "Loading..." but stays on the same line print("Done!") # Prints "Done!" immediately after the last print # Output: Loading...Done! print("Part 1", end=" ") # Prints "Part 1" followed by a space print("Part 2") # Prints "Part 2" on the same line after the space # Output: Part 1 Part 2
Formatting Output with f-strings
f-strings (formatted string literals) are a very popular and easy way to build strings that include variable values or expressions. We saw them briefly in the Variables article. You start the string with f
before the quotes and put variable names (or code) inside {}
.
item = "Shield"
defense = 10
print(f"Found a {item} with {defense} defense points.")
# Output: Found a Shield with 10 defense points.
# You can even do simple formatting inside the {}
price = 99.5
print(f"Price: ${price:.2f}") # Formats price to show 2 decimal places
# Output: Price: $99.50
f-strings are great for making your output messages clear and easy to read.
Input: Getting Information from the User with input()
To get information from the user, you use the built-in input()
function. When Python reaches an input()
line, it stops and waits for the user to type something on the keyboard and press the Enter key.
Basic Input
The input()
function reads the text the user types and returns it as a string.
print("Please tell me something:")
user_text = input() # Program stops here and waits
print("You said:", user_text)
Adding a Prompt Message
It's a good idea to tell the user what you want them to type. You can do this by putting a message (a string) inside the parentheses of input()
. This message is shown to the user before they type.
user_name = input("What is your name? ") # Message is shown to the console
print(f"Hello, {user_name}!")
Important: input()
Always Returns a String!
This is a very important point for beginners. The input()
function always reads whatever the user types as a string (str
) object. It does not matter if they type letters, numbers, or symbols – it's all captured as text.
Look at this example where a user types numbers:
# Let's say the user types '5' when asked
first_number_str = input("Enter the first number: ") # user types 5
# first_number_str is now the string "5"
# Let's say the user types '3' when asked
second_number_str = input("Enter the second number: ") # user types 3
# second_number_str is now the string "3"
# If you try to use '+' here:
# print(first_number_str + second_number_str)
# What do you think this prints? "5" + "3" results in string concatenation!
# Output would be: 53 (NOT 8)
If you want to perform mathematical operations, you cannot use the strings returned by input()
directly. You need to convert them into a number type first. This leads us to the need for Type Conversion, which is covered in the next article.
Putting Inputs and Outputs Together
Let's see a simple program that uses both input and output, correctly handling numbers typed by the user.
# 1. Use input() to get text from the user
age_as_text = input("Please enter your age: ") # user types '25' (or whatever)
# age_as_text variable now points to the string object, e.g., "25"
# 2. Convert the string input to a number type (int)
# We need int() from the next article!
age_as_number = int(age_as_text)
# age_as_number variable now points to the integer object, e.g., 25
# 3. Use operators to do something with the number
age_in_10_years = age_as_number + 10
# 4. Use print() and f-string to show the result
print(f"In 10 years, you will be {age_in_10_years} years old.")
# If user typed 25, Output: In 10 years, you will be 35 years old.
This example shows a common pattern: get input as text, convert it to the needed type, process it, and print the result.
Common Issues with Inputs and Outputs
- Forgetting that
input()
always returns a string, leading to errors or unexpected behavior when trying to use the input as a number or other type without converting it first. - Not providing a clear message in
input()
, leaving the user confused about what they should type. - Syntax errors like forgetting quotes around text, missing parentheses, or incorrect f-string format.
Conclusion
Being able to get information from the user and show results is vital for making your programs interactive and useful.
- You learned that Output is showing information, primarily using the
print()
function. You can control how items are displayed on a line usingsep
andend
, and format text easily with f-strings. - You learned that Input is getting information from the user via the keyboard, using the
input()
function. - Crucially, you learned that
input()
always returns a string. This means you often need to change its type if you want to perform operations (like math) that require a different data type.
Understanding Input and Output, and remembering that input()
requires type conversion for non-string data, is a key step in writing programs that can talk to users.
The next step in building interactive programs is mastering Type Conversion, so you can easily change data from one type to another, like turning a string input "123" into the number 123.