Python: Basic Input/Output
Watch this topic in 60 seconds
Free preview · Lesson 1
Understanding Python: Basic Input/Output
Python for Beginners: Talking to Your Computer with Input and Output (I/O)
Welcome, future coders! Imagine you have a new friend, and that friend is your computer. How do you talk to it? And how does it talk back to you? That’s exactly what we’re going to learn today with Python: Basic Input and Output (often called I/O for short).
What is Input and Output (I/O)?
Think of I/O like having a conversation. When you speak, you are giving Output. When someone listens to you and then replies, they are giving you Input. In the world of computers and programming, it's very similar:
- Output: This is when your Python program shows information to you. It could be text on the screen, a number, or even an error message. It's the computer talking!
- Input: This is when you give information to your Python program. You might type your name, a number, or a command using your keyboard. It's you talking to the computer!
Analogy Time! Imagine a vending machine. When you press the button for a snack and insert money, that's your Input. When the machine drops the snack down for you, that's its Output. Without input, the machine wouldn't know what to give you. Without output, you wouldn't get your snack!
Output: Making Your Python Program Talk! (`print()`)
The most common way for your Python program to "talk" and show you things is by using a special command called print().
The `print()` Function: Your Program's Loudspeaker
The print() function is like your program's loudspeaker or a message bubble. Whatever you put inside its parentheses `()` will be shown on the screen.
1. Printing Simple Text (Strings)
If you want to print words or sentences, you need to put them inside quotation marks (" " or ' '). These are called strings in programming.
print("Hello, world!")
When you run this code, your computer screen will show:
Hello, world!
See? Your program just said "Hello, world!"
print('My name is Python.')
print("I love to code!")
Output:
My name is Python.
I love to code!
2. Printing Numbers
You can also print numbers directly without quotes.
print(123)
print(3.14)
Output:
123
3.14
3. Printing Variables
Remember variables? They are like labeled boxes that hold information. You can print the content of a variable.
name = "Alice"
age = 14
print(name)
print(age)
Output:
Alice
14
4. Combining Text and Variables
Often, you'll want to combine descriptive text with the values stored in your variables. There are a few ways to do this, but for foundational learning, let's look at two simple methods:
Method A: Using a Comma (`,`)
You can separate items you want to print with a comma. Python will automatically put a space between them.
name = "Charlie"
age = 13
print("Hello, my name is", name, "and I am", age, "years old.")
Output:
Hello, my name is Charlie and I am 13 years old.
Method B: Using Plus (`+`) for Strings (Concatenation)
You can "add" strings together using the `+` sign. This is called concatenation. It literally sticks the strings together.
greeting = "Hi there!"
your_name = "Jamie"
full_message = greeting + " My name is " + your_name + "."
print(full_message)
Output:
Hi there! My name is Jamie.
Important Note: When using `+` with strings, you have to add the spaces yourself! If you tried `greeting + your_name`, it would output `Hi there!Jamie` which doesn't look right.
You can only use `+` to join strings with other strings. If you want to combine a string and a number using `+`, you'll have to convert the number to a string first using `str()`. We'll explore this more later!
input() function is how your program waits for you, the user, to type something and press Enter.The `input()` Function: Your Program's Ear
When Python sees an input() command, it pauses the program, displays a message (if you provide one), and waits for you to type something. Whatever you type until you press Enter, Python takes that information and can store it in a variable.
1. Getting Simple Text Input
print("What is your name?")
user_name = input()
print("Nice to meet you,", user_name + "!")
When you run this:
What is your name?
The program waits. You type `Alex` and press Enter:
What is your name?
Alex
Nice to meet you, Alex!
Notice how what you typed (`Alex`) was stored in the `user_name` variable!
2. Adding a Prompt Directly to `input()`
You can make your `input()` function even tidier by putting the question you want to ask directly inside its parentheses. This text is called a "prompt."
favorite_color = input("What is your favorite color? ")
print(favorite_color, "is a lovely color!")
When you run this:
What is your favorite color? Red
Red is a lovely color!
Don't forget the space at the end of your prompt `("What is your favorite color? ")`! It makes the user's input look much neater on the screen.
3. The Big Secret About `input()`: It Always Returns Text!
This is super important! No matter what you type into `input()`, even if you type a number like `5`, Python always treats it as a string (text). It's like putting a "text" label on everything that comes out of the input box.
Analogy: Imagine you have a special scanner that always labels everything it scans as "fruit," even if you scan a shoe. If you later want to treat the scanned item as a "shoe," you need to change its label.
Let's see what happens if we forget this:
num1 = input("Enter a number: ") # Let's say you type 5
num2 = input("Enter another number: ") # Let's say you type 3
sum_numbers = num1 + num2
print("The sum is:", sum_numbers)
What do you expect? `8`? Let's see the actual output:
Enter a number: 5
Enter another number: 3
The sum is: 53
Whoa! Why `53` and not `8`? Because `num1` was the string `"5"` and `num2` was the string `"3"`. When you use `+` with strings, Python performs concatenation (sticks them together), not mathematical addition!
Type Conversion: Changing the Label (`int()`, `float()`, `str()`)
To fix the problem above, we need to change the "label" of our input from a string to a number. This is called type conversion or type casting.
`int()`: To Whole Numbers
If you want to treat the input as a whole number (an integer), you use `int()`.
num_string = "10"
num_integer = int(num_string)
print(num_integer + 5) # Now it works!
Output:
15
`float()`: To Decimal Numbers
If you want to treat the input as a number with a decimal point (a floating-point number), you use `float()`.
price_string = "19.99"
price_float = float(price_string)
print(price_float * 2)
Output:
39.98
`str()`: To Strings (when you need to print numbers with `+`)
Sometimes you have a number and you need to combine it with text using the `+` operator. In this case, you convert the number to a string using `str()`.
score = 100
message = "Your high score is: " + str(score) + " points!"
print(message)
Output:
Your high score is: 100 points!
Fixing Our Addition Problem
Now let's fix that earlier addition example:
num1_str = input("Enter a number: ") # User types 5, num1_str is "5"
num2_str = input("Enter another number: ") # User types 3, num2_str is "3"
num1_int = int(num1_str) # Convert "5" to 5
num2_int = int(num2_str) # Convert "3" to 3
sum_numbers = num1_int + num2_int # Now 5 + 3 = 8
print("The sum is:", sum_numbers)
Or, even more efficiently, you can convert it right when you get the input:
num1 = int(input("Enter a number: ")) # Get input, then convert it to int
num2 = int(input("Enter another number: ")) # Get input, then convert it to int
sum_numbers = num1 + num2
print("The sum is:", sum_numbers)
This will now correctly output:
Enter a number: 5
Enter another number: 3
The sum is: 8
Success! Your program can now properly listen to numbers and do math with them.
Putting It All Together: A Simple Interactive Program
Let's make a small program that asks for your name and your age, then tells you how many years until you're 20!
print("Hello there!")
# Get the user's name
name = input("What's your name? ")
# Get the user's age and convert it to an integer right away
age = int(input("How old are you? "))
# Calculate years to 20
years_to_20 = 20 - age
# Print a personalized message
print("Nice to meet you, " + name + "!")
print("You are " + str(age) + " years old.") # Convert age back to string for + concatenation
print("You have " + str(years_to_20) + " years until you are 20.") # Convert years_to_20 to string
print("Keep coding!")
Example Run:
Hello there!
What's your name? Sam
How old are you? 14
Nice to meet you, Sam!
You are 14 years old.
You have 6 years until you are 20.
Keep coding!
Isn't that neat? You've just created a program that interacts with the user!
Conclusion
Congratulations! You've learned the fundamental building blocks of how your Python programs can communicate with the outside world. The print() function allows your program to show information, and the input() function allows your program to receive information from the user. Remember the crucial step of converting input from strings to numbers (using `int()` or `float()`) when you need to perform calculations. Mastering I/O is a big step towards writing useful and interactive programs!
Keep learning, free
Create a free Syllabax account to unlock practice questions and games for this topic.
Visual Learning Enhanced! 🚀
To help you master this topic, we use Advanced Syllabax AI to generate detailed diagrams and visual models.
Note on Visuals: The AI sometimes makes spelling errors in image labels. Please refer to the lesson text for the correct terminology.