0% found this document useful (0 votes)
103 views76 pages

Cours Python AH

The document outlines a comprehensive introductory course on Python programming for first-year undergraduate students, covering fundamental concepts such as variables, control structures, data structures, functions, and file handling. It aims to develop problem-solving skills through practical examples and hands-on exercises, with specific learning objectives for students. The course content includes various chapters, assessments, and a collaborative project focused on transport fleet management.

Uploaded by

hayfaoueslati06
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)
103 views76 pages

Cours Python AH

The document outlines a comprehensive introductory course on Python programming for first-year undergraduate students, covering fundamental concepts such as variables, control structures, data structures, functions, and file handling. It aims to develop problem-solving skills through practical examples and hands-on exercises, with specific learning objectives for students. The course content includes various chapters, assessments, and a collaborative project focused on transport fleet management.

Uploaded by

hayfaoueslati06
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
You are on page 1/ 76

PROGRAMMING I:

INTRODUCTION TO
PYTHON

Dr. Asma Hadyaoui

YEAR: 1ST YEAR UNDERGRADUATE


ISTLS Asma HADYAOUI

Course Overview
This course offers a comprehensive introduction to Python programming. It
covers the fundamental concepts of programming, including variables, control
structures, data structures such as lists, matrices, and maps (dictionaries),
functions, and file handling. The course emphasizes the development of
problem-solving skills through practical examples and hands-on exercises. By
the end of the course, students will have the ability to write Python programs to
solve a variety of problems across multiple domains.

Learning Objectives
By the end of this course, students will:

• Understand and apply basic Python programming concepts, including


variables, data types, and control structures.

• Apply loops and conditionals to control the flow of a program.

• Design and implement Python functions for modular and reusable code.

• Manipulate and use lists to store and manage collections of data.

• Work with matrices (lists of lists) to handle two-dimensional data.

• Implement maps (dictionaries) to store and retrieve key-value pairs


efficiently.

• Solve practical problems using Python programming.

1
ISTLS Asma HADYAOUI

Course Content

Table des matières


Course Overview ............................................................................................................................1
Learning Objectives ......................................................................................................................1
Course Content ...............................................................................................................................2
Pre-Test .............................................................................................................................................7
Part 1: General Programming Knowledge (10 points) ..........................................................7
1.1. Multiple Choice Questions (5 points) ............................................................................7
1.2. True/False Questions (5 points) .....................................................................................8
Part 2: Python-Specific Concepts (15 points) ..........................................................................8
2.1. Short Answer Questions (5 points)................................................................................8
Part 3: Logic and Problem-Solving (10 points) ......................................................................10
3.1. Problem-Solving (5 points) ............................................................................................10
3.2. Algorithm Design (5 points) ..........................................................................................10
Pre-Test Evaluation ....................................................................................................................10
Chapter 1: Introduction to Python Programming .............................................................11
1. Programming Task: Print a Song .....................................................................................11
2. Performing Arithmetic Operations .................................................................................12
3. Commenting ........................................................................................................................13
4. Variables in Python ............................................................................................................13
5. String Formatting with f-strings .......................................................................................13
6. Assessments ........................................................................................................................15
Quiz (Multiple Choice) ...........................................................................................................15
Quiz (Short Answer) ...............................................................................................................16
Coding Task 1: Delivery Cost Calculation ...........................................................................16
Chapter 2: Conditional statements ........................................................................................17
1. Conditional Branching with if ...........................................................................................17

2
ISTLS Asma HADYAOUI

1.1. Comparison operators ..............................................................................................18


1.2. Indentation ..................................................................................................................19
1.3. Boolean expressions..................................................................................................20
1.4. Programming exercise : Calculate Employee Bonus ...........................................20
1.5. Programming exercise 2: Weather Outfit Suggestions .......................................21
1.6. Programming exercise 3: Solve a Cubic Equation................................................21
2. if-else Statements ...............................................................................................................22
3. Multiple Conditions with elif ............................................................................................23
3.1. Programming exercise: Alphabetically First Word ...............................................25
4. Combining conditions .......................................................................................................25
4.1. Simplified range conditions ......................................................................................26
4.2. Programming exercise : Middle Letter ...................................................................27
4.3. Programming exercise: Calculate Sales Tax ..........................................................27
5. Assessments ........................................................................................................................27
Quiz (True/False) .....................................................................................................................27
Coding Task 1: Vehicle Load Check .....................................................................................27
Coding Task 2: Shipping Eligibility .......................................................................................28
Chapter 3: Loops...........................................................................................................................29
1. while loop.............................................................................................................................29
1.1. Example 1: Fuel Level Monitoring for Trucks ........................................................29
1.2. Example 2 : PIN Entry for Cargo Access .................................................................30
1.3. Programming exercise: Cargo Check Continuation .............................................31
2. Loops with helper variables .............................................................................................31
2.1. Programming exercise: PIN Entry with Attempt Count ......................................32
3. Concatenating strings in Loops .......................................................................................32
4. Loops with conditions .......................................................................................................33
4.1. Initialisation, condition and update ........................................................................35
4.2. Programming exercise: Print Even Numbers ........................................................35
4.3. Programming exercise: Fix the code: Countdown ...............................................36
5. Writing complex conditions ..............................................................................................36

3
ISTLS Asma HADYAOUI

5.1. Programming exercise: Number Series .................................................................37


6. Assessments ........................................................................................................................37
Quiz (Short Answer) ...............................................................................................................37
Quiz (Multiple Choice) ...........................................................................................................38
Coding Task 1: Fleet Fuel Monitoring .................................................................................39
Coding Task 2: Container Weight Check ............................................................................39
Chapter 4: Python Functions ....................................................................................................41
1. Function Introduction ........................................................................................................41
2. Function Definition .............................................................................................................41
3. Function Parameters .........................................................................................................42
3.1. Multiple Parameters ..................................................................................................43
3.2. Default Parameter ......................................................................................................43
4. Return Statement ...............................................................................................................45
5. Lambda Function ................................................................................................................45
5.1. Definition......................................................................................................................45
5.2. Syntax ...........................................................................................................................45
6. Map Function ......................................................................................................................46
7. Assessments ........................................................................................................................47
Quiz (True/False) .....................................................................................................................47
Quiz (Multiple Choice & Short Answer) ..............................................................................47
Coding Task 1: Calculate Fuel Consumption .....................................................................48
Chapter 5: Lists ....................................................................................... Erreur ! Signet non défini.
1. Definition........................................................................................ Erreur ! Signet non défini.
2. Accessing items in a list ............................................................... Erreur ! Signet non défini.
3. Adding items to a list ................................................................... Erreur ! Signet non défini.
4. Adding to a specific location ...................................................... Erreur ! Signet non défini.
5. Removing items from a list ......................................................... Erreur ! Signet non défini.
6. Slicing .............................................................................................. Erreur ! Signet non défini.
7. Assessments .................................................................................. Erreur ! Signet non défini.
Quiz (Multiple Choice) ..................................................................... Erreur ! Signet non défini.

4
ISTLS Asma HADYAOUI

Coding Task 1: Storing Shipment IDs ........................................... Erreur ! Signet non défini.
Coding Task 2: Tracking Cargo Weights ....................................... Erreur ! Signet non défini.
Chapter 6 : Dictionary ........................................................................... Erreur ! Signet non défini.
1. Using a dictionary ......................................................................... Erreur ! Signet non défini.
2. What can be stored in a dictionary? ......................................... Erreur ! Signet non défini.
3. How keys and values in a Dictionary ........................................ Erreur ! Signet non défini.
4. Dictionary Operations: Adding and Removing Items ............ Erreur ! Signet non défini.
5. Assessments .................................................................................. Erreur ! Signet non défini.
Quiz (Multiple Choice) ..................................................................... Erreur ! Signet non défini.
Coding Task 1: Track Delivery Status ............................................ Erreur ! Signet non défini.
Coding Task 2: Warehouse Inventory Management ................. Erreur ! Signet non défini.
Chapter 7: Matrices (Two-Dimensional Arrays)............................ Erreur ! Signet non défini.
1. Defining a Matrix .......................................................................... Erreur ! Signet non défini.
2. Modifying and Traversing a Matrix ........................................... Erreur ! Signet non défini.
3. Traversing Each Element of the Matrix .................................... Erreur ! Signet non défini.
4. Assessments .................................................................................. Erreur ! Signet non défini.
Quiz (Multiple Choice) ..................................................................... Erreur ! Signet non défini.
Coding Task 1: Route Cost Matrix ................................................. Erreur ! Signet non défini.
Coding Task 2: Accessing and Modifying a Matrix ..................... Erreur ! Signet non défini.
Collaborative Project: Transport Fleet Management System........................................50
1. Project Overview.................................................................................................................50
2. Team Structure and Collaboration .................................................................................51
3. Final Deliverables ...............................................................................................................51
4. Grading Criteria ..................................................................................................................51
5. Milestones............................................................................................................................52
Sample Midterm and Final Exams ..........................................................................................53
Proctored exam 2023-2024 ............................................................................................................53
Detailed Proctored Exam Solutions and Explanations ....................................................................55
Final Exam 2022-2023 ....................................................................................................................60
Detailed Final Exam Solutions and Explanations ............................................................................64

5
ISTLS Asma HADYAOUI

References......................................................................................................................................72
Books ..............................................................................................................................................72
Online Documentation and Resources ...........................................................................................72
Research Articles and Academic Resources ...................................................................................73
Useful Python Libraries for Transport and Logistics .......................................................................73
Video Resources and MOOCs .........................................................................................................74

6
ISTLS Asma HADYAOUI

Pre-Test

Part 1: General Programming Knowledge (10


points)
1.1. Multiple Choice Questions (5 points)

Q1: What is the role of a programming language?


a) To control a computer's hardware
b) To interact with the user
c) To write instructions for a computer to execute
d) To display web pages

Q2: Which of the following is a correct representation of a variable in


programming?
a) 1number
b) name_1
c) @value
d) -age

Q3: What does a conditional statement do in a program?


a) Repeats a block of code
b) Chooses between different actions
c) Stores multiple values
d) Stops program execution

Q4: What is the result of 10 + 5 * 2 according to the order of operations?


a) 30
b) 20
c) 15
d) 20

Q5: Which of the following is NOT a common data structure?


a) List
b) Dictionary

7
ISTLS Asma HADYAOUI

c) Circle
d) Matrix

1.2. True/False Questions (5 points)

Q6: A loop is used to execute a block of code only once.


(True / False)

Q7: A function is a reusable block of code that performs a specific task.


(True / False)

Q8: Python is a compiled programming language.


(True / False)

Q9: Variables in Python must be declared with their data types (e.g., int, string).
(True / False)

Q10: A dictionary stores key-value pairs.


(True / False)

Part 2: Python-Specific Concepts (15 points)


2.1. Short Answer Questions (5 points)

Q11: In Python, how would you print "Hello, World!" to the console?
Answer:

Q12: What is a Python list? Write an example of a list that contains three
numbers.
Answer:

Q13: How do you write a comment in Python?


Answer:

Q14: What is the difference between a list and a dictionary in Python?


Answer:

8
ISTLS Asma HADYAOUI

Q15: What does the len() function do in Python?


Answer:

2.2. Coding Exercise (10 points)

Q16: Write a Python program that asks the user for their name and prints a
welcome message.

python

Copier le code

# Your code here

Q17: Write a Python function that takes two numbers as input and returns their
sum.

# Your code here

…………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………………….

…………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………………….

Q18: Write a Python program that prints all the even numbers from 1 to 20
using a loop.

# Your code here

…………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………………….

…………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………………….

…………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………………….

9
ISTLS Asma HADYAOUI

Part 3: Logic and Problem-Solving (10 points)


3.1. Problem-Solving (5 points)

Q19: You are organizing a transport schedule. A driver can take up to 8 hours to
make a delivery. You have 24 hours to schedule the deliveries. How many
drivers do you need if each driver can only work for 8 hours?

Answer:

3.2. Algorithm Design (5 points)

Q20: Design an algorithm (step-by-step process) to find the largest number in a


list of numbers. Write out the steps in plain language.

Answer:

Pre-Test Evaluation
• 30 - 35 Points: Strong foundation in programming and Python; student
may be ready for more advanced topics in the course.

• 20 - 29 Points: Basic understanding; student has a foundation but may


need some review of key concepts.

• 0 - 19 Points: Limited knowledge of programming concepts; student may


require additional support or resources to build a stronger foundation.

10
ISTLS Asma HADYAOUI

Chapter 1: Introduction to Python


Programming
A computer program is a set of instructions that the computer follows
to perform a specific task. Each instruction, or command, tells the
computer to perform an action such as displaying text, performing
calculations, or interacting with the user. The computer processes
these commands one by one in the order they are written.

This simple program instructs the computer to display the message


"Hello, world!" in the console:

print("Hello, world!")

When the program is run, it produces this:

Sample output
Hello, world!

1. Programming Task: Print a Song


Write a Python program that outputs the following lines exactly as
shown, including all punctuation and spacing:

Sample output
Row, row, row your boat,
Gently down the stream.
Merrily, merrily, merrily, merrily,
Life is but a dream.
This exercise will help you practice how to print multi-line strings in
Python.

11
ISTLS Asma HADYAOUI

2. Performing Arithmetic Operations


Python allows you to perform arithmetic directly inside the print()
function. You can add, subtract, multiply, or divide numbers, and the
result will be displayed immediately.

Example1:

print(3 + 5) # Addition
print(4 * 2) # Multiplication
print(8 - 3) # Subtraction
print(16 / 4) # Division

prints out these lines:

Sample output
8
8
5
4.0

You can also combine operations in a single statement. Python follows


the order of operations (PEMDAS: Parentheses, Exponents, Multiplication,
Division, Addition, Subtraction)

Example 2:

print("4 + 3 * 10")

This program prints out:

Sample output
34

12
ISTLS Asma HADYAOUI

3. Commenting
In Python, comments are used to explain the code and are ignored
when the program runs. Comments start with the # symbol and can be
used to make your code easier to understand.

Example:

# Calculate the total number of hours in a year


print(365*24)
# there are 365 days in a year and 24 hours in each day

Programming Task: Calculate Minutes in a Year

Write a Python program that calculates the total number of minutes in


a year by multiplying the number of days in a year by the number of
hours in a day, and then by the number of minutes in an hour.

4. Variables in Python
A variable is a named location used to store data in a program. You can
assign values to variables and then use them throughout your code.
Here's an example:

name = input("Enter your name: ")


print("Welcome, " + name + "!").

5. String Formatting with f-strings


Python offers f-strings (formatted string literals) to make string
formatting easier and more intuitive. An f-string allows you to insert

13
ISTLS Asma HADYAOUI

variable values directly into your string, making it more flexible and
readable.

Example:

age = 25
print(f"I am {age} years old.")

Output:

I am 25 years old.

Programming Task: User Profile Display

magine you are building a CV management app for job seekers in


Tunisia. Your task is to display the basic information of a user along
with their top skills. Use Python’s f-strings to improve the readability of
the output and structure the profile display more clearly.

# User profile details


user_name = "Ahmed Ben Youssef"
user_age = 30
primary_skill = "Web Development"
primary_level = "Advanced"
secondary_skill = "Mobile App Development"
secondary_level = "Intermediate"
salary_expectation_min = 2500
salary_expectation_max = 4000

# Displaying the formatted user profile


print(f"Profile of {user_name}:")
print(f"Age: {user_age}")
print(f"Skills:")

14
ISTLS Asma HADYAOUI

print(f"1. {primary_skill} - {primary_level}")


print(f"2. {secondary_skill} - {secondary_level}")
print(f"Desired Salary: {salary_expectation_min} to {salary_expectation_max}
TND per month")

The program should print out exactly the following:

Sample output
Profile of Ahmed Ben Youssef:
Age: 30
Skills:
1. Web Development - Advanced
2. Mobile App Development - Intermediate
Desired Salary: 2500 to 4000 TND per month

6. Assessments
Quiz (Multiple Choice)

Q1: What does the print() function do in Python?


a) Outputs text to the screen
b) Takes input from the user
c) Saves data to a file
d) Reads a file

Q2: Which of the following is a correct way to declare a variable in Python?


a) x = 10
b) int x = 10
c) let x = 10
d) variable x = 10

Q3: What is the correct output of this code: print(2 + 3 * 4)?


a) 20
b) 14
c) 24
d) 11

15
ISTLS Asma HADYAOUI

Q4: What symbol is used to add a comment in Python?


a) //
b) /* */
c) #
d) <!-- -->

Q5: What is the purpose of using f-strings in Python?


a) To format text
b) To perform mathematical operations
c) To handle file input/output
d) To store data in lists

Quiz (Short Answer)

1. What is a computer program?

2. Write a Python program that displays the following message:

Welcome to the Higher Institute of Transport and Logistics of Sousse

Coding Task 1: Delivery Cost Calculation

Write a Python program that calculates the total delivery cost based on the
distance (in km) and the cost per kilometer. The program should ask the user
for the distance traveled and the cost per kilometer, then display the total cost.

Expected Output:

Enter the distance in km: 120

Enter the cost per kilometer: 5

The total delivery cost is 600 TND.

16
ISTLS Asma HADYAOUI

Chapter 2: Conditional statements


1. Conditional Branching with if
In Python, the if statement allows you to execute code only when a
certain condition is true.

Example 1 : Checking Driving Eligibility

age = int(input("How old are you? "))

if age >= 18:


print("You are eligible to apply for a driving license!")
else:
print("You are too young to apply for a driving license.")

17
ISTLS Asma HADYAOUI

Example Output
How old are you? 20
You are eligible to apply for a driving license!

If the user enters an age below 18, the output would be:

Example output
How old are you? 16 Next customer, please How old are you? 16
You are too young to apply for a driving license.

1.1. Comparison operators

Conditions often involve comparing two values using operators such as


<, >, ==, and != :

Example: Checking Temperature

temperature = float(input("Enter the current temperature: "))

18
ISTLS Asma HADYAOUI

if temperature < 0:
print("It is freezing!")
elif temperature > 35:
print("It is too hot!")
else:
print("The weather is moderate.")

Example Output:

Enter the current temperature: 38

It is too hot!

1.2. Indentation

In Python, consistent indentation is essential to define blocks of code


that belong to conditions or loops.

When you want to end an indented :

19
ISTLS Asma HADYAOUI

1.3. Boolean expressions

Conditions in Python evaluate to either True or False, also known as


Boolean values. These can be used directly in conditional statements.

Example: Evaluating Discounts

items_in_cart = 5
is_member = True

if items_in_cart > 3 and is_member:


print("You qualify for a 10% discount!")
Example output
You qualify for a 10% discount!

1.4. Programming exercise : Calculate Employee Bonus

Write a program that calculates the annual bonus for an employee


based on their performance score.

• If the score is below 70, the bonus is 5%.


• If the score is between 70 and 90, the bonus is 10%.
• If the score is above 90, the bonus is 20%.

Expected Output:

Enter performance score: 85

20
ISTLS Asma HADYAOUI

Your bonus is 10%.

1.5. Programming exercise 2: Weather Outfit Suggestions

Write a Python program that suggests appropriate clothing based on


the weather conditions, including the temperature and the possibility
of rain.

Example Output 1:

What is the temperature for tomorrow? 28


Will it rain (yes/no)? no
Wear light clothing, and don't forget your sunglasses!
Example Output 2:

What is the temperature for tomorrow? 12

Will it rain (yes/no)? yes

Wear a jacket and carry an umbrella.

1.6. Programming exercise 3: Solve a Cubic Equation

Write a program to solve a cubic equation of the form ax³ + bx² + cx + d


= 0. The user should input the values of a, b, c, and d, and the program
will display the real roots using the sympy module:

from sympy import symbols, solve

x = symbols('x')

a = int(input("Enter coefficient a: "))

b = int(input("Enter coefficient b: "))

21
ISTLS Asma HADYAOUI

c = int(input("Enter coefficient c: "))

d = int(input("Enter constant d: "))

equation = a*x**3 + b*x**2 + c*x + d

roots = solve(equation, x)

print(f"The real roots are: {roots}")

This should print out :

Sample output
Enter coefficient a: 1
Enter coefficient b: -6
Enter coefficient c: 11
Enter constant d: -6
The real roots are: [1, 2, 3]

2. if-else Statements
The if-else structure allows you to provide an alternative action when the
if condition is not met.

22
ISTLS Asma HADYAOUI

Example : Checking Number Evenness

number = int(input("Enter a number: "))

if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Example output
Enter a number: 7
The number is odd.

3. Multiple Conditions with elif

23
ISTLS Asma HADYAOUI

When there are more than two possible outcomes, the elif statement
comes in handy.

Example: Blood Pressure Check

systolic = int(input("Enter your systolic blood pressure: "))

if systolic < 90:


print("Your blood pressure is too low.")
elif 90 <= systolic <= 120:

24
ISTLS Asma HADYAOUI

print("Your blood pressure is normal.")


else:
print("Your blood pressure is too high.")
Sample output
Enter your systolic blood pressure: 110
Your blood pressure is normal.

3.1. Programming exercise: Alphabetically First Word

Write a program that takes two city names from the user and prints
which one comes first alphabetically.

Example output
Enter the first city: Tunis
Enter the second city: Sfax
Sfax comes first alphabetically.

4. Combining conditions
You can combine multiple conditions using the and or logical
operators.

The following truth table contains the behaviour of these operators in


different situations:

25
ISTLS Asma HADYAOUI

Example: Checking Admission Eligibility

age = int(input("Enter your age: "))


score = int(input("Enter your exam score: "))

if age >= 18 and score > 80:


print("You are eligible for admission.")
else:
print("You do not meet the eligibility criteria.")

4.1. Simplified range conditions

Python allows you to simplify range checks using combined conditions,


like 5 <= x <= 10.

Example: Checking a Number in a Range

n = int(input("Enter a number: "))

if 10 <= n <= 20:


print(f"{n} is within the range of 10 to 20.")
else:
print(f"{n} is outside the range.")

Sample output
Enter a number: 15

26
ISTLS Asma HADYAOUI

15 is within the range of 10 to 20.

4.2. Programming exercise : Middle Letter

Write a program that asks for three different letters and prints out the
one that would be in the middle if sorted alphabetically.

4.3. Programming exercise: Calculate Sales Tax

Write a program that calculates the sales tax for an item based on its
price and the type of item. Use the following tax rates:

• 5% for food items


• 10% for electronics
• 15% for luxury goods

Example output
Enter the price of the item: 100
Enter the type of item (food/electronics/luxury): electronics
The tax is 10%, so the total price is 110.

5. Assessments
Quiz (True/False)

1. The else clause in an if statement is mandatory.

2. Python uses indentation to determine the blocks of code that belong


together.

Coding Task 1: Vehicle Load Check

Write a Python program that checks if a vehicle is overloaded. If the total load
exceeds 5000 kg, print a warning message. Otherwise, print the current load.

Expected Output:

27
ISTLS Asma HADYAOUI

Enter the vehicle load in kg: 5500

Warning: Vehicle overloaded!

Coding Task 2: Shipping Eligibility

Write a Python program that checks whether a shipment is eligible for free
shipping. The conditions are :

• The shipment weight is less than 30 kg, and

• The shipment destination is within 200 km.

If both conditions are true, print "Free shipping eligible". Otherwise, print the
cost of shipping (5 TND per kilometer).

Expected Output:

Enter the shipment weight in kg: 25

Enter the shipment distance in km: 150

Free shipping eligible

28
ISTLS Asma HADYAOUI

Chapter 3: Loops
Loops allow us to repeat sections of code multiple times, making them
essential for automating tasks, especially in fields like transport and
logistics where repetitive processes, such as tracking shipments,
calculating fuel consumption, or monitoring warehouse inventory, are
common. In this chapter, we will explore various looping structures in
Python.

1. while loop
The while loop repeats a block of code as long as a specified condition
is true. It is particularly useful for processes that require continuous
monitoring or until a specific event occurs.

1.1. Example 1: Fuel Level Monitoring for Trucks

In logistics, you may need to track the fuel level of trucks. This loop
continues to monitor the fuel level, asking the driver to refuel when the
level falls below a certain threshold, and stops when the level is at an
acceptable level or the user types -1 to quit.

while True:
fuel_level = int(input("Enter the truck's fuel level in liters (-1 to quit): "))

if fuel_level == -1:
break

if fuel_level < 20:


print("Warning: Low fuel! Please refuel the truck.")
else:

29
ISTLS Asma HADYAOUI

print(f"Current fuel level: {fuel_level} liters.")

print("Fuel monitoring stopped.")

Sample output
Enter the truck's fuel level in liters (-1 to quit): 15
Warning: Low fuel! Please refuel the truck.
Enter the truck's fuel level in liters (-1 to quit): 50
Current fuel level: 50 liters.
Enter the truck's fuel level in liters (-1 to quit): -1
Fuel monitoring stopped.

1.2. Example 2 : PIN Entry for Cargo Access

In the transport industry, secure access to cargo or warehouse data is


crucial. This loop asks the user to input the correct PIN to access
sensitive cargo information. It will keep asking until the correct PIN is
provided.

while True:
pin = input("Enter the security PIN to access cargo information: ")

if pin == "4321":
break
print("Incorrect PIN. Try again.")

print("Access granted to cargo data.")


Sample output
Enter the security PIN to access cargo information: 1234
Incorrect PIN. Try again.
Enter the security PIN to access cargo information: 4321
Access granted to cargo data.

30
ISTLS Asma HADYAOUI

1.3. Programming exercise: Cargo Check Continuation

Write a program that prints the message "Cargo is being checked" and
asks, "Shall we continue?" until the user inputs "no". The program
should end by printing "Cargo check stopped."

Sample output
Cargo is being checked
Shall we continue? yes
Cargo is being checked
Shall we continue? no
Cargo check stopped.

2. Loops with helper variables


In many logistics applications, limiting the number of attempts for
actions like entering a security code or verifying a shipment is crucial.
The following program gives users only three chances to enter the
correct PIN.

Example : Limited PIN Entry Attempts

attempts = 0
max_attempts = 3
success = False
while attempts < max_attempts:
pin = input("Enter the security PIN: ")
attempts += 1
if pin == "4321":
success = True
break
else:
print("Incorrect PIN.")

31
ISTLS Asma HADYAOUI

if success:
print("Correct PIN entered! Access granted.")
else:
print("Too many attempts. Access blocked.")

Sample output
Enter the security PIN: 1234
Incorrect PIN.
Enter the security PIN: 4321
Correct PIN entered! Access granted.

2.1. Programming exercise: PIN Entry with Attempt Count

Write a program that keeps asking for the correct PIN (4321). The
program should display the number of attempts it took to enter the
correct PIN. If the user gets it right on the first try, print a special
message.

Sample output 1
Enter the PIN: 3245
Wrong PIN.
Enter the PIN: 1234
Wrong PIN.
Enter the PIN: 4321
Correct! It took you 3 attempts.
Sample output 2
Enter the PIN: 4321
Correct! It only took you one attempt!

3. Concatenating strings in Loops

32
ISTLS Asma HADYAOUI

In logistics, you might want to track all shipment IDs or container


numbers entered during an operation. You can use a helper variable to
store and concatenate these values.

Example: Tracking Shipment IDs

This program stores all entered shipment IDs in a string and prints
them at the end.

shipment_ids = ""
attempts = 0

while True:
shipment_id = input("Enter the shipment ID: ")
attempts += 1
shipment_ids += shipment_id + ", "

if attempts == 3:
break

print(f"Shipment IDs logged: {shipment_ids}")

Sample output:

Enter the shipment ID: SHP001


Enter the shipment ID: SHP002
Enter the shipment ID: SHP003
Shipment IDs logged: SHP001, SHP002, SHP003,

4. Loops with conditions


The general structure of the while statement is as follows:

33
ISTLS Asma HADYAOUI

while <condition>:
<block>

Example: Cargo Load Check

This loop continues checking the cargo load and increments the value
until the load reaches the capacity of the truck.

load = int(input("Enter the current load: "))

while load < 5000:


print(f"Current load: {load} kg")
load += 500

print("Truck is fully loaded.")

This could print out:

Sample output
Enter the current load: 3000

34
ISTLS Asma HADYAOUI

Current load: 3000 kg


Current load: 3500 kg
Current load: 4000 kg
Current load: 4500 kg
Truck is fully loaded.

4.1. Initialisation, condition and update

If any one of these three components is missing, the loop will likely not
function correctly.

4.2. Programming exercise: Print Even Numbers

Write a program that prints all the even numbers between 2 and 50.
Use a loop to iterate through the numbers and print each one on a
separate line.

Sample output
2
4
6
...
50

35
ISTLS Asma HADYAOUI

4.3. Programming exercise: Fix the code: Countdown

The program below contains an error. Fix the code to make it print a
countdown starting from a number entered by the user, and ending
with "Now!".

print("Are you ready?")


number = int(input("Enter a number: "))
while number > 0:
print(number)
number -= 1
print("Now!")

Please fix it so that it prints out the following:

Sample output
Are you ready?
Enter a number: 5
5
4
3
2
1
Now!

5. Writing complex conditions


You can combine multiple conditions to control loops. The following
example prints every third number as long as the number is less than
100 and not divisible by 5:

number = int(input("Enter a starting number: "))

36
ISTLS Asma HADYAOUI

while number < 100 and number % 5 != 0:


print(number)
number += 3

Two examples of the program's execution with different inputs:

Sample output
Enter a starting number: 28
28
31
34
Sample output
Enter a starting number: 96
96
+99

5.1. Programming exercise: Number Series

Write a program that asks the user for a number. The program then
prints all integer numbers greater than zero but smaller than the input.

Sample output
Upper limit: 5

6. Assessments
Quiz (Short Answer)

37
ISTLS Asma HADYAOUI

1. Which loop should you use when the number of iterations is unknown?

2. Write a Python while loop that prints numbers from 1 to 10.

Quiz (Multiple Choice)

Q1: What type of loop repeats as long as a given condition is true?


a) for loop
b) while loop
c) repeat loop
d) do loop

Q2: Which of the following is true about a while loop?


a) It runs a fixed number of times.
b) It runs as long as the condition is True.
c) It runs only once.
d) It runs without a condition.

Q3: What is the output of the following code:

for i in range(3):

print(i)

a) 0 1 2 3
b) 1 2 3
c) 0 1 2
d) 3 2 1

Q4: What does the break statement do in a loop?


a) Skips the rest of the loop and starts the next iteration
b) Terminates the loop immediately
c) Continues with the next iteration
d) Stops the program

Q5: How many times will this loop run?

count = 0

while count < 5:

38
ISTLS Asma HADYAOUI

count += 1

print(count)

a) 4 times
b) 5 times
c) 6 times
d) Infinite times

Coding Task 1: Fleet Fuel Monitoring

Write a Python program that keeps asking the user for the fuel level of a truck
(in liters). If the fuel level is less than 20 liters, print a warning. The program
should stop when the user enters -1.

Expected Output:

Enter the truck's fuel level in liters: 18

Warning: Low fuel! Please refuel.

Enter the truck's fuel level in liters: -1

Fuel monitoring stopped.

Coding Task 2: Container Weight Check

Write a Python program that keeps asking the user for container weights until
the total weight exceeds 10,000 kg. Then, display the total weight and the
number of containers loaded.

Expected Output:

Enter the weight of the container: 2500

Enter the weight of the container: 3000

Enter the weight of the container: 5000

Total weight: 10500 kg

39
ISTLS Asma HADYAOUI

Number of containers loaded: 3

40
ISTLS Asma HADYAOUI

Chapter 4: Python Functions

1. Function Introduction
A function is a block of organized, reusable code that performs a specific task.
Functions help in breaking down large programs into smaller, more
manageable pieces. You can pass information to a function using parameters,
and a function can return a result, such as the distance between two locations
or the fuel needed for a trip.

Key Features:

• Functions reduce code duplication.


• Functions allow for better code organization.
• You can call functions multiple times to perform the same task in
different scenarios.

2. Function Definition
A function is defined using the keyword def:

Example

def my_function():

41
ISTLS Asma HADYAOUI

print("Hello from a function")

my_function()

Example: Estimating Delivery Time

In transport and logistics, calculating delivery times is a routine task. Here's a


simple function that prints a message about a delivery.

def delivery_message():

print("The delivery is on its way!")

delivery_message()

Output:

The delivery is on its way!

3. Function Parameters
Parameters allow you to pass data to functions, making them more dynamic.
For instance, you might pass the distance or weight of cargo to a function to
calculate costs or fuel requirements.

Example

def my_function(parameter):

print("I want to learn "+parameter)

my_function("to code!")

42
ISTLS Asma HADYAOUI

my_function("to do AI!")

Example: Calculating Fuel Consumption

This function accepts the distance traveled as a parameter and prints the
estimated fuel consumption.

def calculate_fuel(distance):

fuel_needed = distance * 0.12 # Assume each km requires 0.12 liters of fuel

print(f"Fuel needed for {distance} km is {fuel_needed:.2f} liters.")

calculate_fuel(100)

calculate_fuel(250)

3.1. Multiple Parameters

You can add as many parameters as you want. Just separate them with a
comma.

Example

def my_function(first_parameter, second_parameter):

print("First parameter: "+first_parameter)

print("Second parameter: "+second_parameter)

my_function("Hey", "you!")

3.2. Default Parameter

43
ISTLS Asma HADYAOUI

You can set default parameters for your functions. This is useful when one of
the parameters rarely changes, such as a default fuel price in your region.

Let’s check this out with the following example :

Example

def my_function(country="Tunisia"):

print("I am from "+country)

my_function("Maroc")

my_function("Algeria")

my_function()

Example: Default Fuel Price

def calculate_cost(distance, fuel_price_per_liter=2.1):

fuel_needed = distance * 0.12

total_cost = fuel_needed * fuel_price_per_liter

print(f"The total cost for {distance} km is {total_cost:.2f} TND.")

calculate_cost(100) # Uses default fuel price

calculate_cost(250, 2.3) # Uses provided fuel price

Output:

The total cost for 100 km is 25.20 TND.

44
ISTLS Asma HADYAOUI

The total cost for 250 km is 69.00 TND.

4. Return Statement
To return a value from a function we can use the return statement :

Example

def my_function(x):

return 5*x

print(my_function(0))

print(my_function(1))

print(my_function(2))

5. Lambda Function
5.1. Definition

A lambda function:

• Is a small function.

• Can take any number of arguments, but should have only one
expression.

• Is useful when a function requires another function as its argument.

5.2. Syntax

45
ISTLS Asma HADYAOUI

lambda parameters : expression

Example

sum = lambda a,b,c : a+b+c

print(sum(2,6,3))

One more function:

year = lambda ch : ch[:4]

ch = "20221121"

print(year(ch)) #2022

Example: Quick Weight Calculation

You can use a lambda function to quickly calculate the total weight of cargo in a
shipment.

total_weight = lambda weight_per_box, num_boxes: weight_per_box *


num_boxes

print(total_weight(5, 100)) # 5 kg per box, 100 boxes


Output:

500

6. Map Function
The map() function is a function that applies a specific instruction on each
item of an iterable or more.

The items and the instructions are sent to the map function as parameters:

46
ISTLS Asma HADYAOUI

Example: Convert Distances from Kilometers to Miles

def km_to_miles(km):

return km * 0.621371 # 1 km = 0.621371 miles

distances_km = [100, 200, 300]

distances_miles = list(map(km_to_miles, distances_km))

print(f"Distances in miles: {distances_miles}")

Output:

Distances in miles: [62.1371, 124.2742, 186.4113]

7. Assessments
Quiz (True/False)

1. A function can return multiple values.

2. Parameters passed to a function are optional.

Quiz (Multiple Choice & Short Answer)

47
ISTLS Asma HADYAOUI

Q1: How do you define a function in Python?


a) def function_name():
b) function function_name()
c) func function_name():
d) declare function function_name():

Q2: What is the purpose of a return statement in a function?


a) To stop the function
b) To return a value from the function
c) To pass a value to the function
d) To loop through a function

Q3: Which of the following is a valid function call?


a) my_function
b) my_function[]
c) my_function()
d) my_function{}

Q4: What will the following code output?

def add_numbers(a, b):

return a + b

print(add_numbers(2, 3))

a) 5
b) 2
c) 3
d) Syntax error

Q5: What is a lambda function?


a) A function without a name
b) A loop function
c) A function that calls another function
d) A function that stops execution

Coding Task 1: Calculate Fuel Consumption

48
ISTLS Asma HADYAOUI

Write a function calculate_fuel(distance) that takes the distance (in kilometers)


as input and returns the total fuel needed, assuming the vehicle consumes 0.12
liters of fuel per kilometer.

Expected Output:

Fuel needed for 300 km: 36.0 liters

Coding Task 2: Delivery Cost Estimation with Default Parameter

Write a function calculate_delivery_cost(distance, cost_per_km=3.5) that


calculates and returns the total delivery cost. The cost per kilometer has a
default value of 3.5 TND.

Expected Output:

Total cost for 200 km: 700.0 TND

49
ISTLS Asma HADYAOUI

Collaborative Project: Transport


Fleet Management System
In this collaborative project, students will work in teams to develop a
comprehensive Transport Fleet Management System using Python. The
project will simulate a system for managing a fleet of vehicles, tracking
shipments, calculating delivery costs, and managing warehouse inventory. It
integrates many of the Python concepts learned throughout the course, such as
functions, lists, dictionaries, and matrices. The project will also emphasize
collaboration, enabling students to work together effectively, share tasks, and
combine their knowledge to build a complete system.

1. Project Overview
The Transport Fleet Management System will be divided into several
components, each representing a critical part of fleet and logistics
management. The team will collectively build and integrate the following
features:

1. Vehicle Management – Track vehicle details, fuel levels, and statuses.

2. Shipment Tracking – Monitor the status of shipments, assign vehicles to


shipments, and update delivery statuses.

3. Route Calculation – Calculate and store route distances between


warehouses, ports, and delivery points.

4. Cost Estimation – Estimate fuel and delivery costs based on route


distances and vehicle efficiency.

5. Warehouse Inventory – Manage the inventory at multiple warehouse


locations, including adding and removing stock.

50
ISTLS Asma HADYAOUI

2. Team Structure and Collaboration


Each team should consist of 3-5 students, with roles assigned to each team
member based on their strengths and interests.

3. Final Deliverables
1. Source Code Repository: The full Python code for the Transport Fleet
Management System, organized into modules.

2. Project Report: A collaborative document detailing the system's


architecture, the role of each team member, and how the system solves
logistics-related challenges.

3. Demo Video: A short video (5-10 minutes) demonstrating the system in


action, showing how it tracks shipments, calculates costs, manages
vehicles, and updates inventory.

4. Reflection Document: Each team member will submit an individual


reflection on their contribution, what they learned, and how the
collaborative process worked.

4. Grading Criteria
• Functionality (40%): The system must work as intended, with all features
implemented and functioning properly.
• Collaboration and Teamwork (20%): Each team member should
contribute to the project, and there should be evidence of effective
collaboration.
• Code Quality (20%): The code should be well-organized, documented, and
follow good programming practices.
• Presentation (10%): The demo video and project report should clearly
explain the system’s features and demonstrate its functionality.
• Creativity and Problem-Solving (10%): Bonus points for creative solutions,
additional features, or optimizations that enhance the system.

51
ISTLS Asma HADYAOUI

5. Milestones
Week Milestone Key Deliverables
Week 1 Project Kickoff & Team Formation Team roster, Project outline,
Repository
Week 2 System Architecture & Module Architecture diagram, Module
Specifications specs
Week 3 Initial Module Development Initial implementation, Unit
tests
Week 4 Module Integration & Data Integrated system, Integration
Sharing tests
Week 5 Final Development & Testing Fully functional system, Te*st
reports
Week 6 Final Presentation & Submission Final code, Demo video, Project
report

52
ISTLS Asma HADYAOUI

Sample Midterm and Final Exams


Proctored exam 2023-2024
UNIVERSITY OF SOUSSE
HIGHER INSTITUTE OF TRANSPORT AND LOGISTICS OF SOUSSE
The academic year 2023/2024

Proctored exam
Algorithmics and programming I
Groups: TIT1 Mrs. Asma Hadyaoui
Date: 07-11-2023 Duration:1h
• Documents NOT allowed

Section A: Multiple Choice Questions (2 points)


1. Which of the following is the correct extension of a Python file?
a. .pyth
b. .pt
c. .py
d. .python
2. How do you start writing an if statement in Python?
a. if (condition):
b. if condition then:
c. if condition:
d. if {condition}
3. Which syntax correctly initializes a for loop in Python?
a. for (i=0; i<5; i++):
b. for i in range(5):
c. for i < 5:
d. for i up to 5:
4. Which loop is typically used when the number of iterations is known ahead of time?
a. while loop
b. do-while loop
c. for loop
d. repeat-until loop
Section B: Predict the Program Output (8 points)

53
ISTLS Asma HADYAOUI

For each Python code snippet provided, predict the output that would appear when the
code is executed. Write "Error" if you believe the code would not run successfully due to
a syntax or logical error.

a.

print(10 // 3)

b.

for char in "PYTHON":


if char == "H":
break
print(char)

c.

x = True
y = False
print(x and y)

d.

for i in range(1, 11):


if i % 2 == 0:
print(i)

Section C: Short Answer Questions (2 points each)

1. Create a Python function named calculate_area that takes two arguments, length
and width, and returns the area of a rectangle.
2. Provide a detailed explanation for what the code below is intended to do:

word = "programming"
for letter in word:
if letter in "aeiou":
print(letter, end=" ")

Section D: Exercise (5 points)

54
ISTLS Asma HADYAOUI

Please write a program that asks the user for a positive integer N. The program then prints
out all numbers between -N and N inclusive but leaves out the number 0. Each number
should be printed on a separate line.

An example of expected behaviour:

Sample output
Please type in a positive integer: 4
-4
-3
-2
-1
1
2
3
4

Good Luck ☺

Detailed Proctored Exam Solutions and Explanations


Section A: Multiple Choice Questions (2 points)

1. Which of the following is the correct extension of a Python file?


Answer: c) .py
Explanation: Python files have the extension .py, which is standard for all
Python scripts.

2. How do you start writing an if statement in Python?


Answer: c) if condition:
Explanation: The correct Python syntax for an if statement is if condition:.
The condition is followed by a colon, and the code to be executed is
indented.

3. Which syntax correctly initializes a for loop in Python?


Answer: b) for i in range(5):
Explanation: In Python, the for loop is typically written using the range()
function, which generates a sequence of numbers for iteration.

55
ISTLS Asma HADYAOUI

4. Which loop is typically used when the number of iterations is known


ahead of time?
Answer: c) for loop
Explanation: A for loop is used when the number of iterations is known in
advance, as it iterates over a sequence or a range.

Section B: Predict the Program Output (8 points)

1. What is the output of the following code?

print(10 // 3)

Answer: 3
Explanation: The // operator performs integer division, which divides two
numbers and returns the quotient without the remainder.

2. What is the output of the following code?

for char in "PYTHON":

if char == "H":

break

print(char)

Answer:

Explanation: The loop iterates over each character in the string "PYTHON".
When it encounters "H", the break statement stops the loop, so "P", "Y", and "T"
are printed.

3. What is the output of the following code?

56
ISTLS Asma HADYAOUI

x = True

y = False

print(x and y)

Answer: False
Explanation: The and operator returns True only if both operands are True.
Since x is True and y is False, the result is False.

4. What is the output of the following code?

for i in range(1, 11):

if i % 2 == 0:

print(i)

Answer:

10

Explanation: The code prints even numbers between 1 and 10. The condition i %
2 == 0 checks if the number is divisible by 2, and only even numbers are printed.

Section C: Short Answer Questions (2 points each)

1. Create a Python function named calculate_area that takes two


arguments, length and width, and returns the area of a rectangle.

Answer:

def calculate_area(length, width):

57
ISTLS Asma HADYAOUI

return length * width

Explanation: This function takes two arguments (length and width) and
multiplies them to return the area of the rectangle. The formula for the area of
a rectangle is length * width.

2. Provide a detailed explanation for what the code below is intended to


do:

word = "programming"

for letter in word:

if letter in "aeiou":

print(letter, end=" ")

Explanation:
This code iterates through each letter in the string "programming". For each
letter, it checks if the letter is a vowel ("a", "e", "i", "o", or "u"). If the letter is a
vowel, it is printed without moving to the next line (end=" " keeps all printed
vowels on the same line). The output will be:

oai

Section D: Exercise (5 points)

Write a program that asks the user for a positive integer N. The program
then prints out all numbers between -N and N inclusive but leaves out the
number 0. Each number should be printed on a separate line.

Answer:

# Ask the user for a positive integer

n = int(input("Please type in a positive integer: "))

# Use a for loop to iterate from -N to N, excluding 0

58
ISTLS Asma HADYAOUI

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

if i != 0:

print(i)

Explanation:

1. The program asks the user to input a positive integer N.

2. A for loop is used to generate numbers from -N to N using range(-n, n +


1).

3. The condition if i != 0: ensures that the number 0 is excluded from the


output.

4. Each number is printed on a separate line as required.

Sample Output:

Please type in a positive integer: 4

-4

-3

-2

-1

59
ISTLS Asma HADYAOUI

Final Exam 2022-2023


UNIVERSITY OF SOUSSE
HIGHER INSTITUTE OF TRANSPORT AND LOGISTICS OF SOUSSE
The academic year 2022/2023

Final exam
Programming I
Groups: TIT1 + ST1 + GL1 Mrs. Asma Hadyaoui

Date: 01-05-2023 Duration:1h30

• Documents NOT allowed

Part 1: Questions (8 points: 1+1+2+4)


1. Which Boolean value (True or False) do these Python expressions evaluate?
a. ("A" != "A") or not (2 >= 3)
b. 123 == "123"

2. Which of the following are true of Python dictionaries:


a. All the keys in a dictionary must be of the same type.
b. A dictionary can contain any object type except another dictionary.
c. Dictionaries are accessed by key.
d. Items are accessed by their position in a dictionary.

3. How to define the following dictionary:

4. What would be the output (“Résultat d’exécution”) of the following codes


snippet?

60
ISTLS Asma HADYAOUI

a.
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in a_dict:
print(key)

b.
func = lambda x: return x

print(func(2))

c.
for num in range(1, 5):
print(num)

d.
x=0
while x < 10:
x=x+1
print(x)

Part 2: Exercises (16 points)


Exercise 1: (4 points)
Write a function named chessboard (“échiquier”), which prints out a chessboard
made from ones and zeroes. The function takes an integer argument, which specifies
the length of the side of the board. See the examples below for details:

Example 1:

61
ISTLS Asma HADYAOUI

chessboard(3)
print()
Sample output
101
010
101

Example 2:
chessboard(6)
print()

Sample output
101010
010101
101010
010101
101010
010101

Exercise 2: Matrices (4 points)


We consider the following matrix:

• Write a function that allows the changing of the value of a single element
within the matrix (“changement de la valeur d'un seul élément de la matrice”).
• Write a function that increases the value of each element in the matrix by one
(“ajoute 1 à chaque élément de la matrice”).
• Write the program that defines this matrix and then call these functions.

Exercise 3: Lists (4 points)

62
ISTLS Asma HADYAOUI

Write a program that asks the user to choose between addition and removal. Depending on
the choice, the program adds an item to or removes an item from the end of a list. The item
that is added must always be one greater than the last item in the list. The first item to be
added must be 1 (“Selon le choix effectué,le programme ajoute ou retire un élément à la fin
d'une liste. L'élément qui est ajouté doit toujours être supérieur de 1 au dernier élément de
la liste. Le premier élément à ajouter doit être 1”).

The list is printed out after each operation. Have a look at the example execution below:
Sample output
The list is now []
a(d)d, (r)emove or e(x)it: d
The list is now [1]
a(d)d, (r)emove or e(x)it: d
The list is now [1, 2]
a(d)d, (r)emove or e(x)it: d
The list is now [1, 2, 3]
a(d)d, (r)emove or e(x)it: r
The list is now [1, 2]
a(d)d, (r)emove or e(x)it: d
The list is now [1, 2, 3]
a(d)d, (r)emove or e(x)it: x
Bye!

Good Luck ☺

63
ISTLS Asma HADYAOUI

Detailed Final Exam Solutions and Explanations


Part 1: Questions (8 points: 1+1+2+4)

1. Evaluate the Boolean expressions (1 point)

a. ("A" != "A") or not (2 >= 3)

• Explanation:

o "A" != "A" evaluates to False because "A" is equal to "A".

o 2 >= 3 evaluates to False, so not (2 >= 3) is True.

o False or True evaluates to True.

• Answer: True

b. 123 == "123"

• Explanation:

o 123 is an integer and "123" is a string. In Python, comparing


different types results in False.

• Answer: False

2. Which of the following are true of Python dictionaries? (1 point)

• a. All the keys in a dictionary must be of the same type.


Answer: False
Explanation: Python dictionaries can have keys of mixed types (e.g.,
strings, integers, tuples).

• b. A dictionary can contain any object type except another


dictionary.
Answer: False
Explanation: Dictionaries can contain any type of object, including other
dictionaries (nested dictionaries).

64
ISTLS Asma HADYAOUI

• c. Dictionaries are accessed by key.


Answer: True
Explanation: Dictionaries are accessed using keys, not indexes.

• d. Items are accessed by their position in a dictionary.


Answer: False
Explanation: Dictionary items are not accessed by their position but by
their key.

3. How to define the following dictionary? (2 points)

• Correct definition:

my_dict = {

"color": "blue",

"fruit": "apple",

"pet": "dog"

• Explanation: A dictionary is defined using curly braces {}, where each


key-value pair is separated by a colon : and pairs are separated by
commas.

4. Predict the output of the following code snippets (4 points)

a.

a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

for key in a_dict:

print(key)

• Explanation: The code iterates over the dictionary's keys and prints each
key.

• Answer:

65
ISTLS Asma HADYAOUI

color

fruit

pet

b.

func = lambda x: return x

print(func(2))

• Explanation: This code produces a syntax error because a lambda


function cannot contain a return statement.

• Answer: Error

c.

for num in range(1, 5):

print(num)

• Explanation: The range(1, 5) generates numbers from 1 to 4 (inclusive of


1 but exclusive of 5).

• Answer:

d.

x=0

while x < 10:

66
ISTLS Asma HADYAOUI

x=x+1

print(x)

• Explanation: The while loop increments x until it reaches 10, and then
the loop stops. After the loop, x is printed.

• Answer:

10

Part 2: Exercises (16 points)

Exercise 1: Chessboard Function (4 points)

Task: Write a function named chessboard that prints a chessboard pattern of


ones and zeroes. The function takes an integer argument specifying the length
of the side of the board.

• Solution:

def chessboard(n):

for i in range(n):

row = ""

for j in range(n):

if (i + j) % 2 == 0:

row += "1"

else:

row += "0"

print(row)

# Example calls

67
ISTLS Asma HADYAOUI

chessboard(3)

print()

chessboard(6)

• Explanation:

o The function uses two nested loops. The outer loop iterates
through rows, and the inner loop builds each row by alternating
between 1 and 0 based on the sum of the row and column indices
(i + j) % 2.

o For even sums, it prints 1; for odd sums, it prints 0.

• Sample output for chessboard(3):

101

010

101

• Sample output for chessboard(6):

101010

010101

101010

010101

101010

010101

Exercise 2: Matrix Functions (4 points)

Task: Write functions to modify and increment the elements of a matrix.

Solution:

# Define the matrix

68
ISTLS Asma HADYAOUI

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

# Function to change the value of a single element

def change_value(matrix, row, col, new_value):

matrix[row][col] = new_value

# Function to add 1 to each element in the matrix

def increment_matrix(matrix):

for i in range(len(matrix)):

for j in range(len(matrix[i])):

matrix[i][j] += 1

# Example usage

change_value(matrix, 1, 1, 10) # Changes matrix[1][1] to 10

increment_matrix(matrix) # Adds 1 to all elements

print(matrix)

• Explanation:

o change_value: Modifies a specific element of the matrix by row and


column indices.

69
ISTLS Asma HADYAOUI

o increment_matrix: Iterates over the matrix and increments each


element by 1.

• Sample output:

[[2, 3, 4], [5, 10, 7], [8, 9, 10]]

Exercise 3: List Operations (4 points)

Task: Write a program that allows the user to either add or remove an item
from the end of a list. The item added should always be one greater than the
last item, and the first item added should be 1.

• Solution:

def list_operations():

lst = []

while True:

print(f"The list is now {lst}")

choice = input("a(d)d, (r)emove or e(x)it: ").lower()

if choice == 'd':

if lst:

lst.append(lst[-1] + 1)

else:

lst.append(1)

elif choice == 'r':

if lst:

lst.pop()

elif choice == 'x':

70
ISTLS Asma HADYAOUI

print("Bye!")

break

else:

print("Invalid choice, try again.")

# Example usage

list_operations()

• Explanation:

o The program maintains a list that starts empty. The user can add
items by choosing d, remove items by choosing r, or exit by
choosing x.

o When adding an item, it adds 1 if the list is empty, or the next


number in sequence if items already exist. Removal removes the
last item from the list.

• Sample output:

The list is now []

a(d)d, (r)emove or e(x)it: d

The list is now [1]

a(d)d, (r)emove or e(x)it: d

The list is now [1, 2]

a(d)d, (r)emove or e(x)it: r

The list is now [1]

a(d)d, (r)emove or e(x)it: x

Bye!

71
ISTLS Asma HADYAOUI

References

Books
1. "Python Crash Course" by Eric Matthes (2nd Edition, 2019)
This is a fast-paced, hands-on introduction to programming with Python. It
covers basic concepts and helps students build projects as they learn.

2. "Automate the Boring Stuff with Python" by Al Sweigart (2nd Edition,


2019)
A highly recommended book for beginners that emphasizes practical Python
applications in automating repetitive tasks.

3. "Python for Data Analysis" by Wes McKinney (2nd Edition, 2017)


A guide to data analysis using Python, especially helpful for students
interested in analyzing data from logistics operations.

4. "Fluent Python" by Luciano Ramalho (2015)


A deep dive into Python’s more advanced features, perfect for students
wanting to learn beyond the basics and develop high-quality code.

5. "Python Programming: An Introduction to Computer Science" by


John M. Zelle (3rd Edition, 2017)
A well-rounded introductory textbook focused on computational problem-
solving using Python.

Online Documentation and Resources


1. Python Official Documentation
https://docs.python.org/3/
This is the official Python documentation that provides comprehensive information
about Python’s standard library and its various modules.

72
ISTLS Asma HADYAOUI

2. W3Schools Python Tutorial


https://www.w3schools.com/python/
An excellent online resource that offers interactive Python tutorials covering basic to
intermediate topics.

3. Real Python
https://realpython.com/
This site offers tutorials, articles, and guides on various Python topics, from beginner
concepts to advanced programming techniques.

4. GeeksforGeeks – Python Programming


https://www.geeksforgeeks.org/python-programming-language/
A useful resource for learning about data structures, algorithms, and Python
programming concepts, with a special focus on problem-solving.

5. Learn Python (Codecademy)


https://www.codecademy.com/learn/learn-python-3
A popular online platform that provides an interactive Python course for beginners,
with exercises to practice coding.

Research Articles and Academic Resources


1. "Python: An Introduction to Computer Science" by Guido van Rossum
(1991)
A paper written by Python's creator, introducing the programming language
and its key features.

2. "Python for Logistic Optimization Problems" by Heike Leitschuh (2020)


An insightful paper that focuses on how Python can be used for solving
logistic optimization problems, relevant for students in the transport and
logistics field.

3. "Data Science in Logistics: Using Python for Predictive Analytics" by


A. Wilson (2020)
A detailed resource exploring the applications of Python in logistics,
particularly predictive analysis and transportation optimization.

Useful Python Libraries for Transport and Logistics

73
ISTLS Asma HADYAOUI

1. Pandas
https://pandas.pydata.org/
Pandas is a data manipulation and analysis library that is highly useful for
working with tabular data (e.g., shipments, routes, fuel consumption data).
2. NumPy
https://numpy.org/
NumPy is a library for numerical computing with Python. It is useful for
performing complex mathematical operations in logistics calculations (e.g.,
distances, loads).
3. Matplotlib and Seaborn
https://matplotlib.org/ and https://seaborn.pydata.org/
These are libraries for creating visualizations. They help in plotting charts and
graphs related to logistics data (e.g., fuel efficiency, shipment trends).
4. Scikit-learn
https://scikit-learn.org/stable/
A machine learning library in Python, which can be used to implement
predictive models for transportation optimization and logistic solutions.
5. Geopy
https://geopy.readthedocs.io/
This library is useful for geocoding, distance calculations, and finding
locations based on coordinates, relevant for logistics routing problems.

Video Resources and MOOCs


1. "Python for Everybody" by Dr. Charles Severance (Coursera)
https://www.coursera.org/specializations/python
A comprehensive Python course designed for beginners, available for free on
Coursera.

2. "CS50’s Introduction to Computer Science" (edX)


https://www.edx.org/course/cs50s-introduction-to-computer-science
Harvard’s introductory course on computer science and programming,
featuring Python as one of the programming languages.

3. "Introduction to Python" (Udacity)


https://www.udacity.com/course/introduction-to-python--ud1110
An interactive and free course on Python fundamentals offered by Udacity.

74
ISTLS Asma HADYAOUI

4. "Python for Data Science and Machine Learning Bootcamp" (Udemy)


https://www.udemy.com/course/python-for-data-science-and-machine-
learning-bootcamp/
A course that covers Python for data science applications, including real-
world use cases in logistics and transportation.

75

You might also like