Back to Python
2026-03-256 min read

Variable Exercises (Python Programming)

Learn Variable Exercises (Python Programming) step by step with clear examples and exercises.

Title: Variable Exercises (Python Programming) - Master Python Variables with Practical Examples and Common Mistakes

Why This Matters

In Python programming, variables are essential for storing data values that can be used throughout your code. Understanding how to declare and manipulate variables effectively is crucial for writing efficient and error-free programs. This lesson will guide you through practical exercises to help you master Python variables, with a focus on common mistakes and real-world examples.

Prerequisites

Before diving into variable exercises, it's essential that you have a good understanding of the following topics:

  1. Basic Python syntax (variables, operators, loops, functions)
  2. Data types in Python (strings, integers, floats, booleans, lists, tuples, and dictionaries)
  3. Control structures (if-else statements, conditional expressions, and loops)
  4. File handling in Python
  5. Understanding the difference between mutable and immutable data types
  6. Basic understanding of functions and modules
  7. Familiarity with Python's built-in functions like input(), print(), len(), and type()

Core Concept

Variables are used to store data values in Python. Each variable has a unique name and is associated with a specific data type. To declare a variable, you simply assign a value to it using the equal sign (=). Here's an example:

my_variable = 42
print(my_variable) # Output: 42

Python automatically infers the data type of a variable based on the assigned value. You can change the value of a variable at any time during your program's execution.

Variable Naming Conventions

In Python, variable names should be descriptive and follow these conventions:

  1. Use lowercase letters for variable names (e.g., my_variable, user_input).
  2. Avoid using spaces or special characters in variable names. Instead, use underscores to separate words (e.g., first_name, total_score).
  3. Do not use Python keywords as variable names (e.g., for, while, if).
  4. Use camelCase for naming variables that are part of a class or object (e.g., myClassVariable)
  5. Use PEP8 guidelines for consistent and readable code style.

Data Types and Operators

Python has several data types, including:

  1. Integers (e.g., 42, -7)
  2. Floating-point numbers (e.g., 3.14, -0.5)
  3. Strings (enclosed in single or double quotes, e.g., "Hello, World!", 'This is a string.')
  4. Booleans (True or False)
  5. Lists (a collection of items enclosed in square brackets, e.g., [1, 2, 3], ["apple", "banana", "orange"])
  6. Tuples (similar to lists but immutable, enclosed in parentheses, e.g., (1, 2, 3), ("apple", "banana", "orange"))
  7. Dictionaries (a collection of key-value pairs enclosed in curly braces, e.g., {"name": "John", "age": 30})
  8. Sets (an unordered collection of unique elements, enclosed in curly braces with no commas, e.g., {1, 2, 3})
  9. Byte strings (enclosed in single quotes and prefixed with 'b', e.g., b'Hello, World!')

Operators in Python include arithmetic operators (+, -, , /, %, ), comparison operators (==, !=, >, <, >=, <=), logical operators (and, or, not), assignment operators (=, +=, -=, =, /=, %=), and bitwise operators (&, |, ^, ~, <<, >>).

Variable Scope

In Python, variables have a global scope by default. However, you can create local variables within functions using the def keyword. Local variables are only accessible within their respective function.

def my_function():
local_variable = 42
print(local_variable)

my_function() # Output: 42
print(local_variable) # NameError: name 'local_variable' is not defined

Worked Example

Let's create a simple program that calculates the area of a rectangle using user input for the length and width.

Ask the user for the length and width of the rectangle

length = float(input("Enter the length of the rectangle: "))

width = float(input("Enter the width of the rectangle: "))

Calculate the area and display the result

area = length * width

print("The area of the rectangle is:", area)

Common Mistakes

  1. Forgetting to convert user input to the appropriate data type (e.g., int(), float())
  2. Using an uninitialized variable (e.g., undefined_variable)
  3. Assigning a value of the wrong data type to a variable (e.g., trying to assign a string to an integer)
  4. Forgetting to close a multi-line string with three quotes (''', """)
  5. Using a variable name that is already defined as a Python keyword (e.g., using for as a variable name)
  6. Assigning a value to a variable before it has been declared
  7. Modifying a constant variable (variables prefixed with const)
  8. Using a variable name that is too long or too short for readability
  9. Not following naming conventions for functions and classes
  10. Not using meaningful names for variables, functions, and classes

Practice Questions

  1. Write a program that calculates the sum of two numbers entered by the user.
  2. Create a program that asks the user for their name and age, then displays a personalized greeting.
  3. Write a function that takes three arguments (a, b, c) and returns their average as a floating-point number.
  4. Write a program that reads a list of integers from the user and calculates their sum.
  5. Create a dictionary containing the names and scores of five students in a class. Calculate the total score for the class and the average score per student.
  6. Write a function that takes a list of numbers as input, sorts it in ascending order, and returns the sorted list.
  7. Write a program that calculates the factorial of a number entered by the user using recursion.
  8. Create a module named my_module with a function called my_function(). Import this module and call my_function() in your main script.
  9. Write a program that reads a file line by line, counts the number of words in each line, and calculates the average number of words per line.
  10. Write a program that creates a list of Fibonacci numbers up to a certain value entered by the user.

FAQ

Q: Can I change the data type of a variable once it's been declared?

A: Yes, you can change the value of a variable to any other data type in Python. However, doing so may result in unexpected behavior or loss of precision (e.g., converting a float to an integer).

Q: What happens when I try to assign a value of one data type to a variable of another data type?

A: In Python, the interpreter will automatically convert the value to match the data type of the variable. For example, if you assign a string to an integer variable, the string will be converted to its numeric equivalent (if possible).

Q: How can I check the data type of a variable in Python?

A: You can use the type() function to check the data type of a variable. For example:

my_variable = 42
print(type(my_variable)) # Output: <class 'int'>

Q: What is the difference between mutable and immutable data types in Python?

A: Mutable data types (like lists, dictionaries, and sets) can be modified after they have been created. Immutable data types (like integers, floats, strings, and tuples) cannot be changed once they have been created.

Q: What is the purpose of a constant variable in Python?

A: A constant variable is a variable that should never change its value during the execution of your program. In Python, you can create a constant variable by prefixing it with const. However, Python does not have true constants like some other languages (e.g., C++).

Variable Exercises (Python Programming) | Python | XQA Learn