0% found this document useful (0 votes)
1 views13 pages

Imperative Programming Using Python

Uploaded by

majiriwaraidzo86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views13 pages

Imperative Programming Using Python

Uploaded by

majiriwaraidzo86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

Declaring and Assigning Variables

# Integer variable
age = 18

# Floating-point number
height = 1.75

# String
name = "Alice"

# Boolean
is_student = True

print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is student?", is_student)

2. Inputting Values into Variables

# Getting user input and converting to integer


age = int(input("Enter your age: "))
print("You are", age, "years old.")

3. Changing Variable Values

score = 85
print("Original score:", score)

# Updating variable value


score = 92
print("Updated score:", score)

4. Using Constants (by convention)

# Constants are written in uppercase by convention


PI = 3.14159
radius = 5

area = PI * radius * radius


print("Area of circle:", area)

Note: This improves code readability and tells other


programmers:“This value should not be changed.”
 Python doesn’t have built-in constant support.
 By convention, variables written in uppercase are treated as constants.

Besides the * operator, there are other arithmetic operators


that can be used when suitable.

Comparison Operators

Boolean Operators
5. Multiple Assignment
# Assigning multiple values in one line
x, y, z = 10, 20, 30

print("x =", x)
print("y =", y)
print("z =", z)

6. Swapping Variables

a = 5
b = 10

# Swapping values
a, b = b, a

print("After swap: a =", a, ", b =", b)

7. Type Conversion

num_str = "123"
num_int = int(num_str)
num_float = float(num_str)

print("String to int:", num_int)


print("String to float:", num_float)

8. Scope of Variables – Global vs Local

def show_age():
local_age = 20 # Local variable
print("Local age inside function:", local_age)

global_age = 18 # Global variable

show_age()
print("Global age outside function:", global_age)

9. Using Variables in Expressions

length = 10
width = 5

# Using variables in an expression


area = length * width
perimeter = 2 * (length + width)

print("Area:", area)
print("Perimeter:", perimeter)

10. String Concatenation with Variables

first_name = "John"
last_name = "Doe"

full_name = first_name, " " , last_name


print("Full Name:", full_name)

Variables – Global vs Local in Python

1. Variable Scope
 The scope of a variable refers to the part of the program where the
variable can be accessed.
 In Python, there are two main types of scope:
 Local Variables
 Global Variables

2. Local Variables
 Defined inside a function .
 Can only be accessed inside that function .
 Created when the function is called and destroyed when the function ends
Example:
def show_name():
name = "Alice" # Local variable
print(name)

show_name()
# print(name) ← This would cause an error: 'name' not
defined

Note: Local variables help avoid accidental changes to data


outside the function — this supports modularity and data
protection.

3. Global Variables
 Defined outside all functions .
 Can be accessed anywhere in the program , including inside functions.
 They exist throughout the life of the program.
Example:
global_age = 18 # Global variable

def show_age():
print(global_age)

show_age()
print(global_age)

Output:
18
18

4. Modifying Global Variables Inside Functions


To change the value of a global variable inside a function, you must use the
global keyword.

Example:
count = 0 # Global variable

def increment():
global count
count += 1

increment()
print(count) # Output: 1

Note: global count, Python would treat count as a new local


variable, causing an error when trying to modify it.

5. Advantages and Disadvantages


FEATURE GLOBAL VARIABLES LOCAL VARIABLES

Accessibility Can be used anywhere Only within the function

Lifetime Exists during the whole program run Exists only while the function runs

Useful for sharing data between


Advantages functions Prevents unintended side effects

Disadvantages Harder to debug; can lead to Cannot be reused across functions easily
FEATURE GLOBAL VARIABLES LOCAL VARIABLES

unexpected changes

Best Practice (for exams):


 Use local variables whenever possible.
 Use global variables sparingly , typically for constants or shared state.

6. Scope and Lifespan – Key for Exams


 To identify whether a variable is local or global in code.
 To explain why using local variables is better than using globals.
 To modify code using the global keyword.
 To explain the lifespan and scope of variables.

7. Sample Exam Questions


Q1. Explain the difference between a local and a global variable.
A1. A local variable is declared inside a function and can only be accessed within
that function. A global variable is declared outside all functions and can be
accessed anywhere in the program.
Q2. Why is it considered good practice to use local variables instead of global
variables?
A2. Local variables prevent accidental changes to data elsewhere in the program
and improve modularity and maintainability.
Q3. What does the global keyword do in Python?
A3. It allows a function to access and modify a variable that was originally
defined outside the function.

Summary Table:

CONCEPT DESCRIPTION

Local Variable Declared inside a function; accessible only within it

Global Variable Declared outside functions; accessible anywhere

global keyword Needed to change a global variable inside a function

Constant Not enforced in Python; indicated by uppercase naming

Best Practice Prefer local variables; use global variables only when necessary

The Code:
def show_age():

local_age = 20 # Local variable

print("Local age inside function:", local_age)

global_age = 18 # Global variable

show_age()
print("Global age outside function:", global_age)

Methods in Python

What are commonly referred to as Procedures and Functions


(Subroutines) in pseudocode are known as methods in Python.
They both use keyword def when used.
Procedure is a block of code which does NOT return a value.
A procedure does not use a return statement.
Note: Procedures can be with or without parameters.

 def show_age(): – a procedure without parameters


 def show_age(age): – a procedure with a parameter

Code with a parameter:


def show_age(age):
print("Your age is:", age)

# Calling the procedure with a value


show_age(20)

Output:
Your age is: 20

Code without a parameter:


def show_age():
This defines a procedure that does not expect any data (parameters) when it
is called.
 It always behaves the same way unless it uses global variables.
 It cannot be customized each time you call it.

Example:

def show_age():
print("Age: 18")

show_age()

Output:
Age: 18

You can't change the output without editing the code.

Key aspects we must remember:

 Identify and explain the use of parameters in procedures/functions.


 Write or modify code to include parameters.
 Explain how using parameters improves modularity and code reuse.

Note: The version with the parameter (age) allows the procedure to accept
different values each time it is called, making it more flexible and reusable.
Without a parameter, the procedure would have to be manually changed to
display a different age.

Passing Multiple Parameters

def display_info(name, age):


print("Name:", name)
print("Age:", age)

# Calling the procedure with two arguments


display_info("Alice", 25)
Output:
Name: Alice
Age: 25

Pseudocode:
PROCEDURE display_info(name : STRING, age : INTEGER)
OUTPUT "Name: ", name
OUTPUT "Age: ", age
END PROCEDURE

// Main program
CALL display_info("Alice", 25)

Note: Pseudocode Style:

FEATURE IN THIS PSEUDOCODE

Procedure definition PROCEDURE display_info(name : STRING, age : INTEGER)

Parameters included Yes –name and age, with data types specified

Output command OUTPUTinstead ofprint()

Call syntax CALL display_info("Alice", 25)

Functions That Return Values


def add_numbers(a, b):
return a + b

result = add_numbers(5, 3)
print("Result:", result)
Passing Arrays / Lists as Parameters

In Python, you can pass lists (arrays) into both functions and procedures.

def find_average(scores):
total = sum(scores)
average = total / len(scores)
return average

# Using the function


scores_list = [80, 90, 70]
avg = find_average(scores_list)
print("Average score:", avg)

Pseudocode equivalent
FUNCTION find_average(scores : ARRAY OF INTEGER) RETURNS REAL
total ← 0
FOR i ← 0 TO LENGTH(scores) - 1
total ← total + scores[i]
NEXT i
average ← total / LENGTH(scores)
RETURN average
END FUNCTION

// Main program
DECLARE scores AS INTEGER[] ← [80, 90, 70]
avg ← find_average(scores)
OUTPUT "Average score: ", avg

Notes:

 In pseudocode, use ARRAY OF INTEGER, ARRAY OF STRING, etc., to specify


data types.
 You may also see ARRAY[0:2] OF INTEGER to indicate fixed-size arrays.
 Use loops to process array elements inside functions or procedures.
Basic Array Operations

OPERATION PYTHON PSEUDOCODE

Create arr = [1, 2, 3] DECLARE arr[0:2] OF INTEGER

Access arr[1] OUTPUT arr[1]

Update arr[0] = 99 arr[0] ← 99

Append arr.append(88) APPEND arr WITH 88

Remove arr.remove(2) Loop + shift elements

Sort arr.sort(reverse=True) Bubble/Insertion sort in pseudocode

Working with global and local arrays


# Global Example
scores = []

def add_score(s):

global scores
scores.append(s)

# Local Example

def process_scores():

scores = [80, 90]


print(scores)

Pseudocode:

DECLARE scores AS ARRAY OF INTEGER


PROCEDURE add_score(s : INTEGER)
APPEND scores WITH s
END PROCEDURE

class Student:

def __init__(self):
self.scores = []

def add_score(self, score):


self.scores.append(score)

s = Student()
s.add_score(90)

Pseudocode:
CLASS Student
DECLARE scores AS ARRAY OF INTEGER
PROCEDURE add_score(score : INTEGER)
APPEND THIS.scores WITH score
END PROCEDURE
END CLASS

Focus on:

1. Creating an Array
Python:
# One-dimensional list
scores = [85, 90, 78]

# Two-dimensional list
grid = [[1, 2], [3, 4]]

Pseudocode:
DECLARE scores[0:2] OF INTEGER
scores[0] ← 85
scores[1] ← 90
scores[2] ← 78

DECLARE grid[0:1, 0:1] OF INTEGER


grid[0][0] ← 1
grid[0][1] ← 2
grid[1][0] ← 3
grid[1][1] ← 4

2. Accessing Elements
Python:
print(scores[1]) # Output: 90
print(grid[1][0]) # Output: 3

You might also like