Learn
B2.1.1 | TYPES AND VARIABLE SCOPE
01 | A PROGRAM NEEDS TO REMEMBER THINGS
A workshop booking program must remember a student’s name, how many places they request, a group letter, a price and whether the request is accepted. These values represent different kinds of information, and they may be needed in different parts of the program.
A variable associates a name with a value that can change during execution. Its data type tells us the kind of value and which operations make sense. Its scope tells us where the name can be used. Type and scope answer different questions.
This common SL/HL lesson uses runnable Python examples. You will construct programs using Boolean, character, decimal, integer and string values, then trace local and global variables through function calls. You do not need previous experience with functions: we will introduce the parts needed here.
02 | NAME, VALUE AND TYPE
places = 2
student_name = "Maya"
price = 4.50
confirmed = True
In places = 2, places is the name, 2 is its current value and int is the Python type of that value. The equals sign performs assignment: evaluate the expression on the right, then associate its result with the name on the left.
Python names refer to objects; the object has a type. You do not declare an integer variable with a separate type keyword. In these examples we keep each name’s intended role consistent to make the program clear.
Read quantity = quantity + 1 as “take the old quantity, add one and store the new value”. It is an update instruction, not a mathematical claim that a number equals itself plus one.
03 | THE FIVE SYLLABUS DATA TYPES
| Syllabus category | Meaning | Python example | Important distinction |
|---|---|---|---|
| Boolean value | True or false | confirmed = True | True is a Boolean; "True" is text. |
| char | One character | group = "A" | Python represents a character using a length-one str, not a separate char type. |
| decimal | A number with a fractional part | price = 4.5 | Python float is the usual introductory representation; it is approximate binary floating point. |
| integer | A whole number | places = 2 | Use numeric values for calculations, not quoted digits. |
| string | A sequence of characters | student_name = "Maya" | May contain letters, digits, spaces or no characters. |
The syllabus categories describe the information. Language representations differ. In Python, "A" and "Maya" both have type str. Writing 4.0 produces a float even though its numerical value equals the integer 4.
04 | INTEGER: COUNT WHOLE THINGS
An integer represents a whole-number value such as −3, 0 or 12. Use one for a count of students, a score or a loop position when fractional values are not appropriate.
The appearance of digits does not automatically make data an integer. A membership code such as "0042" is text if its leading zeros matter and it is not a quantity to calculate with. Choose a representation from its meaning.
places = 2
places = places + 1
print(places) # outputs 3
The update reads the old value 2 and stores 3. The print call displays the current value; an assignment alone does not display it.
05 | DECIMAL VALUES AND PYTHON FLOAT
A decimal-valued measurement or price may have a fractional part, such as 2.5 or 4.50. Python normally uses float for these introductory calculations. A float stores a binary approximation, so some familiar decimal fractions cannot be represented exactly.
distance = 2.5
print(distance * 2) # 5.0
print(0.1 + 0.2) # 0.30000000000000004
This is a representation issue, not a broken addition operator. Formatting a result to two places changes its presentation; it does not make all underlying calculations exact. Python also provides Decimal for deliberate decimal arithmetic, but importing and configuring it is beyond the core examples here.
Do not confuse the syllabus category decimal with a requirement that every fractional value must be an instance of Python’s Decimal class. Also note that 4.50 normally prints as 4.5: a number does not retain the way its literal was written.
06 | CHAR AND STRING: TEXT HAS ITS OWN RULES
group = "A"
student_name = "Maya"
member_code = "0042"
empty_text = ""
The group value is one character, making it suitable for a char role in the problem. Python still stores it as a str. A longer str can hold a name or a message, and an empty str has length zero.
Quotes tell Python that a value is literal text. print(student_name) displays the value held by the variable; print("student_name") displays the literal letters student_name.
A digit character such as "8" is text, so "8" + "2" produces "82" by concatenation. Numeric 8 + 2 produces 10. The meaning and type of the operands affect the operation.
07 | BOOLEAN: A RESULT YOU CAN TEST
places = 2
confirmed = places > 0
print(confirmed) # True
A Boolean has one of two values: True or False in Python. The comparison places > 0 produces a Boolean result and assigns it to confirmed. The comparison itself does not change places.
The string "False" is not the Boolean False. It is nonempty text, so Python treats it as true in a truth test. Similarly, bool("False") does not parse the word into the Boolean value False.
For a yes/no response, compare the normalised text to an explicitly accepted answer or use a controlled choice. Handling arbitrary responses properly comes with validation; do not assume that converting any nonempty input with bool gives its intended meaning.
08 | INPUT STARTS AS TEXT
student_name = input("Student name: ")
places = int(input("Number of places: "))
price = float(input("Price per place: "))
print(places * price)
input returns a string. int converts suitable text into an integer; float converts suitable numeric text into a floating-point value. Without conversion, multiplying or adding can perform text operations or cause a type error rather than the intended calculation.
For this first example assume valid supplied numeric text. An input such as "two" cannot be converted by int and raises ValueError. The next exception-handling lesson develops ways to respond; conversion is not a complete validation policy.
For a single group character entered by a user, the program must check its length if one character is required. Python does not enforce that rule simply because you named the variable group.
09 | CHOOSE TYPES FROM THE REQUIREMENTS
| Information | Suitable category / Python representation | Reason |
|---|---|---|
| Number of requested places | Integer / int | A whole-number count. |
| Average journey duration | Decimal-valued number / float | Fractional measurements can occur. |
| Whether accepted | Boolean / bool | A logical state, not the words "yes" or "no". |
| One group letter | char role / length-one str | Exactly one character is required by the problem. |
| Name or code with leading zeros | String / str | Preserve characters rather than treat them as a quantity. |
Types alone do not establish allowed ranges. An int can represent −2, but negative requested places may be invalid. A str can contain one letter or a long paragraph. The specification supplies the additional rules.
10 | SCOPE: WHERE DOES A NAME BELONG?
A program can contain several functions. A function is a named unit of code that runs when called. Its indented body groups its actions. We use functions here to demonstrate where names are visible and how values move between parts of a program.
A name assigned at the top level of a Python module is global to that module. A name assigned inside a function is normally local to that function call. A parameter also becomes a local name receiving an argument value.
Global does not mean that every program on the computer can read it. Our discussion concerns one Python module and ordinary function scopes, not a universal public storage area.
11 | DEFINITION IS NOT EXECUTION
def greet(name):
message = "Hello " + name
print(message)
greet("Maya")
def introduces a function definition. Python creates the function, but does not execute its indented body just because it encounters the definition. The call greet("Maya") enters that body.
name is the parameter, a local name for the supplied argument "Maya". message is another local name. The call creates its local scope; the print displays Hello Maya; then execution returns to the line after the call.
Indentation marks the body. Writing message outside that body would give it a different scope. Keep the example’s layout when copying it.
12 | A GLOBAL VALUE CAN BE READ LOCALLY
RATE = 0.10
def quote(price):
fee = price * RATE
return price + fee
total = quote(20.0)
print(total)
print(RATE)
RATE is assigned at module level. The quote function has local price and fee names. It can read RATE because there is no local RATE in this function. A global statement is not needed merely to read the global value.
The argument 20.0 becomes local price. fee becomes 2.0 and return supplies 22.0 to the waiting call. That value is assigned to global total. The outputs are 22.0 and 0.1.
Uppercase RATE signals a constant-like intention by convention. Python does not make it immutable or prevent reassignment because of its capital letters.
13 | FOLLOW THE CALL AND THE RETURN
| Action | Module/global state | Local quote call | Output |
|---|---|---|---|
| Assign RATE | RATE = 0.1 | Not active | None |
| Define quote | Function created | Body not running | None |
| Call quote(20.0) | total not assigned yet | price = 20.0 | None |
| Calculate fee | RATE unchanged | fee = 2.0 | None |
| Return price + fee | Call returns 22.0 | Call finishes | None |
| Assign returned result | total = 22.0 | Local call finished | None |
| Print total; print RATE | Values unchanged | Not active | 22.0 then 0.1 |
return and print have different jobs. return sends a value to the caller; print displays a value. Returning 22.0 does not itself print it, and print is not a substitute for returning a result needed by another calculation.
14 | SAME NAME, TWO DIFFERENT BINDINGS
score = 10
def show_score():
score = 3
print(score)
show_score()
print(score)
The module has score = 10. The assignment score = 3 inside show_score creates a local score, separate from the global one. The function’s print uses its local score and displays 3. After the call, the module print uses the global score and displays 10.
This is called shadowing: a local name hides a same-named global within that scope. Changing the local binding does not reassign the global one.
A trace should use separate columns such as global score and local score. Combining both into one column makes the program appear to change a single variable when it does not.
15 | EACH CALL HAS ITS OWN LOCAL VALUES
def next_score(score):
score = score + 1
return score
first = next_score(4)
second = next_score(9)
print(first, second) # 5 10
On the first call, local score begins at 4 and becomes 5. On the second call, a new local score begins at 9 and becomes 10. The second call does not continue from the previous local value.
When a call finishes, its local names are no longer accessible as that call’s local variables. A returned object can remain available through the caller’s name; “the local scope ended” does not mean every returned value is instantly destroyed.
These examples use immutable numeric and string values. Mutating a shared list has different effects from rebinding a local name; lists are addressed in B2.2.
16 | EXPLICITLY REASSIGNING A GLOBAL
score = 5
def add_bonus():
global score
score = score + 3
add_bonus()
print(score)
global score tells Python that assignments to score in this function refer to the module’s score. The update reads 5, adds 3 and rebinds that global name to 8. The final output is 8.
The global statement does not itself create a new numeric value or add the bonus. The following assignment performs the update. The statement applies to that name in this function’s scope.
Use shared mutable program state deliberately. If many functions change the same global, understanding a call requires knowing what earlier calls have done, making testing and reuse harder.
17 | WHY THE NEARLY IDENTICAL PROGRAM FAILS
score = 5
def add_bonus():
score = score + 3
add_bonus()
Without global score, Python treats score as a local name because the function assigns to it. The right-hand side tries to read that local score before it has a value. The call raises UnboundLocalError; it does not automatically read 5 and update the global.
Do not describe this as every function being unable to read globals: the RATE example reads one successfully. The issue is a local assignment to the same name and a read before that local binding has been established.
You can fix this specific example with an explicit global declaration, but often a parameter and return value provide a clearer design.
18 | PREFER AN EXPLICIT VALUE FLOW WHEN SUITABLE
def add_bonus(current_score, bonus):
updated_score = current_score + bonus
return updated_score
score = 5
score = add_bonus(score, 3)
print(score) # 8
The function receives what it needs and returns a result. The caller decides to store that result in its global score. This is different from the function directly reassigning a global.
The inputs and output are visible in the call, so you can test add_bonus(10, 2) independently of a hidden earlier score. Local names also reduce accidental interference between unrelated parts of the program.
Global configuration can still be useful, as with a read-only rate. The aim is to choose and document scope sensibly, not to claim that all global names are inherently wrong.
19 | A COMPLETE MIXED-TYPE PROGRAM
CLUB_NAME = "Robotics"
BASE_FEE = 4.50
def booking_cost(student_name, places, group):
confirmed = places > 0
cost = places * BASE_FEE
print(student_name)
print(group)
print(confirmed)
return cost
student = "Maya"
quantity = 2
group_letter = "A"
total = booking_cost(student, quantity, group_letter)
print(CLUB_NAME)
print(total)
Assume valid inputs for this small demonstration. student is a string, quantity an integer, group_letter a single-character str representing a char role, BASE_FEE a float and local confirmed a Boolean. The function calculates a cost; it is not a complete capacity-enforcing booking service.
The outputs are Maya, A, True, Robotics and 9.0 on separate lines. The function reads global BASE_FEE, uses its own local parameters and cost, and returns a value assigned to global total.
20 | TRACE TYPE AND SCOPE SEPARATELY
| Name | Scope in the mixed-type example | Value / Python type |
|---|---|---|
| CLUB_NAME | Module/global | "Robotics" / str |
| BASE_FEE | Module/global | 4.5 / float |
| quantity | Module/global | 2 / int |
| group_letter | Module/global | "A" / str, char role |
| places | Local parameter during booking_cost | 2 / int |
| confirmed | Local during booking_cost | True / bool |
| cost | Local during booking_cost | 9.0 / float |
| total | Module/global after return | 9.0 / float |
An integer can be global or local; so can a Boolean, string or float. Scope does not determine data type. A global name can also be assigned later in the file, so read the execution order as well as the indentation.
21 | INTERACTIVE: STEP THROUGH SCOPE
Choose one of the three supplied programs. Predict each next action before stepping. The table keeps module values separate from the active function’s local values. A finished call is shown as inactive, not as every local value becoming zero. The simulator traces these examples only; it does not execute arbitrary Python.
| Step / action | Module/global values | Active local values | Explanation |
|---|
22 | CHECK THE TYPE, NOT JUST THE APPEARANCE
For each supplied assignment, select the actual Python type of the value. Remember that the syllabus char category is represented using str in Python. A quoted word is not automatically a Boolean.
23 | CONSTRUCT A PROGRAM: A READING CHALLENGE
Write a Python program with global CHALLENGE_NAME containing text and global POINTS_PER_BOOK = 2.5. Define a function that receives a student name, a whole-number count of books and a one-character group. Inside it, calculate a local points value and a local Boolean met_target that is true for at least four books. Print the name, group and Boolean, then return the points.
At module level, call the function for Maya, four books and group A. Store the returned result and print the challenge name and points. Assume valid inputs; state that a real input version would need checks for allowed counts and exactly one group character.
Reveal one possible solution
CHALLENGE_NAME = "Read and Discover"
POINTS_PER_BOOK = 2.5
def reading_points(student_name, books, group):
points = books * POINTS_PER_BOOK
met_target = books >= 4
print(student_name)
print(group)
print(met_target)
return points
result = reading_points("Maya", 4, "A")
print(CHALLENGE_NAME)
print(result)
The outputs are Maya, A, True, Read and Discover and 10.0 on separate lines. The parameters, points and met_target are local. The two configuration names and result are global to this module.
24 | COMMON MISTAKES
| Mistake | Correction |
|---|---|
| "False" is the Boolean False | It is nonempty str text; compare accepted responses deliberately. |
| Python has a separate char for "A" | It is a length-one str representing a character role. |
| Global means available to every program | Here it means a name in the module’s global namespace. |
| Assigning score locally changes global score | Normally it creates/rebinds a local name unless declared global. |
| A definition runs all its body lines | The body runs when the function is called. |
| return prints the answer | It supplies a value to the caller; print displays. |
| A decimal number always has exact representation | float uses binary approximation; choose representation with care. |
| Capital letters enforce a constant | They communicate a convention, not an assignment prohibition. |
25 | HOW TO CONSTRUCT AND TRACE
For construct, produce a program that satisfies the requested behaviour and uses appropriate types and scopes. Choose meaningful identifiers, preserve indentation and make the flow of arguments and returned values clear.
For trace, record the actions and current values. Mark the call, create local parameter values, follow the body, record any output, pass the return value to the waiting caller and then continue. Separate same-named globals and locals.
An error is part of a trace too. If execution reaches an unbound local read, identify where it fails and stop; do not invent the result the programmer probably intended.
26 | TEST YOUR OWN UNDERSTANDING
Can you explain why 8, 8.0 and "8" have different Python types? Can you show one example of a global read, local shadowing and explicit global reassignment? Can you trace a function call without confusing its return value with its output?
Change the reading-challenge example to three books and predict met_target and points before running it: False and 7.5. Then call it again for a different student and explain why its locals begin from the new arguments.
The next lesson applies string values to extracting and manipulating substrings.