7. Variables
rectangle_length = 2.3, the variable names is rectangle_length, the type is float (decimal) and the value is 2.3.user_name = Annie, the variable names is user_name, the type is str (string) and the value is Annie.- Rules for Python variable names:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscores ( _ )
Variable names are case-sensitive (
age,AgeandAGEare three different variables)
7.1. Python Reserved Words
Reserved Words are keywords that have a set meaning and can’t be used for other purposes such as for variable names. Reserved words are case-sensitive and must be used exactly as shown. They are all entirely lowercase, except for False, None, and True.
print(help("keywords")).import keyword
print(keyword.kwlist)
7.2. Python conventions
height instead of x for the height of an object.7.3. Snake case
7.4. ALL_CAPS
PI = 3.14, GRAVITY = 9.8, MILES_TO_METRES = 1609.7.5. CapWords
AnimalFeatures, are used for Class names in python.7.6. camelCase
playerScore, are not recommended in python.7.7. KebabCase
player-score, are not recommended in python.7.8. Sample code
print('Federer has won 20 Grand Slams.')
Generalised to:
player_name = 'Federer'
wins = '20'
print(player_name + ' has won ' + wins + ' Grand Slams.')
7.9. Tasks
Questions
Write
AGEin snake case.Write
MyNamein snake case.Write
MyFirstNameLastNamein snake case.Write
rectangleAreain snake case.Write
cm_in_an_inch = 2.14as ALL_CAPS.Write
lbs_in_a_kg = 2.2as ALL_CAPS.A program asks for a person’s age and stores it. What would be a good variable to use:
x,variable1,AGE,age,Years_Old?A program uses a person’s first name and last name. What would be a good variable to use for their last name:
x,variable1,SURNAME,last_name,Name?A program calculates the area of a rectangle. What would be two good variables to use for the length and width of the rectangle:
x,y,LENGTH,length,Width,width?
Write AGE in snake case.
age
Write MyName in snake case.
my_name
Write MyFirstNameLastName in snake case.
my_first_name_last_name
Write rectangleArea in snake case.
rectangle_area
Write cm_in_an_inch = 2.14 as ALL_CAPS.
CM_IN_AN_INCH = 2.14
Write lbs_in_a_kg = 2.2 as ALL_CAPS.
LBS_IN_A_KG = 2.2
A program asks for a person’s age and stores it. What would be a good variable to use: x, variable1, AGE, age, Years_Old?
age
A program uses a person’s first name and last name. What would be a good variable to use for their last name: x, variable1, SURNAME, last_name, Name?
last_name
A program calculates the area of a rectangle. What would be two good variables to use for the length and width of the rectangle: x, y, LENGTH, length, Width, width?
length, width
8. Variables
=.# Creating variables with different data types
player_name = "Alex" # String (text)
score = 100 # Integer (whole number)
speed = 4.5 # Float (decimal number)
When naming variables in Python, you must follow specific rules and conventions:
Must start with a letter or an underscore (`_`): A variable name cannot start with a number.
Can only contain alphanumeric characters and underscores: Only letters (a-z, A-Z), numbers (0-9), and _ are allowed.
Case-sensitive: score, Score, and SCORE are three completely different variables!
Use snake_case: Use lowercase letters separated by underscores for multi-word names (e.g., player_score).
# ✅ Valid variable names
user_age = 14
_total = 50
player2_score = 95
# ❌ Invalid variable names (will cause SyntaxError)
# 2nd_place = "Bob" # Starts with a number
# user-name = "Sam" # Contains a hyphen (-)
# total score = 100 # Contains spaces
8.1. Quiz: Variable Naming Rules
8.1.1. Fill-in-the-Blanks (Cloze)
1. In Python, variables are created using the Drop here assignment operator.
2. A variable name cannot start with a Drop here.
3. Multi-word variable names in Python typically use Drop here naming style with underscores.
4. Variable names in Python are Drop here, meaning `age` and `Age` are distinct.
5. Attempting to use a variable with spaces in its name raises a Drop here.
8.1.2. Code Ordering Examples
Example 1: Define a valid player name variable, assign a string, and print it.
Example 2: Create two distinct variables demonstrating case sensitivity, then print their sum.
Example 3: Assign a score using snake_case, update it, and print the updated value.
8.1.3. Multiple Choice Questions
Which of the following is a valid Python variable name?
Correct! Uses letters, underscores, and lowercase snake_case syntax.
Incorrect. Variable names cannot start with a number.
Incorrect. Variable names cannot contain hyphens (-).
Incorrect. Variable names cannot contain spaces.
What operator symbol is used to assign a value to a variable in Python?
Correct! The single equals sign = is the assignment operator.
Incorrect. == is used to compare equality, not for variable assignment.
Incorrect. = is the standard assignment operator.
Incorrect. -> is used in function type annotations.
What happens if you define x = 5 and then try to run print(X)?
Correct! Variables are case-sensitive, so capital X is not defined.
Incorrect. x and X are distinct due to case sensitivity.
Incorrect. Python raises an unhandled NameError exception.
Incorrect. Python will not auto-define X.
Which variable naming convention is recommended by Python style guidelines (PEP 8)?
Correct! Snake case with lowercase letters and underscores is the standard.
Incorrect. camelCase is common in JavaScript, but not Python’s default style.
Incorrect. PascalCase is reserved primarily for class names in Python.
Incorrect. UPPERCASE is reserved for constants.
Why is class = 10 an invalid variable name in Python?
Correct! Reserved keywords cannot be used as variable names.
Incorrect. Variables can store numbers.
Incorrect. Starting with lowercase is standard practice.
Incorrect. Integers are valid variable values.
What is the primary function of a variable in computer programming?
Correct! Variables act as named containers for data.
Incorrect. print() displays text on the screen.
Incorrect. Variables store data rather than handle errors.
Incorrect. For and while structures create loops.
Which statement about Python variable creation is TRUE?
Correct! Python requires no explicit declaration keyword.
Incorrect. Python uses dynamic typing.
Incorrect. Python uses simple assignment syntax.
Incorrect. Variables can be created anywhere.
What will _count = 100; print(_count) output?
Correct! Variable names starting with an underscore are completely valid in Python.
Incorrect. Underscores are valid initial characters.
Incorrect. _count is properly assigned before printing.
Incorrect. _count evaluates to 100.
Which character cannot be used anywhere inside a Python variable name?
Correct! Special symbols like $, @, !, and % are not permitted in variable names.
Incorrect. Underscores are valid and widely used in variable names.
Incorrect. Numbers can be used anywhere except as the first character.
Incorrect. Letters are valid variable characters.
Given a = 5 and A = 10, what does print(a + A) yield?
Correct! Since variables are case-sensitive, a and A store separate values (5 and 10).
Incorrect. Both variables contribute to the sum.
Incorrect. a is 5, not 10.
Incorrect. Both variables are validly defined.
8.1.3.1. Updating Variables and Dynamic Typing
In Python, variables are dynamic, meaning:
Values can be overwritten: Assigning a new value replaces the old value stored in the variable.
Data types can change: A variable holding a number can later be assigned a string.
Re-assignment using existing values: You can update a variable based on its current value (e.g., incrementing a counter).
# Overwriting a variable value
health = 100
health = 80 # Replaced 100 with 80
# Updating a variable relative to its current value
health = health - 15 # Result: 65
# Changing the data type dynamically
data = 42 # Currently an integer
data = "Forty-two" # Now a string!
8.2. Quiz: Updating Variables
8.2.1. Fill-in-the-Blanks (Cloze)
1. Replacing an existing variable's value with a new one is called Drop here.
2. Python allows a variable to hold different data types over time because it uses Drop here typing.
3. To increase a number variable ``x`` by 1, you can write ``x = x + 1`` or use the shorthand Drop here.
4. Attempting to reference a variable before assigning a value to it causes a Drop here.
5. The built-in function Drop here can be used to check the current data type of a variable.
8.2.2. Code Ordering Examples
Example 1: Initialize a variable, update its value by adding 5, and print it.
Example 2: Reassign a variable from an integer to a string, then print the variable’s type.
Example 3: Swap the values of two variables a and b using Python’s tuple assignment.
8.2.3. Multiple Choice Questions
What is the final value of score after evaluating score = 10; score = score + 5; score = 20?
Correct! The final assignment
score = 20completely overwrites previous values.
Incorrect. 15 was overwritten by the final assignment of 20.
Incorrect. Assignments overwrite rather than accumulate unless explicitly added.
Incorrect. Initial value 10 was modified and then overwritten.
What does the statement count += 1 do in Python?
Correct! += is shorthand for count = count + 1.
Incorrect. == checks equality.
Incorrect. += modifies the variable in place.
Incorrect. *= performs multiplication assignment.
What happens when you run x = 5; x = "hello" in Python?
Correct! Python features dynamic typing.
Incorrect. Python allows dynamic reassignment across types.
Incorrect. Reassignment replaces the old value.
Incorrect. Type reassignment is standard syntax.
Which built-in function tells you the current data type stored in variable item?
Correct! type() returns the class type of the object.
Incorrect. typeof is used in JavaScript, not Python.
Incorrect. class is a reserved keyword for object definitions.
Incorrect. No such built-in function exists in Python.
What error occurs if you run print(points) before defining points = 0?
Correct! Referencing an unassigned variable raises a NameError.
Incorrect. TypeErrors occur during invalid operation combinations.
Incorrect. ValueErrors occur with incompatible arguments.
Incorrect. AttributeErrors occur with missing object methods.
Given a = 3; b = a; a = 5, what is the value stored in b?
Correct! b was assigned the value of a when a was 3; changing a later does not update b.
Incorrect. Primitive variable assignment copies the value at execution time.
Incorrect. Values are separate, not combined.
Incorrect. b holds value 3.
What does evaluating x = 10; x *= 2 leave inside x?
Correct! *= multiplies the current value (10) by 2 and reassigns it.
Incorrect. += adds, whereas *= multiplies.
Incorrect. 10 * 2 equals 20.
Incorrect. /= divides, whereas *= multiplies.
What type is returned by type(3.14)?
Correct! Decimal numbers in Python are classified as float objects.
Incorrect. Whole numbers are integers, whereas 3.14 is a decimal.
Incorrect. Unquoted decimal numbers are float types.
Incorrect. The standard built-in type name is float.
What does shorthand a -= 3 do?
Correct! -= is shorthand for a = a - 3.
Incorrect. Comparison operators do not use -=.
Incorrect. Direct assignment uses = -3.
Incorrect. -= subtracts and reassigns.
What is the result of running x = 10; x = x / 2; print(type(x))?
Correct! Division / always returns a float in Python 3.
Incorrect. Standard division converts results to float (5.0).
Incorrect. Numbers remain numeric types.
Incorrect. Python represents floating-point numbers as float.
8.2.3.1. Multiple Variable Assignment and Unpacking
Python provides concise syntax shortcuts for creating and assigning multiple variables simultaneously:
Assigning multiple values to multiple variables: Assign distinct items in one line using commas.
Assigning one value to multiple variables: Assign the exact same value across several variables.
Unpacking collections: Extract values from lists or tuples directly into variables.
# Assigning multiple values in one line
x, y, z = 1, 2, 3 # x=1, y=2, z=3
# Assigning the same value to multiple variables
a = b = c = 0 # a=0, b=0, c=0
# Unpacking a list into variables
fruits = ["apple", "banana"]
first, second = fruits # first="apple", second="banana"
8.3. Quiz: Multiple Assignment and Unpacking
8.3.1. Fill-in-the-Blanks (Cloze)
1. Setting multiple variables to the exact same value in one line uses multiple Drop here signs.
2. Extracting elements from a list into individual variables is called list Drop here.
3. In multiple assignment ``x, y = 10, 20``, variable ``y`` receives the value Drop here.
4. Unpacking a list into variables requires the number of variables to Drop here the number of list elements.
5. If unpacking variable count does not match collection length, Python raises a Drop here.
8.3.2. Code Ordering Examples
Example 1: Assign three values to three variables in a single line and print their sum.
Example 2: Assign zero to three variables simultaneously and print one of them.
Example 3: Unpack a list of coordinates into x_pos and y_pos variables and print x_pos.
8.3.3. Multiple Choice Questions
What are the values of a and b after executing a, b = 5, 10?
Correct! Values map positionally from left to right.
Incorrect. Values match variables in corresponding order.
Incorrect. Values are assigned individually.
Incorrect. Two variables match two values cleanly.
What does x = y = z = 100 achieve?
Correct! Chained assignment sets all targets to the rightmost value.
Incorrect. Equality checking uses == operators.
Incorrect. Chained assignment is valid syntax.
Incorrect. All targets receive 100.
What error occurs if you try a, b = [1, 2, 3]?
Correct! ValueError occurs when unpacking mismatched counts (2 variables vs 3 items).
Incorrect. Syntax is valid, but item counts mismatch.
Incorrect. Direct list indexing was not performed.
Incorrect. Variables are assigned during execution.
How do you swap the values of two variables p and q without using a third temporary variable?
Correct! Tuple packing/unpacking swaps variables atomically in one line.
Incorrect. Overwrites p with q first, losing p’s original value.
Incorrect. swap() is not a built-in Python function.
Incorrect. == tests equality without updating variables.
Given colors = ["red", "green"]; c1, c2 = colors, what does print(c2) output?
Correct! c2 gets the second item from the list colors.
Incorrect. c1 receives “red”.
Incorrect. Unpacking extracts scalar string values.
Incorrect. Valid list unpacking syntax.
What will x, y, z = "ABC" assign to variable y?
Correct! Strings are iterables, so unpacking extracts each character into variables.
Incorrect. Individual characters are unpacked positionally.
Incorrect. “A” is assigned to x.
Incorrect. “C” is assigned to z.
What is the outcome of a = 1, 2, 3; print(type(a))?
Correct! Assigning comma-separated values without parentheses creates a tuple object.
Incorrect. Comma separation packs elements into a tuple.
Incorrect. Square brackets [] are required for explicit list literals.
Incorrect. Automatic tuple packing is valid Python syntax.
Given m, n = 10 * 2, 30 + 5, what value does n hold?
Correct! Expressions are evaluated first before positionally assigning to n.
Incorrect. 20 is assigned to m.
Incorrect. Values evaluate separately before assignment.
Incorrect. Expressions are fully evaluated first.
If data = [100], what happens when you run x, y = data?
Correct! Cannot unpack 1 item into 2 variables.
Incorrect. Mismatched unpacking counts raise an exception.
Incorrect. Python does not provide default values during unpacking.
Incorrect. Python requires explicit variable-to-value matches.
What is output by x = 5; y = 10; x, y = y, x + 2; print(x, y)?
Correct! Right side evaluates to (10, 7) before assigning to x and y simultaneously.
Incorrect. x was 5 when evaluating x + 2.
Incorrect. Variables swap and reassign values.
Incorrect. Expression uses right-hand initial state.
8.3.3.1. Variable Scope and Constants
Understanding where variables can be accessed (scope) and how to represent unchanging values (constants) is essential:
Global Scope: Variables defined outside functions, accessible throughout the script.
Local Scope: Variables defined inside a function, accessible only within that function.
Constants: Values that should not change throughout a program. Python does not have enforced constants, but programmers use ALL_CAPS names as a convention!
# Constant convention (ALL_CAPS) MAX_SPEED = 120
PI = 3.14159
# Global variable
player_status = "Active"
def update_game():
# Local variable (only exists inside this function)
local_score = 50
print(player_status) # Can access global variable
update_game()
# print(local_score) # ❌ Error! local_score does not exist outside the function.
8.4. Quiz: Variable Scope and Constants
8.4.1. Fill-in-the-Blanks (Cloze)
1. A variable declared inside a function has Drop here scope.
2. A variable declared outside all functions has Drop here scope.
3. In Python, constants are indicated by writing variable names in Drop here.
4. Trying to access a local variable from outside its function causes a Drop here.
5. To modify a global variable inside a function, use the Drop here keyword keyword.
8.4.2. Code Ordering Examples
Example 1: Define a global constant and display it inside a function call.
Example 2: Define a global variable, modify it inside a function using global, and print it.
Example 3: Demonstrate local scope by defining a local variable inside a function.
8.4.3. Multiple Choice Questions
How do Python programmers indicate that a variable should be treated as a CONSTANT (unchanging value)?
Correct! Uppercase naming is the standard convention for constants.
Incorrect. Python does not have a const keyword.
Incorrect. Dollar signs are not valid in variable names.
Incorrect. Python variables remain reassignable.
What happens if you try to access a local variable outside the function where it was created?
Correct! Local variables cease to exist outside their function scope.
Incorrect. Out-of-scope variable access raises an error.
Incorrect. Scope boundaries are strictly maintained.
Incorrect. Python raises an exception.
Which keyword allows you to modify a global variable from INSIDE a function?
Correct! Declaring global variable_name inside a function allows modification of the global instance.
Incorrect. nonlocal is used for nested functions, not top-level global variables.
Incorrect. public is not a Python scope keyword.
Incorrect. import loads modules into the script.
Given x = 10 outside functions and x = 5 inside a function without global, what happens?
Correct! Assigning creates a local variable shadowing the global one.
Incorrect. Explicit global keyword is required to modify global scope.
Incorrect. Assigning creates a local binding.
Incorrect. Local and global scopes remain distinct.
Does Python enforce constant immutability (meaning Python prevents you from changing ALL_CAPS variables)?
Correct! Python relies on convention rather than strict enforcement.
Incorrect. Python permits reassignment of uppercase names.
Incorrect. Uppercase names remain reassignable variables.
Incorrect. Python does not enforce const immutability anywhere natively.
Where are global variables stored and accessible?
Correct! Global variables have module-level scope.
Incorrect. Local variables belong to function blocks.
Incorrect. Global variables span the entire file.
Incorrect. Variables reside in memory during script execution.
What will the following code output? val = 5; def test(): val = 2; test(); print(val)
Correct! The function created a local variable val = 2, leaving the global val equal to 5.
Incorrect. Global val was untouched without global keyword.
Incorrect. Scope variables do not add together automatically.
Incorrect. val exists cleanly in global scope.