0% found this document useful (0 votes)
9 views37 pages

Python Labs Study Guide for Exams

The document is a comprehensive study guide for Python programming labs prepared for the final lab exam at the International University of Rabat in December 2025. It includes various projects covering data types, loops, conditional statements, lists, dictionaries, tuples, and functions, along with exercises and solutions. Each section provides detailed explanations and examples to aid in understanding the concepts and preparing for the exam.

Uploaded by

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

Python Labs Study Guide for Exams

The document is a comprehensive study guide for Python programming labs prepared for the final lab exam at the International University of Rabat in December 2025. It includes various projects covering data types, loops, conditional statements, lists, dictionaries, tuples, and functions, along with exercises and solutions. Each section provides detailed explanations and examples to aid in understanding the concepts and preparing for the exam.

Uploaded by

jeromejeje2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming Labs

Complete Study Guide with Corrections


Prepared for Final Lab Exam
International University of Rabat
December 2025

Contents
1 Introduction 2

2 Project 1: Data Types and Basic Operations 2


2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Exercise 1: Type Prediction and Operations . . . . . . . . . . . . . . . . 2
2.2.1 Problem Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2.2 Solution and Explanation . . . . . . . . . . . . . . . . . . . . . . 2
2.3 Exercise 2: Variable Types and Mathematical Operations . . . . . . . . . 4
2.3.1 Part A: Variable Types . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3.2 Part B: Variable Swapping . . . . . . . . . . . . . . . . . . . . . . 4
2.3.3 Part C: Disc Surface Area . . . . . . . . . . . . . . . . . . . . . . 5
2.3.4 Part D: Right Triangle Angle . . . . . . . . . . . . . . . . . . . . 6
2.4 Exercise 3: String Manipulation . . . . . . . . . . . . . . . . . . . . . . . 6
2.4.1 Part A: Case Conversion . . . . . . . . . . . . . . . . . . . . . . . 6
2.4.2 Part B: Character Swapping . . . . . . . . . . . . . . . . . . . . . 7
2.4.3 Part C: Character Replacement . . . . . . . . . . . . . . . . . . . 7
2.4.4 Part D: String Length . . . . . . . . . . . . . . . . . . . . . . . . 8

3 Project 2: Loops and Conditional Statements 8


3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 Exercise 1: Basic Conditional Operations . . . . . . . . . . . . . . . . . . 8
3.2.1 Part A: Basic Calculator . . . . . . . . . . . . . . . . . . . . . . . 8
3.2.2 Part B: Grade Calculator . . . . . . . . . . . . . . . . . . . . . . 9
3.2.3 Part C: Remove Special Characters . . . . . . . . . . . . . . . . . 9
3.2.4 Part D: Palindrome Checker . . . . . . . . . . . . . . . . . . . . . 10
3.3 Exercise 2: Loops and Number Operations . . . . . . . . . . . . . . . . . 10
3.3.1 Part A: Prime Number and Divisors . . . . . . . . . . . . . . . . 10
3.3.2 Part B: Fibonacci Sequence . . . . . . . . . . . . . . . . . . . . . 11
3.3.3 Part C: Factorial Calculation . . . . . . . . . . . . . . . . . . . . 12
3.4 Exercise 3: Complex Conditional Logic . . . . . . . . . . . . . . . . . . . 12
3.4.1 Part A: Series Sum . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4.2 Part B: Quadratic Equation Solver . . . . . . . . . . . . . . . . . 13

1
Computer Programming 2024/2025 Python Labs Study Guide

3.4.3 Part C: Discount Calculator . . . . . . . . . . . . . . . . . . . . . 14


3.4.4 Part D: Severance Pay Calculator . . . . . . . . . . . . . . . . . . 14

4 Project 3: Lists 15
4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.2 Exercise 1: Animal List Manipulation . . . . . . . . . . . . . . . . . . . . 15
4.3 Exercise 2: Find Largest Element . . . . . . . . . . . . . . . . . . . . . . 16
4.4 Exercise 3: List Manipulations . . . . . . . . . . . . . . . . . . . . . . . . 17
4.4.1 Part A: Index-wise Addition . . . . . . . . . . . . . . . . . . . . . 17
4.4.2 Part B: Nested Loop Concatenation . . . . . . . . . . . . . . . . . 17
4.4.3 Part C: Remove Empty Strings . . . . . . . . . . . . . . . . . . . 18
4.4.4 Part D: Remove All Occurrences . . . . . . . . . . . . . . . . . . 18

5 Project 4: Dictionaries 18
5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.2 Exercise 1: Dictionary Operations . . . . . . . . . . . . . . . . . . . . . . 19
5.2.1 Part A: Lists to Dictionary . . . . . . . . . . . . . . . . . . . . . . 19
5.2.2 Part B: Merge Dictionaries . . . . . . . . . . . . . . . . . . . . . . 19
5.2.3 Part C: Extract Specific Keys . . . . . . . . . . . . . . . . . . . . 20
5.2.4 Part D: Square Dictionary . . . . . . . . . . . . . . . . . . . . . . 20
5.2.5 Part E: Drop Empty Items . . . . . . . . . . . . . . . . . . . . . . 20
5.2.6 Part F: Maximum and Minimum Values . . . . . . . . . . . . . . 21
5.2.7 Part G: Word Count . . . . . . . . . . . . . . . . . . . . . . . . . 21

6 Project 5: Dictionaries and Tuples 22


6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6.2 Exercise 1: Student Management System . . . . . . . . . . . . . . . . . . 22
6.3 Exercise 2: Tuple Operations . . . . . . . . . . . . . . . . . . . . . . . . 24
6.3.1 Part A: Single Item Tuple . . . . . . . . . . . . . . . . . . . . . . 24
6.3.2 Part B: Copy Elements . . . . . . . . . . . . . . . . . . . . . . . . 24
6.3.3 Part C: Modify Nested Tuple . . . . . . . . . . . . . . . . . . . . 24
6.3.4 Part D: Sort Tuple of Tuples . . . . . . . . . . . . . . . . . . . . . 25
6.3.5 Part E: Count Occurrences . . . . . . . . . . . . . . . . . . . . . . 25
6.3.6 Part F: Check All Items Same . . . . . . . . . . . . . . . . . . . . 25
6.4 Exercise 3: List Conversions . . . . . . . . . . . . . . . . . . . . . . . . . 26
6.4.1 Part A: Lists to Tuple of Tuples . . . . . . . . . . . . . . . . . . . 26
6.4.2 Part B: Lists to Dictionary . . . . . . . . . . . . . . . . . . . . . . 26

7 Project 6: Functions 26
7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
7.2 Exercise 1: Mathematical Functions . . . . . . . . . . . . . . . . . . . . . 27
7.2.1 Part A: List Statistics Function . . . . . . . . . . . . . . . . . . . 27
7.2.2 Part B: sin(x)/x Function . . . . . . . . . . . . . . . . . . . . . . 27
7.2.3 Part C: Factorial Function . . . . . . . . . . . . . . . . . . . . . . 28
7.2.4 Part D: Taylor Series for ex . . . . . . . . . . . . . . . . . . . . . 28
7.2.5 Part E: Recursive Sequence . . . . . . . . . . . . . . . . . . . . . 28
7.3 Exercise 2: Employee Bonus System . . . . . . . . . . . . . . . . . . . . . 29
7.4 Project 6 Suite: Sales Statistics . . . . . . . . . . . . . . . . . . . . . . . 31

2
Computer Programming 2024/2025 Python Labs Study Guide

8 Key Concepts Summary 32


8.1 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
8.2 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
8.3 Common Mistakes to Avoid . . . . . . . . . . . . . . . . . . . . . . . . . 33

9 Exam Preparation Tips 33


9.1 Study Strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
9.2 Time Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
9.3 Debugging Checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

10 Quick Reference 34
10.1 Essential Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
10.2 String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
10.3 List Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
10.4 Dictionary Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

11 Conclusion 34

3
Computer Programming 2024/2025 Python Labs Study Guide

1 Introduction
This comprehensive study guide covers all six Python programming lab projects from the
Computer Programming course (2024/2025). Each section includes:

• Problem statements and requirements

• Complete corrected solutions with explanations

• Step-by-step code breakdowns

• Key concepts and best practices

• Common mistakes to avoid

This guide is designed to help you prepare for your final lab exam by reviewing all
the fundamental Python concepts covered throughout the semester.

2 Project 1: Data Types and Basic Operations


2.1 Overview
Project 1 focuses on fundamental Python concepts including data types, type conversion,
mathematical operations, and string manipulation.

2.2 Exercise 1: Type Prediction and Operations


2.2.1 Problem Statement
Predict the result of various Python operations involving arithmetic, strings, and type
conversions.

2.2.2 Solution and Explanation

1 # ======== = = == = = = == = = Exercise 1 = = = == = = == = = == = = == = =
2

3 # Operation 1: Power operation


4 var = (1+2) **3
5 print ( var ) # Output : 27
6 # Explanation : (1+2) = 3 , then 3**3 = 27
7

8 # Operation 2: String repetition


9 var = " Da " * 4
10 print ( var ) # Output : DaDaDaDa
11 # Explanation : Multiplying a string repeats it
12

13 # Operation 3: String + Integer ( This causes an error !)


14 var = " Da " + 3
15 print ( var ) # TypeError : can only concatenate str to str
16 # Explanation : Cannot add string and integer directly
17

4
Computer Programming 2024/2025 Python Labs Study Guide

18 # Operation 4: String concatenation and repetition


19 var = ( " Pa " + " La " ) * 2
20 print ( var ) # Output : PaLaPaLa
21 # Explanation : First concatenate " Pa "+" La " = " PaLa " , then repeat
twice
22

23 # Operation 5: String and division ( This causes an error !)


24 var = ( " Da " *4) / 2
25 print ( var ) # TypeError : unsupported operand type ( s )
26 # Explanation : Cannot divide a string
27

28 # Operation 6: Float division


29 var = 5 / 2
30 print ( var ) # Output : 2.5
31 # Explanation : Regular division returns float
32

33 # Operation 7: Integer division ( floor division )


34 var = 5 // 2
35 print ( var ) # Output : 2
36 # Explanation : Floor division returns integer part only
37

38 # Operation 8: Modulo operation


39 var = 5 % 2
40 print ( var ) # Output : 1
41 # Explanation : Remainder when 5 is divided by 2
42

43 # Operation 9: Type conversion and string repetition


44 var = str (4) * int ( " 3 " )
45 print ( var ) # Output : 444
46 # Explanation : str (4) = "4" , int ("3") = 3 , so "4" * 3 = "444"
47

48 # Operation 10: Type conversion and addition


49 var = int ( " 3 " ) + float ( " 3.2 " )
50 print ( var ) # Output : 6.2
51 # Explanation : int ("3") = 3 , float ("3.2") = 3.2 , sum = 6.2
52

53 # Operation 11: Invalid operation


54 var = str (3) * float ( " 3.2 " )
55 print ( var ) # TypeError : can ’t multiply string by non - int
56 # Explanation : Cannot multiply string by float
57

58 # Operation 12: Division result to string and repetition


59 var = str (3/4) * 2
60 print ( var ) # Output : 0.750.75
61 # Explanation : 3/4 = 0.75 , str (0.75) = "0.75" , repeated twice
62

63 # Operation 13: Variable assignment and concatenation


64 str1 , str2 , str3 = " got ready . " , " Paul " , " Michel "
65 var = str2 + str1
66 print ( var ) # Output : Paul got ready .
67

5
Computer Programming 2024/2025 Python Labs Study Guide

68 var = str3 + str1


69 print ( var ) # Output : Michel got ready .
70

71 var = str2 + " and " + str3 + " got ready \ n "
72 print ( var ) # Output : Paul and Michel got ready
Listing 1: Exercise 1 - Operations and Type Predictions
Key Concepts:

• Type Compatibility: You cannot directly mix incompatible types (string + int)

• String Repetition: string * int repeats the string

• Division Types: / (float division) vs // (floor division)

• Modulo Operator: % returns remainder

• Type Conversion: str(), int(), float() functions

2.3 Exercise 2: Variable Types and Mathematical Operations


2.3.1 Part A: Variable Types

1 # a - Define 3 variables and display their types


2 var_str = " I Love Python "
3 var_int = 10
4 var_decimal = 17.9
5

6 print ( " The type of var_str is : " , type ( var_str ) ) # < class ’ str
’>
7 print ( " The type of var_int is : " , type ( var_int ) ) # < class ’ int
’>
8 print ( " The type of var_decimal is : " , type ( var_decimal ) ) # < class
’ float ’>
Listing 2: Variable Types Display
Explanation:

• type() function returns the data type of a variable

• Three basic types: str (string), int (integer), float (decimal)

2.3.2 Part B: Variable Swapping

1 # b - Exchange contents of two integers A and B


2 A = int ( input ( " Enter the value of integer ( A ) : " ) )
3 B = int ( input ( " Enter the value of integer ( B ) : " ) )
4

5 print ( " \ nBefore exchange : " )


6 print ( " the value of A : " , A )
7 print ( " the value of B : " , B )
8

6
Computer Programming 2024/2025 Python Labs Study Guide

9 # Swapping using temporary variable


10 temp = A
11 A = B
12 B = temp
13

14 print ( " \ nAfter exchange : " )


15 print ( " the value of A : " , A )
16 print ( " the value of B : " , B )
Listing 3: Swapping Two Variables
Step-by-Step Explanation:
1. Store the value of A in a temporary variable temp

2. Assign B’s value to A (now A = B)

3. Assign temp’s value (original A) to B (now B = original A)

4. Result: Values are swapped


Alternative Method (Pythonic way):
1 A, B = B, A # Swap in one line without temp variable

2.3.3 Part C: Disc Surface Area

1 # c - Calculate surface area of a cut disc


2 import math
3

4 r_ext = float ( input ( " Enter the outer radius ( rext ) : " ) )
5 r_int = float ( input ( " Enter the inner radius ( rint ) : " ) )
6

7 # Calculate outer circle area


8 surface_ext = math . pi * math . pow ( r_ext , 2)
9 # Calculate inner circle area
10 surface_int = math . pi * math . pow ( r_int , 2)
11

12 # Surface area is the difference


13 surface_Area = surface_ext - surface_int
14

15 print ( f " The surface area of the cut disc is : { round ( surface_Area ,
2) } " )
Listing 4: Calculate Cut Disc Surface Area
Mathematical Explanation:
• Formula: Area of circle = πr2

• Cut disc area = Outer circle area - Inner circle area


2 2
• A = πrext − πrint

• [Link] provides the value of π (3.14159...)

7
Computer Programming 2024/2025 Python Labs Study Guide

• [Link](r, 2) calculates r2 (can also use r**2)

• round(value, 2) rounds to 2 decimal places

2.3.4 Part D: Right Triangle Angle

1 # d - Calculate angle alpha using opposite side and hypotenuse


2 opposite = float ( input ( " Enter the length of the opposite side : " )
)
3 hypotenuse = float ( input ( " Enter the length of the hypotenuse : " ) )
4

5 alpha = 0
6

7 # Validate input : hypotenuse must be greater than opposite


8 if opposite >= hypotenuse :
9 print ( " The hypotenuse must be greater than the opposite side .
")
10 else :
11 # Calculate angle using inverse sine ( arcsin )
12 alpha = math . asin ( opposite / hypotenuse )
13

14 # Convert from radians to degrees


15 alpha = math . degrees ( alpha )
16

17 print ( f " The angle alpha is : { round ( alpha , 2) } degrees " )


Listing 5: Calculate Angle in Right Triangle
Mathematical Explanation:
opposite
• In a right triangle: sin(α) = hypotenuse
 
opposite
• To find α: α = arcsin hypotenuse

• [Link]() returns angle in radians

• [Link]() converts radians to degrees

• Input validation ensures hypotenuse > opposite

2.4 Exercise 3: String Manipulation


2.4.1 Part A: Case Conversion

1 # a - String case conversions


2 name = " Elizabeth "
3

4 # Convert to lowercase
5 lower_case = name . lower ()
6 print ( " Name in lower case : " , lower_case ) # elizabeth
7

8 # Convert to uppercase

8
Computer Programming 2024/2025 Python Labs Study Guide

9 upper_case = name . upper ()


10 print ( " Name in UPPER case : " , upper_case ) # ELIZABETH
11

12 # Title case ( first letter uppercase , rest lowercase )


13 capitalized_name = name . title ()
14 print ( " Name with first letter UPPER : " , capitalized_name ) #
Elizabeth
Listing 6: String Case Manipulation
String Methods Explained:

• .lower(): Converts all characters to lowercase

• .upper(): Converts all characters to uppercase

• .title(): Capitalizes first letter of each word

2.4.2 Part B: Character Swapping

1 # b - Swap first two characters between strings


2 str_1 = input ( " Enter the first str : " )
3 str_2 = input ( " Enter the second str : " )
4

5 # Take first 2 chars from str_2 and remaining from str_1


6 new_str1 = str_2 [:2] + str_1 [2:]
7

8 # Take first 2 chars from str_1 and remaining from str_2


9 new_str2 = str_1 [:2] + str_2 [2:]
10

11 # Concatenate with space


12 result = new_str1 + " " + new_str2
13

14 print ( result )
15 # Example : Input : " abc " , " xyz " -> Output : " xyc abz "
Listing 7: Swap First Two Characters of Strings
String Slicing Explanation:

• str[:2]: Gets characters from index 0 to 1 (first 2 chars)

• str[2:]: Gets characters from index 2 to end

• Slicing format: str[start:end] (end is exclusive)

2.4.3 Part C: Character Replacement

1 # c - Replace ’a ’ with ’e ’
2 strVar = input ( " Enter a string : " )
3

4 new_strVar = strVar . replace ( ’a ’ , ’e ’)


5

9
Computer Programming 2024/2025 Python Labs Study Guide

6 print ( " Modified string : " , new_strVar )


7 # Example : " apple " -> " epple "
Listing 8: Replace Characters in String
Explanation:

• .replace(old, new): Replaces all occurrences of old with new

• Returns a new string (strings are immutable in Python)

2.4.4 Part D: String Length

1 # d - Print string length


2 strVar = input ( " Enter a string : " )
3

4 lengthStr = len ( strVar )


5

6 print ( " Sample Output : " , strVar )


7 print ( " Length of String : " , lengthStr )
Listing 9: Calculate String Length
Explanation:

• len() function returns the number of characters in a string

• Includes spaces and special characters

3 Project 2: Loops and Conditional Statements


3.1 Overview
Project 2 introduces control flow structures: conditional statements (if/elif/else) and
loops (for/while).

3.2 Exercise 1: Basic Conditional Operations


3.2.1 Part A: Basic Calculator

1 # a- Basic arithmetic calculator


2 num1 = float ( input ( " Enter the first number : " ) )
3 num2 = float ( input ( " Enter the second number : " ) )
4 op = input ( " Select operation (+ , - ,* ,/) : " )
5

6 result = 0
7

8 if op == ’+ ’:
9 result = num1 + num2
10 elif op == ’ - ’:
11 result = num1 - num2
12 elif op == ’* ’:

10
Computer Programming 2024/2025 Python Labs Study Guide

13 result = num1 * num2


14 else : # Division case
15 if num2 == 0:
16 result = ’ Division by zero is not allowed ! ’
17 else :
18 result = num1 / num2
19

20 print ( result )
Listing 10: Simple Calculator with User Choice
Key Concepts:

• if-elif-else chain: Tests multiple conditions sequentially

• Nested if: Checks for division by zero before dividing

• Input validation: Prevents runtime errors

3.2.2 Part B: Grade Calculator

1 # b - Calculate student grade


2 percentage = float ( input ( " Enter the percentage : " ) )
3 Grade = ’A ’
4

5 if percentage >= 90:


6 Grade = ’A ’
7 elif percentage >= 80:
8 Grade = ’B ’
9 elif percentage >= 70:
10 Grade = ’C ’
11 elif percentage >= 60:
12 Grade = ’D ’
13 else :
14 Grade = ’F ’
15

16 print ( " Grade : " , Grade )


Listing 11: Student Grade Based on Percentage
Logic Explanation:

• Conditions are checked from highest to lowest

• Once a condition is True, remaining conditions are skipped

• If percentage = 85: First condition (¿=90) False, second (¿=80) True Grade = ’B’

3.2.3 Part C: Remove Special Characters

1 # c - Remove special characters


2 VarStr = " I L@ove Pyt ^& ho - n L - angu / age "
3

11
Computer Programming 2024/2025 Python Labs Study Guide

4 for st in VarStr :
5 # Check if character is not alphabetic and not a space
6 if st . isalpha () == False and st != ’ ’:
7 VarStr = VarStr . replace ( st , ’ ’)
8

9 print ( VarStr ) # Output : " I Love Python Language "


Listing 12: Remove Special Symbols from String
Explanation:

• .isalpha(): Returns True if character is alphabetic

• Loop through each character in the string

• If character is not alphabetic AND not a space, remove it

• st != ’ ’: Keeps spaces in the string

3.2.4 Part D: Palindrome Checker

1 # d - Check palindrome
2 VarStr = input ( " Enter the string : " )
3 isPalindrome = False
4

5 if VarStr [:: -1] == VarStr [0::]:


6 isPalindrome = True
7 else :
8 isPalindrome = False
9

10 print ( isPalindrome )
Listing 13: Check if String is Palindrome
Explanation:

• VarStr[::-1]: Reverses the string (step = -1)

• VarStr[0::]: Original string (equivalent to VarStr)

• Palindrome: String that reads same forwards and backwards

• Examples: ”radar”, ”level”, ”madam”

3.3 Exercise 2: Loops and Number Operations


3.3.1 Part A: Prime Number and Divisors

1 # a - Find proper divisors


2 num = 0
3 while num < 1:
4 num = int ( input ( " Enter a strictly positive integer : " ) )
5

6 print ( f " Proper divisors of { num } without repetition : " , end = " " )

12
Computer Programming 2024/2025 Python Labs Study Guide

8 i = 1
9 countD = 0
10

11 while i <= num /2:


12 if num % i == 0:
13 countD += 1
14 print (i , end = " " )
15 i += 1
16

17 if countD == 0:
18 print ( " none ! It is prime . " )
Listing 14: Find Proper Divisors or Check Prime
Step-by-Step Explanation:

1. Input Validation: Loop until user enters positive integer

2. Divisor Finding: Check all numbers from 1 to num/2

3. Why num/2? No divisor exists beyond half the number

4. Modulo Check: If num % i == 0, i is a divisor

5. Count Divisors: Track how many divisors found

6. Prime Check: If count = 0, number is prime

3.3.2 Part B: Fibonacci Sequence

1 # b - Display Fibonacci series up to N terms


2 N = int ( input ( " Enter the N terms : " ) )
3 num1 = 0
4 num2 = 1
5 next_number = num2
6 i = 1
7

8 while i <= N :
9 print ( next_number , end = " " )
10 i += 1
11 num1 = num2
12 num2 = next_number
13 next_number = num1 + num2
Listing 15: Generate Fibonacci Series
Fibonacci Logic:

• Sequence: 1, 1, 2, 3, 5, 8, 13, 21...

• Each number is sum of previous two numbers

• Initialize: num1 = 0, num2 = 1

13
Computer Programming 2024/2025 Python Labs Study Guide

• Loop: next = num1 + num2, then shift variables


Variable Updates:
Iteration num1 num2 next Output
1 0 1 1 1
2 1 1 2 1
3 1 2 3 2
4 2 3 5 3
5 3 5 8 5

3.3.3 Part C: Factorial Calculation

1 # c - Find factorial of N
2 N = int ( input ( " Enter a strictly positive integer : " ) )
3 fact = 1
4

5 for i in range (1 , N +1) :


6 fact = fact * i
7

8 print ( f " The factorial of { N } is : " , end = " " )


9 print ( fact )
Listing 16: Calculate Factorial of N
Factorial Explanation:
• Definition: n! = n × (n − 1) × (n − 2) × ... × 1
• Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
• range(1, N+1): Generates numbers from 1 to N (inclusive)
• Multiply fact by each number in the range

3.4 Exercise 3: Complex Conditional Logic


3.4.1 Part A: Series Sum

1 # a - Find sum of series


2 N = int ( input ( " Enter the N terms : " ) )
3

4 start = 3
5 sumN = 0
6

7 print ( " serie : " , end = " " )


8 for i in range (0 , N ) :
9 print ( start , end = " " )
10 sumN += start
11 start = ( start * 10) + 3
12

13 print ( " \ nSum of above serie is : " , sumN )


Listing 17: Sum of Series 3 + 33 + 333 + ...

14
Computer Programming 2024/2025 Python Labs Study Guide

Pattern Explanation:
• Term 1: 3
• Term 2: 3 * 10 + 3 = 33
• Term 3: 33 * 10 + 3 = 333
• Term 4: 333 * 10 + 3 = 3333
• General: next term = previous term * 10 + 3

3.4.2 Part B: Quadratic Equation Solver

1 # b - Solve quadratic equation


2 import math
3

4 a = int ( input ( " Enter the value of a : " ) )


5 b = int ( input ( " Enter the value of b : " ) )
6 c = int ( input ( " Enter the value of c : " ) )
7

8 # Calculate discriminant
9 delta = math . pow (b , 2) - 4* a * c
10

11 if delta > 0:
12 # Two real and distinct roots
13 x1 = ( - b - math . sqrt ( delta ) ) / (2* a )
14 x2 = ( - b + math . sqrt ( delta ) ) / (2* a )
15 print ( f " Two real and distinct roots : { x1 } and { x2 } " )
16

17 elif delta == 0:
18 # One real and repeated root
19 x = -b / (2* a )
20 print ( f " One real and repeated root : { x } " )
21

22 else : # delta < 0


23 # Two complex roots
24 real_part = -b / (2 * a )
25 imaginary_part = math . sqrt ( - delta ) / (2 * a )
26 y1 = f " { real_part } + i { imaginary_part } "
27 y2 = f " { real_part } - i { imaginary_part } "
28 print ( f " Two complex roots : { y1 } and { y2 } " )
Listing 18: Solve Quadratic Equation ax + bx + c = 0
Mathematical Background: √
2
The quadratic formula: x = −b± 2ab −4ac
Discriminant: ∆ = b2 − 4ac

• If ∆ > 0: Two real distinct roots


• If ∆ = 0: One repeated root
• If ∆ < 0: Two complex conjugate roots

15
Computer Programming 2024/2025 Python Labs Study Guide

3.4.3 Part C: Discount Calculator

1 # c - Calculate discount and amount to pay


2 purchase = float ( input ( " Enter the purchase amount : " ) )
3

4 discount = 0
5

6 if purchase > 5000:


7 discount = 0.20 # 20% discount
8 elif purchase > 3000:
9 discount = 0.15 # 15% discount
10 elif purchase > 1000:
11 discount = 0.10 # 10% discount
12 else :
13 discount = 0.0 # No discount
14

15 amountPaid = purchase * (1 - discount )


16

17 if discount > 0:
18 print ( f " the discount is { discount } and amount to be paid is {
amountPaid } " )
19 else :
20 print ( " No discount for amounts <= 1000 MAD " )
Listing 19: Calculate Discount Based on Purchase Amount
Discount Tiers:
Purchase Amount Discount
> 5000 MAD 20%
3000 - 5000 MAD 15%
1000 - 3000 MAD 10%
< 1000 MAD 0%

3.4.4 Part D: Severance Pay Calculator

1 # d - Calculate severance pay


2 age = int ( input ( " Enter the age : " ) )
3 seniority = int ( input ( " Enter the seniority : " ) )
4 last_salary = float ( input ( " Enter the last salary : " ) )
5

6 # Base severance based on seniority


7 if seniority <= 10 and seniority >= 1:
8 severance_pay = ( last_salary / 2) * seniority
9 else :
10 severance_pay = last_salary * seniority
11

12 # Additional severance for age


13 if age >= 46 and age <= 49:
14 severance_pay += 2 * last_salary
15 elif age >= 50:
16 severance_pay += 5 * last_salary

16
Computer Programming 2024/2025 Python Labs Study Guide

17

18 print ( severance_pay )
Listing 20: Calculate Employee Severance Pay
Severance Calculation Rules:
Base Severance:

• 1-10 years: 0.5 * monthly salary * years

• > 10 years: 1.0 * monthly salary * years

Age Bonus:

• 46-49 years: +2 months salary

• ≥ 50 years: +5 months salary

4 Project 3: Lists
4.1 Overview
Project 3 covers list operations, manipulation, and traversal techniques in Python.

4.2 Exercise 1: Animal List Manipulation


1 # ======== = = == = = = == = = Exercise 1 = = = == = = == = = == = = == = =
2 animal_list = [ " rabbit " , " cat " , " dog " , " puppy " , " dragon " , "
platypus " ]
3

4 # a - Display all elements


5 for animal in animal_list :
6 print ( animal , end = " " )
7

8 # b - Display list in reverse order


9 animal_list . reverse ()
10 for animal in animal_list :
11 print ( animal , end = " " )
12

13 # c - Display list in sorted order


14 animal_list . sort ()
15 for animal in animal_list :
16 print ( animal , end = " " )
17

18 # d - Add element ’ troll ’


19 animal_list . append ( " troll " )
20

21 # e - Remove all domestic animals


22 domestic_animals = [ " rabbit " , " cat " , " dog " , " puppy " ]
23 for animal in domestic_animals :
24 animal_list . remove ( animal )
25

17
Computer Programming 2024/2025 Python Labs Study Guide

26 # Display result
27 for animal in animal_list :
28 print ( animal , end = " " )
Listing 21: List Operations - Display, Reverse, Sort, Add, Remove
List Methods Explained:

• .reverse(): Reverses list in-place (modifies original)

• .sort(): Sorts list alphabetically in-place

• .append(item): Adds item to end of list

• .remove(item): Removes first occurrence of item

4.3 Exercise 2: Find Largest Element


1 # ======== = = == = = = == = = Exercise 2 = = = == = = == = = == = = == = =
2 # a - Create list from user input
3 List_number = []
4 n = int ( input ( " Enter the dimension of the list : " ) )
5

6 i = 0
7 while ( i < n ) :
8 num = int ( input ( f " Enter the number_ { i }: " ) )
9 List_number . append ( num )
10 i += 1
11

12 print ( List_number )
13

14 # b - Determine largest element


15 largest_value = max ( List_number )
16

17 # c - Print largest value


18 print ( largest_value )
19

20 # d - Print index of largest element


21 index_number = List_number . index ( largest_value )
22 print ( index_number )
Listing 22: Find Maximum Value and Its Index
Key Functions:

• max(list): Returns maximum value in list

• [Link](value): Returns index of first occurrence

• Lists are 0-indexed (first element at index 0)

18
Computer Programming 2024/2025 Python Labs Study Guide

4.4 Exercise 3: List Manipulations


4.4.1 Part A: Index-wise Addition

1 # a - Add two lists index - wise


2 list1 = [ " M " , " na " , " i " , " Ke " ]
3 list2 = [ " y " , " me " , " s " , " lly " ]
4 lists_index_Wise = []
5

6 length1 = len ( list1 )


7 length2 = len ( list2 )
8

9 # Find shorter length


10 if length1 < length2 :
11 lengthIW = length1
12 else :
13 lengthIW = length2
14

15 # Concatenate elements at same index


16 for i in range (0 , lengthIW ) :
17 item = list1 [ i ] + list2 [ i ]
18 lists_index_Wise . append ( item )
19

20 print ( lists_index_Wise )
21 # Output : [ ’ My ’, ’ name ’, ’ is ’, ’ Kelly ’]
Listing 23: Add Two Lists Index-wise
Logic:
• Find minimum length to avoid index errors

• Concatenate strings at corresponding indices

• Result: [’M’+’y’, ’na’+’me’, ’i’+’s’, ’Ke’+’lly’]

4.4.2 Part B: Nested Loop Concatenation

1 # b - Concatenate two lists


2 list1 = [ " Hello " , " take " ]
3 list2 = [ " Dear " , " Sir " ]
4 listOutput = []
5

6 for item1 in list1 :


7 for item2 in list2 :
8 item = item1 + " " + item2
9 listOutput . append ( item )
10

11 print ( listOutput )
12 # Output : [ ’ Hello Dear ’, ’ Hello Sir ’, ’ take Dear ’, ’ take Sir ’]
Listing 24: Concatenate Lists with All Combinations
Nested Loop Explanation:

19
Computer Programming 2024/2025 Python Labs Study Guide

• Outer loop iterates through list1


• Inner loop iterates through list2 for each item in list1
• Creates all possible combinations: len(list1) * len(list2) = 4

4.4.3 Part C: Remove Empty Strings

1 # c - Remove empty strings


2 list1 = [ " Mike " , " " , " Emma " , " Kelly " , " " , " Brad " ]
3

4 for item in list1 :


5 if item == " " :
6 indexItem = list1 . index ( item )
7 del list1 [ indexItem ]
8

9 print ( list1 )
Listing 25: Remove Empty Strings from List
Note: The code checks for " " (single space), but should check for "" (empty string).
Better approach:
1 list1 = [ item for item in list1 if item != " " ]
2 # Or : list1 = list ( filter ( None , list1 ) )

4.4.4 Part D: Remove All Occurrences

1 # d - Remove all occurrences of item 20


2 list1 = [5 , 20 , 15 , 20 , 25 , 50 , 20]
3

4 for item in list1 :


5 if item == 20:
6 list1 . remove ( item )
7

8 print ( list1 )
Listing 26: Remove All Occurrences of Item 20
Warning: This code has a bug! Modifying list while iterating can skip elements.
Better approach:
1 list1 = [5 , 20 , 15 , 20 , 25 , 50 , 20]
2 while 20 in list1 :
3 list1 . remove (20)
4 # Or : list1 = [ item for item in list1 if item != 20]

5 Project 4: Dictionaries
5.1 Overview
Project 4 introduces dictionaries - key-value pair data structures for efficient data storage
and retrieval.

20
Computer Programming 2024/2025 Python Labs Study Guide

5.2 Exercise 1: Dictionary Operations


5.2.1 Part A: Lists to Dictionary

1 # a - Convert lists to dictionary


2 keys = [ ’ Ten ’ , ’ Twenty ’ , ’ Thirty ’]
3 values = [10 , 20 , 30]
4

5 # Create empty dictionary


6 res_dict = dict ()
7

8 for i in range ( len ( keys ) ) :


9 res_dict [ keys [ i ]] = values [ i ]
10

11 print ( res_dict )
12 # Output : { ’ Ten ’: 10 , ’ Twenty ’: 20 , ’ Thirty ’: 30}
Listing 27: Convert Two Lists into Dictionary
Alternative methods:
1 # Method 1: Using zip
2 res_dict = dict ( zip ( keys , values ) )
3

4 # Method 2: Dictionary comprehension


5 res_dict = { keys [ i ]: values [ i ] for i in range ( len ( keys ) ) }

5.2.2 Part B: Merge Dictionaries

1 # b - Merge two dictionaries


2 dict1 = { ’ Ten ’: 10 , ’ Twenty ’: 20 , ’ Thirty ’: 30}
3 dict2 = { ’ Thirty ’: 30 , ’ Fourty ’: 40 , ’ Fifty ’: 50}
4

5 for key in dict1 . keys () :


6 if key not in dict2 . keys () :
7 dict2 [ key ] = dict1 [ key ]
8

9 print ( dict2 )
10 # Output : { ’ Thirty ’: 30 , ’ Fourty ’: 40 , ’ Fifty ’: 50 , ’ Ten ’: 10 , ’
Twenty ’: 20}
Listing 28: Merge Two Dictionaries
Explanation:
• Loop through dict1 keys
• If key doesn’t exist in dict2, add it
• Preserves dict2 values for common keys (’Thirty’)
Modern Python method (3.9+):
1 merged = dict1 | dict2 # dict2 values override dict1

21
Computer Programming 2024/2025 Python Labs Study Guide

5.2.3 Part C: Extract Specific Keys

1 # c - Extract specific keys


2 Sample_dict = { " name " : " Kelly " , " age " : 25 , " salary " : 8000 , " city "
: " New york " }
3 keys = [ " name " , " salary " ]
4

5 new_dict = {}
6 for key in keys :
7 new_dict [ key ] = Sample_dict [ key ]
8

9 print ( new_dict )
10 # Output : { ’ name ’: ’ Kelly ’, ’ salary ’: 8000}
Listing 29: Extract Mentioned Keys from Dictionary
Dictionary comprehension version:
1 new_dict = { key : Sample_dict [ key ] for key in keys }

5.2.4 Part D: Square Dictionary

1 # d - Create square dictionary


2 n = int ( input ( " Enter a number : " ) )
3 dictSquare = {}
4

5 for i in range (1 , n +1) :


6 dictSquare [ i ] = i **2
7

8 print ( dictSquare )
9 # Example : n =5 -> {1: 1 , 2: 4 , 3: 9 , 4: 16 , 5: 25}
Listing 30: Create Dictionary with Squares

5.2.5 Part E: Drop Empty Items

1 # e - Drop empty items


2 BeforeDropping = { ’ Name ’: ’ Pooja ’ , ’ Age ’: 23 , ’ Gender ’: None ,
3 ’ Mark ’: 488 , ’ City ’: None }
4 AfterDropping = {}
5

6 for key , value in BeforeDropping . items () :


7 if value is not None :
8 AfterDropping [ key ] = value
9

10 print ( AfterDropping )
11 # Output : { ’ Name ’: ’ Pooja ’, ’ Age ’: 23 , ’ Mark ’: 488}
Listing 31: Remove None Values from Dictionary
Key Point: Use is not None instead of != None

22
Computer Programming 2024/2025 Python Labs Study Guide

5.2.6 Part F: Maximum and Minimum Values

1 # f - Get maximum and minimum values


2 Dictionary = { " m1 " : 78 , " m2 " : 89 , " m3 " : 64 , " m4 " : 35 , " m5 " : 71}
3 listVal = []
4

5 for value in Dictionary . values () :


6 listVal . append ( value )
7

8 MaximumValue = max ( listVal )


9 MinimumValue = min ( listVal )
10

11 for key , value in Dictionary . items () :


12 if value == MaximumValue :
13 print ( f " Maximum Value : ({ key } : { value }) " )
14 if value == MinimumValue :
15 print ( f " Minimum Value : ({ key } : { value }) " )
Listing 32: Find Max and Min Dictionary Values
Simpler approach:
1 max_key = max ( Dictionary , key = Dictionary . get )
2 min_key = min ( Dictionary , key = Dictionary . get )

5.2.7 Part G: Word Count

1 # g - Count word occurrences


2 String = " To change the overall look your document . To change the
look available in the gallery "
3 OutputDict = dict ()
4

5 words = String . split ()


6 for word in words :
7 countWord = String . count ( word )
8 OutputDict [ word ] = countWord
9

10 print ( OutputDict )
Listing 33: Count Word Occurrences in Sentence
Explanation:

• .split(): Splits string by whitespace into list of words

• .count(word): Counts occurrences of word in string

• Creates dictionary with word frequencies

23
Computer Programming 2024/2025 Python Labs Study Guide

6 Project 5: Dictionaries and Tuples


6.1 Overview
Project 5 combines dictionaries and tuples for complex data management, focusing on
student information systems.

6.2 Exercise 1: Student Management System


1 # ======== = = == = = = == = = Exercise 1 = = = == = = == = = == = = == = =
2 # Student information management system
3

4 students = []
5

6 # a - Input information for N students


7 num_students = int ( input ( " Enter the number of students : " ) )
8

9 for i in range ( num_students ) :


10 print ( f " \ nEnter details for student { i + 1}: " )
11 last_name = input ( " Last name : " )
12 first_name = input ( " First name : " )
13 enrollment _numbe r = input ( " Enrollment number : " )
14 date_of_birth = input ( " Date of birth ( DD / MM / YYYY ) : " )
15 exam_grade = float ( input ( " Exam grade : " ) )
16

17 # Store information in dictionary


18 student_info = {
19 ’ LastName ’: last_name ,
20 ’ FirstName ’: first_name ,
21 ’ EnrollmentNumber ’: enrollment_number ,
22 ’ DateofBirth ’: date_of_birth ,
23 ’ ExamGrade ’: exam_grade
24 }
25

26 students . append ( student_info )


Listing 34: Complete Student Management Program - Part 1
Data Structure:

• students: List of dictionaries

• Each dictionary represents one student

• Keys: LastName, FirstName, EnrollmentNumber, DateofBirth, ExamGrade

1 # b - Calculate class statistics


2

3 # Total Sum of Grades


4 Total_Sum_Grades = 0
5 for student in students :
6 Total_Sum_Grades += student [ ’ ExamGrade ’]

24
Computer Programming 2024/2025 Python Labs Study Guide

8 # Average ( MOY )
9 nbStudents = len ( students )
10 Average = Total_Sum_Grades / nbStudents
11

12 # Calculate grade percentage for each student


13 for student in students :
14 gradePercentage = ( student [ ’ ExamGrade ’] / Total_Sum_Grades ) *
100
15 student [ ’ gradePercentage ’] = gradePercentage
16

17 # Add success indicator


18 successThreshold = 10
19 for student in students :
20 if student [ ’ ExamGrade ’] > 10:
21 student [ ’ Succeeded ’] = ’ Yes ’
22 else :
23 student [ ’ Succeeded ’] = ’ No ’
Listing 35: Student Management - Part 2: Statistics
Statistics Explained:

• Total Sum: Sum of all student grades

• Average: Total sum divided by number of students

• Grade Percentage: (Student’s grade / Total sum) * 100

• Success Status: ’Yes’ if grade > 10, else ’No’

1 # c - Sort students by exam grade ( ascending )


2 students . sort ( key = lambda x : x [ ’ ExamGrade ’ ])
3

4 # d - Display results
5 print ( " \ nStudent Details :\ n " )
6 for student in students :
7 print ( f " Student : { student [ ’ FirstName ’]} { student [ ’ LastName ’]}
")
8 print ( f " Enrollment Number : { student [ ’ EnrollmentNumber ’]} " )
9 print ( f " Date of Birth : { student [ ’ DateofBirth ’]} " )
10 print ( f " Exam Grade : { student [ ’ ExamGrade ’]} " )
11 print ( f " gradePercentage : { student [ ’ gradePercentage ’]:.2 f }% "
)
12 print ( f " Succeeded : { student [ ’ Succeeded ’]} " )
13 print ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\ n " )
14

15 print ( ’ Total Sum of Grades : ’ , Total_Sum_Grades )


16 print ( " Class Average : " , Average )
Listing 36: Student Management - Part 3: Sort and Display
Lambda Function:

25
Computer Programming 2024/2025 Python Labs Study Guide

• lambda x: x[’ExamGrade’]: Anonymous function

• Takes student dictionary, returns ExamGrade value

• Used as sorting key

6.3 Exercise 2: Tuple Operations


6.3.1 Part A: Single Item Tuple

1 # a - Create single item tuple


2 SingTuple = (50 , ) # Note the comma !
3 print ( SingTuple )
Listing 37: Create Tuple with Single Item
Important: Comma is required for single-item tuple. Without it, Python treats it
as integer in parentheses.

6.3.2 Part B: Copy Elements

1 # b - Copy elements 44 and 55


2 TupleVar = (11 , 22 , 33 , 44 , 55 , 66)
3 newTupleVar = TupleVar [3:5] # Indices 3 and 4
4 print ( newTupleVar ) # Output : (44 , 55)
Listing 38: Copy Specific Elements from Tuple

6.3.3 Part C: Modify Nested Tuple

1 # c - Modify nested tuple


2 TupleVar = (11 , [22 , 33] , 44 , 55)
3 TupleVar [1][0] = 222
4 print ( TupleVar ) # Output : (11 , [222 , 33] , 44 , 55)
Listing 39: Modify List Inside Tuple
Key Concept:

• Tuples are immutable (cannot change elements)

• BUT if tuple contains mutable object (list), that object can be modified

• TupleVar[1] accesses the list

• TupleVar[1][0] accesses first element of that list

26
Computer Programming 2024/2025 Python Labs Study Guide

6.3.4 Part D: Sort Tuple of Tuples

1 # d - Sort tuple of tuples by 2 nd item


2 TupleVar = (( ’a ’ , 23) , ( ’b ’ , 37) , ( ’c ’ , 11) , ( ’d ’ , 29) )
3

4 # Convert to list for sorting


5 ListTupleVar = list ( TupleVar )
6

7 # Sort by second element


8 ListTupleVar . sort ( key = lambda x : x [1])
9

10 # Convert back to tuple


11 SortedTupleVar = tuple ( ListTupleVar )
12 print ( SortedTupleVar )
13 # Output : (( ’ c ’, 11) , ( ’ a ’, 23) , ( ’ d ’, 29) , ( ’ b ’, 37) )
Listing 40: Sort Tuple by Second Item
Process:
1. Convert tuple to list (tuples are immutable)

2. Sort list by second element of each inner tuple

3. Convert back to tuple

6.3.5 Part E: Count Occurrences

1 # e - Count occurrences of 50
2 TupleVar = (50 , 10 , 60 , 70 , 50)
3 count_50 = TupleVar . count (50)
4 print ( count_50 ) # Output : 2
Listing 41: Count Item Occurrences in Tuple

6.3.6 Part F: Check All Items Same

1 # f - Check if all items are the same


2 TupleVar = (30 , 30 , 31 , 30 , 30)
3

4 find = False
5 for Tp in TupleVar :
6 if Tp != TupleVar [0]:
7 find = True
8

9 if find == True :
10 print ( " Tuple items are not the same " )
11 else :
12 print ( " Tuple items are the same " )
Listing 42: Check if All Tuple Items Are Same
Logic:

27
Computer Programming 2024/2025 Python Labs Study Guide

• Compare each element to first element

• If any element differs, set flag to True

• All same flag stays False

6.4 Exercise 3: List Conversions


6.4.1 Part A: Lists to Tuple of Tuples

1 # a - Create tuple of tuples from two lists


2 L1 = [ ’ Rabat ’ , ’ Casa ’ , ’ Agadir ’ , ’ Beni Mellal ’ ,
3 ’ khouribgua ’ , ’ Fes ’ , ’ Nador ’ , ’ Dakhla ’]
4 L2 = [4 , 6 , 2 , 5 , 8 , 9 , 7 , 3]
5

6 ListResultTuple = []
7 for i in range ( len ( L1 ) ) :
8 ListResultTuple . append (( L1 [ i ] , L2 [ i ]) )
9

10 ResultTuple = tuple ( ListResultTuple )


11 print ( ResultTuple )
12 # Output : (( ’ Rabat ’, 4) , ( ’ Casa ’, 6) , ...)
Listing 43: Convert Two Lists to Tuple of Tuples
Alternative:
1 ResultTuple = tuple ( zip ( L1 , L2 ) )

6.4.2 Part B: Lists to Dictionary

1 # b - Create dictionary from two lists


2 OutputDict = dict ()
3 for i in range ( len ( L1 ) ) :
4 key = L1 [ i ]
5 value = L2 [ i ]
6 OutputDict [ key ] = value
7

8 print ( OutputDict )
9 # Output : { ’ Rabat ’: 4 , ’ Casa ’: 6 , ...}
Listing 44: Convert Two Lists to Dictionary

7 Project 6: Functions
7.1 Overview
Project 6 introduces modular programming through function definition, parameters, re-
turn values, and scope.

28
Computer Programming 2024/2025 Python Labs Study Guide

7.2 Exercise 1: Mathematical Functions


7.2.1 Part A: List Statistics Function

1 # a - Function to find min , max , average


2 def f ( L ) :
3 result = []
4 smallest = min ( L )
5 largest = max ( L )
6 average = sum ( L ) / len ( L )
7 result . append ( smallest )
8 result . append ( largest )
9 result . append ( average )
10 return result
11

12 # Test the function


13 numbers = [10 , 20 , 30 , 40 , 50]
14 result = f ( numbers )
15 print ( " Smallest : " , result [0])
16 print ( " Largest : " , result [1])
17 print ( " Average : " , result [2])
Listing 45: Function for Min, Max, and Average
Function Components:

• def f(L): Function definition with parameter L

• return result: Returns a list containing 3 values

• Calling: result = f(numbers)

7.2.2 Part B: sin(x)/x Function

1 # b - Function for sin ( x ) / x


2 import math
3

4 def f ( x ) :
5 if x == 0:
6 return 1 # Limit as x approaches 0
7 return math . sin ( x ) / x
8

9 x = 3.14
10 result = f ( x )
11 print ( f " f ({ x }) = { result } " )
Listing 46: Function for sin(x)/x
Mathematical Note:
sin(x)
• limx→0 x
=1

• Special case handling prevents division by zero

29
Computer Programming 2024/2025 Python Labs Study Guide

7.2.3 Part C: Factorial Function

1 # c - Factorial function
2 def CalcFactorielle ( n ) :
3 factorial = 1
4 if n == 0:
5 factorial = 1
6 else :
7 for i in range (1 , n +1) :
8 factorial *= i
9 return factorial
10

11 print ( CalcFactorielle (4) ) # Output : 24


Listing 47: Factorial Function

7.2.4 Part D: Taylor Series for ex

1 # d - Calculate e ^ x using Taylor series


2 def tylorExpression (n , x ) :
3 result = 1
4 for i in range (1 , n +1) :
5 result += ( x ** i ) / CalcFactorielle ( i )
6 return result
7

8 print ( tylorExpression (100 , 2) ) # Approximates e ^2


Listing 48: Taylor Series Exponential Function
Taylor Series:
x2 x3 xn
ex = 1 + x + + + ... +
2! 3! n!

7.2.5 Part E: Recursive Sequence

1 # e - Calculate sequence U_n


2 def U ( n ) :
3 Un = 1
4 Un_PREV = 1
5 Un_NEXT = 1
6

7 if n == 0 or n == 1:
8 return 1
9

10 for i in range (2 , n +1) :


11 Un_NEXT = Un + Un_PREV
12 Un_PREV = Un
13 Un = Un_NEXT
14

15 return Un
16

30
Computer Programming 2024/2025 Python Labs Study Guide

17 print ( U (5) ) # Output : 5


Listing 49: Calculate Sequence U n
Sequence Definition:
• U0 = 1, U1 = 1

• Un+1 = Un + Un−1

• This is the Fibonacci sequence starting at 1

7.3 Exercise 2: Employee Bonus System


1 # ======== = = == = = = == = = Exercise 2 = = = == = = == = = == = = == = =
2 from datetime import datetime
3

4 # 1 - Fill employee information


5 def fill_employees () :
6 employees = []
7 for i in range (6) :
8 cin = input ( " Enter CIN : " )
9 last_name = input ( " Enter Last Name : " )
10 first_name = input ( " Enter First Name : " )
11 Date_of_Birth = input ( " Enter Date of Birth ( YYYY - MM - DD ) :
")
12 hire_date = input ( " Enter Hire Date ( YYYY - MM - DD ) : " )
13 salary = float ( input ( " Enter Salary : " ) )
14

15 employees . append ({
16 " CIN " : cin ,
17 " LastName " : last_name ,
18 " FirstName " : first_name ,
19 " DateofBirth " : Date_of_Birth ,
20 " HireDate " : hire_date ,
21 " Salary " : salary ,
22 })
23 return employees
Listing 50: Employee Management - Part 1: Input

1 # 2 - Calculate years of experience


2 def calc_NAE ( employee ) :
3 dataNow = datetime . now ()
4 hire_date = datetime . strptime ( employee [ " HireDate " ] , " %Y -% m -% d
")
5 NAE = dataNow . year - hire_date . year
6 return NAE
7

8 # 3 - Calculate bonus
9 def calc_bonus ( salary , employee ) :
10 NAE = calc_NAE ( employee )
11 Bonus = 0

31
Computer Programming 2024/2025 Python Labs Study Guide

12

13 if NAE > 2 and NAE <= 4:


14 Bonus = salary
15 elif NAE > 4 and NAE <= 6:
16 Bonus = salary * 1.5
17 elif NAE > 6 and NAE <= 8:
18 Bonus = salary * 2
19 elif NAE > 8:
20 Bonus = salary * 4
21

22 return Bonus
23

24 # 4 - Assign bonuses to all employees


25 def assign_bonuses ( employees ) :
26 for employee in employees :
27 employee [ " Bonus " ] = calc_bonus ( employee [ " Salary " ] ,
employee )
Listing 51: Employee Management - Part 2: Calculations

1 # 5 - Display employees by hire date


2 def display ByHire Date ( hireDate ) :
3 for employee in employees :
4 if employee [ " HireDate " ] == hireDate :
5 print ( employee )
6

7 # 6 - Sort employees by salary


8 def sortBySalary ( employees ) :
9 empSorted = sorted ( employees , key = lambda x : x [ " Salary " ] ,
reverse = True )
10 return empSorted
11

12 # Main program
13 employees = fill_employees ()
14 assign_bonuses ( employees )
15 empSorted = sortBySalary ( employees )
16

17 print ( empSorted )
18 displayByH ireDat e ( ’ 2015 -12 -10 ’)
Listing 52: Employee Management - Part 3: Display and Sort
Function Design Principles:

• Single Responsibility: Each function has one clear purpose

• Modularity: Functions can be reused

• Parameters: Input data passed to function

• Return Values: Output data from function

32
Computer Programming 2024/2025 Python Labs Study Guide

7.4 Project 6 Suite: Sales Statistics


1 # ============ ===== Project 6 Suite ===== ====== ======
2

3 # 1 - Input all sales data


4 def Input_All_Data () :
5 L1 , L2 , L3 = [] , [] , []
6 print ( " Enter sales data for each product (8 products in total
):")
7 for i in range (8) :
8 l1 = float ( input ( f " Store 1 - Total Product { i +1}: " ) )
9 l2 = float ( input ( f " Store 2 - Total Product { i +1}: " ) )
10 l3 = float ( input ( f " Store 3 - Total Product { i +1}: " ) )
11 L1 . append ( int ( l1 ) )
12 L2 . append ( int ( l2 ) )
13 L3 . append ( int ( l3 ) )
14 return L1 , L2 , L3
15

16 # 2 - Calculate total per product


17 def C a l c u l a t e _ T o t a l _ P e r _ P r o d u c t ( L1 , L2 , L3 ) :
18 M = []
19 total_of_p roduct s = 8
20 for i in range ( t otal_o f_prod ucts ) :
21 M . append ( L1 [ i ] + L2 [ i ] + L3 [ i ])
22 return M
23

24 # 3 - Calculate total per store


25 def C a l c u l a t e _ T o t a l _ P e r _ S t o r e ( L1 , L2 , L3 ) :
26 TotalProduct_S1 = sum ( L1 )
27 TotalProduct_S2 = sum ( L2 )
28 TotalProduct_S3 = sum ( L3 )
29 P = [ TotalProduct_S1 , TotalProduct_S2 , TotalProduct_S3 ]
30 return P
31

32 # 4 - Calculate average per product


33 def c a l c u l a t e _ a v e r a g e _ p e r _ p r o d u c t ( M ) :
34 R = []
35 for total in M :
36 R . append ( total /3) # Divide by 3 stores
37 return R
38

39 # Main program
40 L1 , L2 , L3 = Input_All_Data ()
41

42 M = C a l c u l a t e _ T o t a l _ P e r _ P r o d u c t ( L1 , L2 , L3 )
43 print ( " Total quantity sold per product : " , M )
44

45 P = C a l c u l a t e _ T o t a l _ P e r _ S t o r e ( L1 , L2 , L3 )
46 print ( " Total quantity sold per store : " , P )
47

48 R = calculate_average_per_product (M)

33
Computer Programming 2024/2025 Python Labs Study Guide

49 print ( " Average quantity sold per product : " , R )


Listing 53: Sales Analysis Functions
Data Structure:

• L1, L2, L3: Sales quantities for 8 products in 3 stores

• M: Total quantity per product (sum across stores)

• P: Total quantity per store (sum across products)

• R: Average quantity per product

8 Key Concepts Summary


8.1 Data Types
Type Example Description
int 42, -10 Integer numbers
float 3.14, -0.5 Decimal numbers
str ”Hello”, ’Python’ Text strings
bool True, False Boolean values
list [1, 2, 3] Mutable ordered sequence
tuple (1, 2, 3) Immutable ordered sequence
dict {’key’: ’value’} Key-value pairs

8.2 Control Structures


Conditional Statements:
1 if condition :
2 # code block
3 elif another_ condit ion :
4 # code block
5 else :
6 # code block

Loops:
1 # For loop
2 for item in sequence :
3 # code block
4

5 # While loop
6 while condition :
7 # code block

34
Computer Programming 2024/2025 Python Labs Study Guide

8.3 Common Mistakes to Avoid


1. Division by zero: Always check before dividing

2. Index errors: Ensure index is within range

3. Type mismatches: Cannot add string + int directly

4. Modifying list during iteration: Can skip elements

5. Forgetting comma in single-item tuple: (50,) not (50)

6. Mutable default arguments: Avoid def func(L=[])

9 Exam Preparation Tips


9.1 Study Strategy
1. Understand, don’t memorize: Focus on logic and concepts

2. Practice typing code: Speed and accuracy are important

3. Review common patterns: Loops, conditionals, functions

4. Test edge cases: Empty lists, zero values, negative numbers

5. Read problems carefully: Understand requirements before coding

9.2 Time Management


• Read all questions first

• Start with easiest problems

• Leave time for testing and debugging

• Don’t get stuck on one problem

9.3 Debugging Checklist


• Syntax errors: Check parentheses, colons, indentation

• Logic errors: Trace through code with example values

• Runtime errors: Check for division by zero, index out of range

• Output format: Match expected output exactly

35
Computer Programming 2024/2025 Python Labs Study Guide

10 Quick Reference
10.1 Essential Functions
Function Description
print() Display output
input() Get user input
len() Length of sequence
type() Get data type
int(), float(), str() Type conversion
range(start, stop, step) Generate number sequence
max(), min(), sum() Aggregate functions
round(num, digits) Round to decimal places

10.2 String Methods


Method Description
.lower() Convert to lowercase
.upper() Convert to uppercase
.title() Title case
.replace(old, new) Replace substring
.split() Split into list
.count(substring) Count occurrences
.isalpha() Check if alphabetic

10.3 List Methods


Method Description
.append(item) Add to end
.remove(item) Remove first occurrence
.pop() Remove and return last item
.sort() Sort in place
.reverse() Reverse in place
.index(item) Find index of item
.count(item) Count occurrences

10.4 Dictionary Methods


Method Description
.keys() Get all keys
.values() Get all values
.items() Get key-value pairs
.get(key, default) Get value with default
.update(dict) Merge dictionaries

11 Conclusion
This study guide covers all six Python lab projects with detailed explanations and cor-
rections. Key takeaways for your final exam:

36
Computer Programming 2024/2025 Python Labs Study Guide

• Master fundamental data types and operations

• Understand control flow (if/else, loops)

• Practice list and dictionary manipulations

• Learn to write clean, modular functions

• Test your code with various inputs

• Manage time effectively during the exam

Good luck with your final lab exam!

This study guide was prepared for Computer Programming 2024/2025


International University of Rabat

37

You might also like