Table of Contents
Variables are the building blocks of every Python program. They allow you to store, reference, and update data during code execution. Understanding how variables work - how to create them, assign values, and use them in expressions - is essential for writing even the simplest scripts. With variables, you can turn hardcoded programs into flexible tools that interact with user input, make decisions, and adapt to changes. In this practice section, you’ll work with numbers, text, and basic operations to reinforce your understanding of variable assignment and manipulation.
Take your time with each exercise - variables may seem simple, but building a solid foundation here will save you time and confusion later.
What you should know before starting:
- How variables work in Python
- Basic syntax and indentation
- Working with numbers and strings
-
Using
input()
andprint()
functions - Naming rules (identifiers, lowercase/uppercase, no reserved keywords)
Practice in Variables for Beginner Level
Variables may be easy to create, but using them correctly in small programs takes practice. These beginner tasks will help you get comfortable with assigning values, using descriptive variable names, and combining them in expressions. You’ll also practice simple input/output to see how values can be entered by the user and processed by your program. These tasks are the first step in learning to think in variables instead of hardcoded values. Pay attention to how variables are updated and reused - this is where programming begins to feel dynamic and powerful.
1. Personal Info Card
Write a program that asks the user for their name and city of residence. Then, store the values in two separate variables and print a sentence like “Olivia lives in Berlin”. Your output should reflect the values entered by the user.
What this Task Teaches
This task helps you understand how to assign multiple inputs to different variables and combine them in a formatted output. It also trains you to use variable names that reflect their purpose.
Hints and Tips
- Use
input()
to collect name and city from the user. - Assign each input to a separate variable.
- Use
print()
with anf-string
or string concatenation to display the final message.
Common Mistakes
- Using one variable for both inputs: If you overwrite a variable, the previous value is lost. Use one variable for the name and another for the city.
- Forgetting to include both variables in the output: Double-check that your print statement includes both the user’s name and their city.
- Mixing up variable names: Make sure the names match exactly when using them -
City
andcity
are different. - Hardcoding values instead of using variables: The point is to work with what the user inputs, not predefined strings.
- Poor formatting: Watch spacing and punctuation to keep your output clean and readable.
Step-by-Step Thinking
Think of this as filling out a digital contact form and then summarizing it in one sentence.
- Ask the user for their name using
input()
- Ask the user for the city where they live
- Store each answer in its own variable
- Create a sentence combining the two values using
print()
- Make sure the sentence is grammatically correct and includes both values
How to Make it Harder
- Add a third question about the user’s profession.
- Capitalize the city name using
.title()
. - Allow the user to re-enter values if any field is left blank.
2. Simple Math Tracker
Ask the user to enter two numbers. Store them in separate variables, add them together, and display the result with a clear message like “The total is 17”. Use meaningful variable names and keep your code clean and readable.
What this Task Teaches
This exercise shows how to store numeric data in variables and perform arithmetic operations on them. It also strengthens your understanding of type conversion and result formatting.
Hints and Tips
- Use
input()
andint()
to collect and convert numbers. - Assign each number to a separate variable.
- Add the numbers and store the result in another variable.
- Display the result using
print()
.
Common Mistakes
- Forgetting to convert input to numbers: If you try to add two strings, you’ll get concatenation, not numeric addition.
- Reusing variable names: Be careful not to overwrite your input variables before calculating the sum.
- Inconsistent formatting: Output like “Thetotalis17” is hard to read. Use spaces or string formatting.
- Using vague variable names: Avoid names like
a
andb
. Usefirst_number
,second_number
, etc. - Missing a print statement: Make sure the result actually shows up - don’t forget the output step!
Step-by-Step Thinking
Treat this task like a calculator: input two values, compute, and show the result. Think clearly through each phase.
- Ask the user to enter the first number
- Convert the input to an integer and store it in a variable
- Repeat the process for the second number
- Add both numbers and store the result in a new variable
- Print the final result in a full sentence
How to Make it Harder
- Calculate and display the average of the two numbers.
- Allow decimal inputs using
float()
instead ofint()
. - Print a breakdown: “8 + 9 = 17” instead of just the result.
Practice in Variables for Intermediate Level
At the intermediate level, we begin to explore how variables interact with logic and control flow. You’ll now start using variables not just to store input, but to modify, compare, and make decisions based on them. These tasks go beyond simple assignments - you’ll write programs that track progress, apply conditions, and simulate small real-world systems. A strong grasp of variables at this stage will make it much easier to understand loops, functions, and data structures later on. These exercises are all about building confidence in how values move and change throughout a program. Write your code with clear logic, meaningful variable names, and consistent formatting.
1. Budget Reminder
Write a program that asks the user how much money they have and how much they plan to spend today. Store both values in variables. Then calculate the difference and display a message like “You have 12 dollars left”. Make sure to handle the case when the user spends more than they have.
What this Task Teaches
This task focuses on using numeric variables in calculations and applying conditional logic to show different outcomes. You’ll also practice naming and updating variables based on user input.
Hints and Tips
- Use
int()
orfloat()
to convert the user’s input to numbers. - Calculate the difference with subtraction.
- Use
if
statements to check whether the result is positive or negative. - Use separate messages for each case.
Common Mistakes
- Using strings for arithmetic: Remember to convert input to numbers before calculating. Otherwise, subtraction will fail.
- Incorrect subtraction order: Don’t mix up
spending - money
andmoney - spending
. The meaning changes! - Not handling overspending: The program should display a warning if the user tries to spend more than they have.
- Hardcoding output: Always calculate the difference dynamically, based on what the user enters.
- Inconsistent formatting: Use spaces, punctuation, and clean output messages to keep it readable.
Step-by-Step Thinking
Think of this like a simple money tracker. The logic follows a clear flow from input to decision.
- Ask the user how much money they have and store it in a variable
- Ask how much they want to spend and store that too
- Subtract spending from available money and store the result
- Use
if
to check if the result is negative or positive - Print a message based on the result (“You have X left” or “You are short by Y”)
How to Make it Harder
- Round the output to two decimal places using
round()
. - Show a warning if spending exceeds a certain limit (e.g., 100).
- Allow the user to enter multiple purchases and calculate the total spending.
2. Temperature Converter
Ask the user to enter the current temperature in Celsius. Store it in a variable. Then convert it to Fahrenheit using the formula F = C × 9/5 + 32
and print the
result. The message should say something like “22°C is 71.6°F”.
What this Task Teaches
This task shows how variables can be used to store input, apply a formula, and display a formatted result. It also reinforces working with decimal numbers and combining math with string output.
Hints and Tips
- Convert the input to
float()
to allow decimal temperatures. - Use parentheses in the formula to ensure correct order of operations.
- Use an
f-string
to format both Celsius and Fahrenheit in one sentence.
Common Mistakes
- Forgetting type conversion: Without
float()
, decimal temperatures will be treated as strings, leading to errors in calculations. - Incorrect formula usage: Make sure you multiply Celsius by 9/5 before adding 32 - don’t reverse the steps.
- No formatting in output: Displaying raw numbers without ° symbols or rounding can be confusing to users.
- Hardcoded Celsius value: Don't assign the value manually - take it from the user input.
- Overwriting variable names: Keep variables like
celsius
andfahrenheit
clearly named and separate.
Step-by-Step Thinking
This is a simple formula-based transformation. Focus on accurate calculations and user-friendly output.
- Ask the user to enter a temperature in Celsius
- Convert the input to a float
- Use the formula
fahrenheit = celsius × 9/5 + 32
- Store the result in a separate variable
- Display both the original and converted values in one formatted sentence
How to Make it Harder
- Round the Fahrenheit result to 1 decimal place.
- Add support for converting Fahrenheit to Celsius as well.
- Let the user choose which direction to convert (C → F or F → C).
Practice in Variables for Advanced Level
Now that you’re confident with declaring and using variables, it’s time to apply them in more advanced contexts. These tasks simulate small real-world applications where values are updated, reused, and compared across multiple steps. You'll work with multiple variables, conditional logic, and controlled user interaction. The goal is to strengthen your ability to track changing data, organize code cleanly, and solve slightly more involved problems. In these tasks, your focus should be on clarity, precision, and making your variables meaningful and reusable. Mastering this level will prepare you for working with functions, loops, and more structured programs.
1. Shopping Cart Total
Create a program that simulates a simple shopping cart. Ask the user to enter the price of three items one by one. Store each price in a separate variable, then calculate the total and display a summary like “Total cost: $42.50”. Use variables to keep the code clean and readable.
What this Task Teaches
This task teaches how to store multiple related values in variables and combine them in a calculation. You’ll also practice formatting output and structuring code for clarity. It helps reinforce the habit of using variables for clean, maintainable code.
Hints and Tips
- Use
float()
to allow prices with decimals. - Store each item price in a separate variable.
- Add the variables together to get the total.
- Use
round()
or formatting to display two decimal places.
Common Mistakes
- Forgetting float conversion: Using
int()
will cut off decimal parts. Always usefloat()
for monetary values. - Mixing calculation and print logic: It’s better to calculate the total in one variable and print it separately, not inline.
- Hardcoding item prices: Always take input from the user instead of assigning fixed values.
- Skipping formatting: Without rounding, the total might show many unnecessary decimals (e.g., 12.6666667).
- Using unclear variable names: Avoid generic names like
a
,b
,c
. Useitem1_price
, etc.
Step-by-Step Thinking
Think of this as a digital receipt. You collect prices, calculate the total, and present the result clearly.
- Ask the user to enter the price of item 1 and store it as a float
- Repeat for item 2 and item 3
- Add all three variables to compute the total
- Round the result to 2 decimal places using
round()
orf-string
formatting - Display the result with a dollar sign and message
How to Make it Harder
- Ask how many items the user wants to add and repeat input dynamically.
- Apply a 10% discount if total exceeds $50.
- Add sales tax (e.g., 7%) to the total before displaying it.
2. Gym Workout Tracker
Write a program that tracks a user’s total workout time. Ask how many minutes they spent on three different exercises: running, cycling, and strength training. Store each value in a variable, calculate the total workout time, and display a message like “You trained for 75 minutes today!”.
What this Task Teaches
This task trains you to combine multiple numeric inputs in a logical context. It also helps build good practices in naming variables, performing aggregation, and giving clear, concise output summaries.
Hints and Tips
- Ask the user separately about each type of workout.
- Use
int()
to convert the time to minutes. - Add the times together in a separate variable.
- Make your output message motivational and well-formatted.
Common Mistakes
- Skipping input conversion: If you forget
int()
, you can’t add the time values together - they’re strings by default. - Incorrect addition: Make sure you’re adding all three values - no more, no less.
- Overwriting variables: If you accidentally use the same name twice, earlier values will be lost.
- Weak variable naming: Use specific names like
running_minutes
orcycling_minutes
to keep the code readable. - Unclear message: Always show the total and context (e.g., “minutes” and the workout theme).
Step-by-Step Thinking
Picture this as a daily fitness log. You collect each session’s duration and present a motivating total at the end.
- Ask how many minutes were spent running, and store it in a variable
- Repeat for cycling and strength training
- Convert all inputs to integers using
int()
- Add the three values and store in
total_minutes
- Print a summary message with the final time
How to Make it Harder
- Convert minutes to hours and minutes (e.g., “1 hour 15 minutes”).
- Add calorie estimation based on minutes and exercise type.
- Store the session in a log (e.g., dictionary or write to file).