- Understand that a variable is a container for storing data.
- Use the
input()function to get information from the user. - Use modern f-strings to combine text and variables for clear output.
Variables: The Brain of Your Program
A program isn't very smart if it can't remember things. A variable is like a labeled box in the computer's memory where you can store a piece of information. We assign a value to a variable using the equals sign (=).
# variable_name = value
user_name = "Ada Lovelace"
user_age = 29
To make our programs interactive, we need to get information from the user. We do this with the input() function. The text you put inside the parentheses is the prompt the user will see.
Displaying Variables with Text: The Power of f-strings
Once you have data in a variable, you'll want to display it in a sentence. The "old way" was to combine everything with + signs. It works, but it can get clumsy and error-prone.
# The "Old Way" - notice the extra spaces needed inside the quotes.
print("My favourite food is " + favourite_food + "!")
The modern, cleaner, and better way is to use an f-string. You just put an f before the opening quote and then place your variable names directly inside curly braces {}.
Live Example: See it in Action!
The code below is a live, interactive example. Click the Run ▶ button to see how it works. When it asks for your name, type it in and press Enter. Then, try changing the code directly in the window and running it again!
We will use f-strings for all our output. They are easier to read, less error-prone, and the standard in modern Python code.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.