Computer ScienceChapter 3: Programming Fundamentals (Python)
3.6 Python Variables
A variable
Explanation level
Introduction
In programming, we often need to store information so that we can use it later. For example, we might need to remember a user's name, a calculated result, or a temporary value during a computation. Python uses variables to store this information.
Definition
A variable stores some information which when allocated in the program, can be used later on.
In simple words, a variable is like a labeled box where you can store a value and retrieve it whenever you need it.
Main Idea
For example, rather than solving the same equation which is used multiple times in a program, we just store the resultant in a variable and use it without recalculating the formula.
A good programming practice is to keep meaningful variable names.
Core Concept
- Has a name (identifier)
- Holds a value (data)
- Can be used later in the program
- Can be changed (updated) during program execution
Detailed Explanation
Rules for Naming Variables
The name of a variable:
- Can be alphanumeric: A combination of alphabets and numbers, but cannot start with a number.
- ✓ Valid: `num1`, `student_name`, `totalMarks`
- ✗ Invalid: `1num`, `2ndValue`
- Are Case Sensitive: `Num` and `num` are treated as two separate variables.
- `age = 10` and `Age = 20` are different variables.
- Cannot contain spaces: A good technique is to use underscore (`_`), like `Temp_var`, which reflects a meaningful message that the value assigned to this variable is temporary.
- ✓ Valid: `student_name`, `total_marks`
- ✗ Invalid: `student name`, `total marks`
- Should be meaningful: Use names that describe what the variable holds.
- ✓ Good: `student_age`, `total_price`, `average_score`
- ✗ Poor: `x`, `y`, `z` (unless used for mathematical purposes)
Variable Assignment
In Python, you assign a value to a variable using the `=` operator.
Example: ```python x = 5 y = 3 name = "Ali" ```
- `x = 5` — Creates a variable `x` and stores the value `5`
- `y = 3` — Creates a variable `y` and stores the value `3`
- `name = "Ali"` — Creates a variable `name` and stores the text `"Ali"`
Sequence of Instructions
Generally, instructions are written in the order they are supposed to execute, in all programming languages. This way, it is easier to apply the logic which is meant to be implemented via those instructions.
So, if for some reason, the sequence of instructions changes, it may result in undesirable results. And when you look again at your code the syntax of the code seems all right but the instructions are not behaving according to your expectations.
Such a scenario is called a Logical Bug or Bug. A bug is hard to detect just by looking at the code and this capability comes with experience. But the simplest method is to Dry-Run your code.
Example — Swapping Two Variables
Let's write a code to swap the values of two variables, namely `x` and `y`, with the help of a temporary variable `temp`.
Correct Code: ```python x = 5 y = 3 temp = 0 print("Values of x:", x, "and y:", y) print("Let's Swap the value of x & y") temp = x x = y y = temp print("Values of x:", x, "and y:", y) ```
Output: ``` Values of x: 5 and y: 3 Let's Swap the value of x & y Values of x: 3 and y: 5 ```
- `x = 5`, `y = 3`, `temp = 0` — Initialize variables
- Print initial values
- `temp = x` — Store value of `x` (5) in `temp`
- `x = y` — Copy value of `y` (3) into `x`
- `y = temp` — Copy value of `temp` (5) into `y`
- Print final values — `x` is now 3, `y` is now 5
Incorrect Code (Wrong Sequence): ```python x = 5 y = 3 temp = 0 print("Values of x:", x, "and y:", y) print("Let's Swap the value of x & y") temp = x y = temp x = y print("Values of x:", x, "and y:", y) ```
Output: ``` Values of x: 5 and y: 3 Let's Swap the value of x & y Values of x: 5 and y: 5 ```
- `temp = x` — `temp` becomes 5
- `y = temp` — `y` becomes 5
- `x = y` — `x` becomes 5 (but we wanted 3)
- The value `3` is lost!
Dry Run — Finding the Bug
Dry-Run is where you execute your program on paper and keep track of the variables.
Dry Run Table for Incorrect Code:
| Line | x | y | temp |
|---|---|---|---|
| Before | 5 | 3 | 0 |
| 6 | 5 | 3 | 5 |
| 7 | 5 | 5 | 5 |
| 8 | 5 | 5 | 5 |
- After line 6: `temp = 5`
- After line 7: `y = 5`
- After line 8: `x = 5`
The value `3` is lost and cannot be assigned to `x`. Hence, value of `3` is lost.
As a result, we now know where the problem lies, and we can fix it.
Data Types in Python
A variable needs to be defined as what type of data it can hold, and thus programming language needs to define support for various data types. Python also provides support for different data types by default.
Common Data Types:
| Data Type | Description | Example |
|---|---|---|
| `int` | Integer (whole numbers) | `x = 5` |
| `float` | Decimal numbers | `x = 3.14` |
| `str` | String (text) | `name = "Ali"` |
| `bool` | Boolean (True/False) | `flag = True` |
| `list` | Ordered collection (mutable) | `nums = [1, 2, 3]` |
| `tuple` | Ordered collection (immutable) | `coords = (10, 20)` |
Numbers are stored in numeric data types, like `int` and `float`.
Sequence of characters are handled by `string` data type.
To manoeuvre a series of similar values, `list` can be used, represented by `[_,_]`.
Tuple is identical to list, but are immutable — once defined, the values in a tuple cannot be changed. A tuple holds the values in `(_,_)`.
Intermediate Level
Variable Scope
Variables in Python have a scope — the part of the program where the variable is accessible.
- Defined outside all functions
- Accessible throughout the program
- Defined inside a function
- Accessible only within that function
Example: ```python global_var = 10 # Global variable
def myfunction(): localvar = 20 # Local variable print("Inside function - global:", globalvar) print("Inside function - local:", localvar)
myfunction() print("Outside function - global:", globalvar) # print("Outside function - local:", local_var) # This would cause an error ```
Output: ``` Inside function - global: 10 Inside function - local: 20 Outside function - global: 10 ```
Multiple Assignment
Python allows you to assign values to multiple variables in one line.
Example: ```python x, y, z = 1, 2, 3 print(x, y, z) ```
Output: ``` 1 2 3 ```
You can also assign the same value to multiple variables:
```python a = b = c = 100 print(a, b, c) ```
Output: ``` 100 100 100 ```
Reassigning Variables
Variables can be reassigned to new values at any time.
Example: ```python x = 5 print(x) # Output: 5
x = 10 print(x) # Output: 10
x = "Hello" print(x) # Output: Hello ```
Note: The data type of a variable can change in Python because it is a dynamically typed language.
Deleting Variables
You can delete a variable using the `del` keyword.
Example: ```python x = 5 print(x) # Output: 5
del x # print(x) # This would cause an error because x no longer exists ```
Common Data Types — Detailed
int (Integer): ```python age = 16 count = 100 temperature = -5 ```
float (Decimal): ```python price = 99.99 pi = 3.14159 percentage = 85.5 ```
str (String): ```python name = "Ali" city = 'Lahore' message = "Hello, World!" ```
bool (Boolean): ```python is_student = True has_passed = False ```
list (List): ```python marks = [85, 90, 78, 92] names = ["Ali", "Sara", "Ahmed"] mixed = [1, "Hello", 3.14, True] ```
tuple (Tuple): ```python coordinates = (10, 20) rgb_color = (255, 0, 0) ```
Formula / Mathematical Form
Not applicable for this topic.
Solved Example
Example — Swap Two Variables Without a Third Variable
Given: `x = 5`, `y = 3` Required: Swap values without using a temporary variable
Method (using arithmetic): ```python x = 5 y = 3 x = x + y # x = 8 y = x - y # y = 5 x = x - y # x = 3 print("x =", x, "y =", y) ```
Output: ``` x = 3 y = 5 ```
- 0 → x = 5 + 3 = 8
- 0 → y = 8 - 3 = 5
- 0 → x = 8 - 5 = 3
Method (using Python's tuple unpacking): ```python x = 5 y = 3 x, y = y, x print("x =", x, "y =", y) ```
Output: ``` x = 3 y = 5 ```
Explanation: Python evaluates the right side first (creates a tuple `(3, 5)`), then assigns to the left side (`x = 3`, `y = 5`).
Important Points
- - A variable stores information that can be used later in the program.
- - Variable names can be alphanumeric but cannot start with a number.
- - Variable names are case sensitive.
- - Variable names cannot contain spaces; use underscores instead.
- - Use meaningful variable names.
- - Instructions are written in the order they should execute.
- - Changing the sequence of instructions can cause logical bugs.
- - Dry run helps find logical bugs.
- - Python supports multiple data types: int, float, str, bool, list, tuple.
- - Lists are mutable; tuples are immutable.
- - Python is dynamically typed — no need to declare data types.
Remember
- - Variable = Named storage for a value.
- - Rules: Alphanumeric, no start with number, case-sensitive, no spaces.
- - Meaningful names — use descriptive names.
- - Sequence matters — instructions execute in order.
- - Dry run — execute on paper to find bugs.
- - Data types: int, float, str, bool, list, tuple.
- - List = mutable (can change).
- - Tuple = immutable (cannot change).
- - Python = dynamically typed — no need to declare types.
Common Mistakes
- - Starting variable names with a number: `1num` is invalid; use `num1`.
- - Using spaces in variable names: `student name` is invalid; use `student_name`.
- - Confusing case sensitivity: `Name` and `name` are different variables.
- - Using meaningless names: `x1`, `x2`, `x3` are hard to understand; use `student_age`, `total_marks`.
- - Changing instruction sequence: Changing the order of instructions can cause logical bugs.
- - Not dry-running: Assuming code works without testing leads to undetected bugs.
- - Confusing list and tuple: Lists are mutable (changeable); tuples are immutable (unchangeable).
- - Forgetting that Python is dynamically typed: You can reassign variables to different data types.
Quick Revision
A variable stores some information which when allocated in the program, can be used later on. For example, rather than solving the same equation which is used multiple times in a program, we just store the resultant in a variable, and use it without recalculating the formula. A good programming practice is to keep meaningful variable names.
- Can be alphanumeric (combination of alphabets and numbers) but cannot start with a number.
- Are case sensitive — `Num` and `num` are treated as two separate variables.
- Cannot contain spaces — use underscore (`_`) like `Temp_var`.
Generally, instructions are written in the order they are supposed to execute. If the sequence of instructions changes, it may result in undesirable results — this is called a Logical Bug or Bug. The simplest method to find bugs is to Dry-Run your code.
- Numbers — stored in numeric data types like `int`, `float`
- Sequence of characters — handled by `string` data type
- List — used for a series of similar values, represented by `[_,_]`
- Tuple — identical to list but immutable, represented by `(_,_)`
60-Second Revision
- Variable = Named storage for a value.
- Rules: Alphanumeric, no start with number, case-sensitive, no spaces.
- Meaningful names — use descriptive names.
- Sequence matters — instructions execute in order.
- Dry run — execute on paper to find bugs.
- Data types: int, float, str, bool, list, tuple.
- List = mutable (can change).
- Tuple = immutable (cannot change).
- Swap example: `x, y = y, x` swaps values in one line.
- Warning: Changing instruction sequence can cause logical bugs — always dry-run your code.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.6 Python Variables
Sticky Notes · Quick Revision
Key Point 1
- Variable = Named storage for a value.
Key Point 2
- Rules: Alphanumeric, no start with number, case-sensitive, no spaces.
Key Point 3
- Meaningful names — use descriptive names.
Key Point 4
- Sequence matters — instructions execute in order.
Key Point 5
- Dry run — execute on paper to find bugs.
Key Point 6
- Data types: int, float, str, bool, list, tuple.
Key Point 7
- List = mutable (can change).
Key Point 8
- Tuple = immutable (cannot change).
Key Point 9
- Python = dynamically typed — no need to declare types.
Key Point 10
- Swap example: Use temp variable or tuple unpacking (`x, y = y, x`).
Same supplied content as this Notes page (shared canonical source).