Solve the different problems by writing Python programs.
number1 and number2 to store numbers: if the
product of the two numbers is less than or equal to
1000, print their product; otherwise print their
sum.Sample inputs and outputs:
number1 = 20, number2 = 30, output
is 600number1 = 40, number2 = 30, output
is 70number1 and number2 using the
input() function. (Hint: Remember to convert the
input string to a number with the casting function
int())LIMIT, a
constant, and use it in your comparison instead of hardcoding
the number 1000.%) and print the
result (e.g., “20 is Even”, “31 is Odd”).number1.Output sample:
Enter number1: 10
Enter number2: 3
30 # 3*10 < LIMIT, we print the product
10 is Even
3 is Odd
Enter number1: 500
Enter number2: 10
510 # 500*10 > LIMIT, we print the sum
500 is Even
10 is Even
Enter number1: 0 # end the program1
2
3
4
5
6
7
8
9
100
2
4
6
8
12
14Note: Notice that 10 is skipped in the output sequence!
1
2
4
8
16
32
64
128
256-1
1
-1
1
-1
1
-1
1"Yes!"
"No!"
"Yes!"
"No!"
"Yes!"
"No!"Then, modify this loop to display the following output:
"Yes!"
"No!"
"Yess!"
"Noo!"
"Yesss!"
"Noooo!"We want to write a program that calculates and prints the details of an invoice.
True if VAT is applicable, or False if
not.VAT=20%
Invoice {} :
Subtotal : {} EUROS
Tax Amount : {} EUROS
Total (incl. taxes): {} EUROS
{ }are placeholders: fill with appropriate variables and values.
input() function to ask the user for invoice
details (invoice number, subtotal and VAT applicable). Then, print the
invoice details. Keep asking the user for next invoice details. To quit
the program, the user must leave the invoice number blank.To quit the program, leave invoice number blank (press Enter)
Enter invoice number: 71
Enter invoice subtotal: 1200
VAT applies: False
Invoice details:
VAT=20%
Invoice 71 :
Subtotal : 1200.00 EUROS
Tax Amount : 00.00 EUROS
Total (incl. taxes): 1200.00 EUROSWrite a Python program named
discount.py that calculates the final payable amount for a
purchase based on a tiered discount system.
The program must prompt the user to enter a net price (excluding tax) and compute the corresponding total price including tax (using a constant VAT rate of 20%).
It then applies a discount rate based on the calculated total price including tax:
Finally, the program must display the details using the exact format shown below.
Enter net price (excl. VAT): 2500
VAT-inclusive price 3000.00
discount 90.00
net to pay 2910.00while and print “infinite loop” at each
iteration. Terminate its execution manually using Ctrl+C
(interrupt).break
statement.Output sample:
Infinite loop (0)
Infinite loop (1)
Infinite loop (2)
Infinite loop (3)
Infinite loop (4)
Infinite loop (5)
Infinite loop (6)Write a Python program parrot.py that
continuously echoes the user’s input. The program should run
indefinitely until the user types “exit” to quit.
Sample output:
python parrot.py #run the program
hello #input
hello #output
Stop repeating what I say!
Stop repeating what I say!
exit #end the programtriangle.py that prompts the user to enter the size of a
triangle to draw (the number of lines), up to a maximum of 20
lines:*).Sample inputs and outputs:
Valid case:
Enter the triangle size: 4
*
**
***
****
*****Invalid case:
Enter the triangle size: 25
Error: The maximum allowed size is 20 lines.
half_diamond.py that prompts the user to enter the size of
the upper half of a half diamond, up to a maximum of 10 lines, and print
it.Sample inputs and outputs:
Valid case:
Enter the maximum width: 4
-
**
---
****
---
**
-Note the alternation of hyphens (
-) and asterisks (*) to draw each line
Invalid case:
Enter the maximum width: 25
Error: The size must be between 1 and 20 lines.rectangle.py
that :
Modify the rectangle.py program to
:
Sample output:
Enter the dimensions of the rectangle: 3 10
The area of the rectangle is equal to 30 units
**********
**********
**********half_diamond.py program, write a Python
program named diamond.py that prompts the user to
enter the size of the upper half of a diamond, up to a maximum of 20
lines, and print it.Enter the upper size of the diamond: 4
*
***
*****
*******
*****
***
*FizzBuzz (before being widely used by recruiters for technical interviews) is a counting game designed to help children learn division. The rules are simple: players count up to a predetermined positive integer , applying the following rules:
Write a program that outputs the sequence for the
game, where N represents the upper limit provided by the
user.
Sample output:
Welcome to FizzBuzz. How high do you want to play? 15
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
10
11
Fizz
13
14
Fizz BuzzWrite the “Guess My Number” program in Python, a classic procedural program!
The game is simple: the computer generates a random number (integer) between 1 (included) and 100 (excluded) and the player has to guess it in minimum trials.
random module to select
a secret integer between 1 (included) and 100 (excluded).input() functionTry to find the process, the different steps before coding! Use comments to help you design the process.
Hint: To help you, this a pseudo-code of the game:
1. Generate a random `secret` number
2. *Game loop*, repeat until the guess is correct:
1. Ask user for a `guess`
2. Print a message with a hint:
*"It's greater than {guess} !"* if guess < secret
*"It's lower than {guess} !"* otherwise
3. Increment the number of attempts
3. Print a congratulations message with the total number of attempts:
"Congratulations, the secret number was {secret}. It took you {attempts} attempts to guess this number."
4. End the program.Here are two data lists: one contains a series of numbers, the other a series of letters:
numbers = [1, 5, 32, 27, 12, -5, 100, -1.5, 230];
letters = ['a', 'z', 'b', 'u', 'r', 'g'];For each expressed requirement, write a function that:
Use list and string methods
d6 that simulates a
single roll of a six-sided die.Expected output:
n=10 p=..
n=100 p=..
n=1000 p=..
n=10000 p=..
# etc.Write a program that allows the user to generate
random band names, using the random package. The system
displays the names as a list. A band name follows this template:
The {adjective} {noun} (e.g., The Last Biscuits,
The Midnight Llamas). The program contains two list of 10
adjectives and 10 nouns (singular or plural).
Write a program with the following functions:
find_adjectives() and find_nouns():
functions that retrieve the list of adjectives and
nouns from the “database”.Write a small program that ask the user for its height (in cm) and weight (in kg) and computes its Body Mass Index (BMI):
where is the weight in kilograms and is the height in meters.
Print the result with a small report:
See all categories, you can add them all!
You are a Finance and Business Analyst. At the end of each quarter, the HR and Sales Management teams calculate performance commissions and bonuses for the sales force.
Currently, this calculation is done manually in Excel by copying and pasting formulas for every single salesperson. This process is slow, prone to human error, and risky when sales policy rules change.
Your task is to write a reusable Python program that automates this process according to the company’s business rules (see below).
sales_comissions.pycalculate_total_payout(sales_amount, csat_score) that
returns the final total payout (commission + tier bonus + CSAT
adjustment).Represent sales force as a list of dictionaries. Each salesperson is represented by a revenue and a CSAT score.
sales.py. Import this module into your
program. What is the benefice of doing this?You manage a local cinema. You have a record of ticket sales over 5 days (Monday through Friday) for 3 different ticket categories: Adult, Child, and Senior. Your data is stored in a 2D NumPy array called sales, where:
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']['Adult', 'Child', 'Senior']Here is the starting code:
import numpy as np
# Rows: Days (Mon to Fri)
# Columns: Categories (Adult, Child, Senior)
sales = np.array([
[120, 45, 30], # Monday
[95, 30, 25], # Tuesday
[110, 50, 40], # Wednesday
[150, 60, 35], # Thursday
[220, 90, 75] # Friday
])axis=1). Which day had the
highest total attendance?np.round function, print the
percentage rounded to one decimal place.days = ["Mon", "Tue", "Wed", "Thu", "Fri"].total_per_day. Count the
days on which we exceeded our target of 200 tickets. (Hint: use a
boolean mask.)targets = np.array([180, 150, 200, 220, 350]) (Monday to
Friday). Print the number of days on which the target
was exceeded. (Hint: compare total_per_day and
targets element by element, then use a boolean mask.)total_revenue_bar.png by using the savefig
function.The Birthday problem is a well-known and interesting problem. It asks for the probability that, in a set of randomly chosen people, at least two will share the same birthday. As we will see, the result is quite counterintuitive, showing that our brains are bad at estimating probabilities!
The objective is to compute and plot the probability that at least two people in a group of people share the same birthday.
Hypotheses: we assume 365 days in a year, an equal birthday probability for each day. Of course, (the group must not be empty!)
It is easier to calculate the complementary probability that no two people share a birthday:
By definition
Thus, for a group of size , we get the following expression:
Knowing , we can compute for each value of .
birthday_problem.pyplot() method. Add
x-axis and y-axis labelsRandom walk is a simple process and yet really surprising and fundamental.
In a 1D random walk, a particle (or someone, or something!) starts at some position, let say . At each step , it moves one step forward (+1) or one step backward (-1) with equal probability ().
The moving thing plays Heads or Tails? at each step! Sometimes, the random walk is called the “drunkard’s walk”!
random_walk.py.N_STEPS = 1000. It
stores the size of the walk (the number of steps to take).N_STEPS random steps of
or
using np.random.choice().
Take the time to read the documentation of this function to understand
how to use it correctly. Store the result in a variable
called steps.np.cumsum()(cumulative
sum). Store the resulting array in a variable
called positions.positions
versus step number."Steps""Distance""Single 1D random walk"Sample output:
squared_distances.squared_distances.To understand the average behavior of random walks, we have to simulate a lot of them. This is where things become really interesting!
random_walks.py. This way, you can still use and read the
first program you wrote.N_WALKS = 500
and N_STEPS = 1000. N_WALKS is the number of
random walks simulated (or experiments), and
N_STEPS is the number of steps in each walk.(N_WALKS, N_STEPS) called
steps, containing random steps of
or
.
Each row stores one random walk.axis=1) using np.cumsum(), and
store the result in a variable called
positions.last_positions.last_positions, compute the squared
distances
and store them in a variable called
squared_distances.plt.subplots(1, 2):
last_positions
for each value of
(set transparencyalpha = 0.4)What do you notice?
Why random walks? A random walk is a simple model of how atoms and molecules move in a gas or a liquid. A particle undergoes countless collisions with its neighbors, each one changing its direction unpredictably. Its trajectory therefore looks like a sequence of random steps, a motion known as Brownian motion. We cannot predict the path of a single particle, but the statistics of many paths are remarkably regular: the mean squared displacement follows a simple law with time. This is the signature of diffusion, which Einstein analyzed in 1905, making a quantitative prediction that could be tested experimentally. Later, Jean Perrin used Einstein’s result to experimentally prove the existence of atoms, a work for which he received the Nobel Prize in Physics in 1926! In this exercise, each walker represents one particle, and each step represents a time interval between collisions (in a simplified 1D model).
We have access to real-world dataset containing historical population statistics.
API_SP.POP.TOTL_DS2_en_csv_v2_441303.csv to
world_pop.csvYou can see that:
world_pop.csv using Python’s built-in csv module.matplotlib.pyplot to compare the population evolution of
France and South Korea on the same plot from 1960 to 2025.Create a single figure window containing two
subplots stacked vertically (top and bottom) using
plt.subplots():
where is the population in the current year and is the population in the previous year.
Define a constant variable at the top of your script containing a list of two country codes to analyze, for example:
COUNTRIES_TO_ANALYZE = ["FRA", "KOR"] # you should be able to change both countries here easilyYour program should be able to reproduce above analysis when both countries are changed without any changes.
np.diff() or slicing techniques
(population[1:]) for efficient growth rate
calculations.np.min(), np.max(), and
np.where() to locate the extreme values easily.The World Bank publishes the total population of every country since 1960. In this problem, you will compare the population and the year-over-year growth rate of two countries. We have access to real-world dataset containing historical population statistics.
API_SP.POP.TOTL_DS2_en_csv_v2_441303.csv to
world_pop.csv1960 to 2025).world_pop.csv into a
DataFrame, using the country code as the index
(row-label)Hint: Use
read_csv()parametersskiprowsto skip the metadata lines andindex_colto useCountry Codeas the index. Check the result withdf.head().
FRA) and South Korea (KOR)
from 1960 to 2025 as NumPy arrays of floats.Hint:
df.loc[row_label, first_column:last_column]selects one row and a range of columns, both ends included. The column names are strings ("1960", not1960). Use thepandasmethod.to_numpy(dtype=float)to get a NumPy array of floats.
for loop). The year-over-year
growth rate (in %) is defined as follow:where is the population in the current year and is the population in the previous year.
You need an Numpy array of years for the x axis. For example,
np.arange(1960, 2026). How many growth rates do you get for 66 years of data?
NumPy operations (
-,/,*) are applied element by element on arrays of the same size. Can you combinep[1:]andp[:-1]to apply the growth rate formula?
Each subplot must have a title, axis labels, a legend and a grid.
Example output with France and Morocco:
Expected output format (values are placeholders):
Minimum growth rate: X.XX% (Country, Year)
Maximum growth rate: X.XX% (Country, Year)
np.min(arr)returns the smallest value of an array,np.argmin(arr)returns the position of this smallest value (np.argmaxfor the largest). Use this position to find the corresponding year in your array of years
plt.savefig("population_growth.png") (before
plt.show())countries = {"FRA": "France", "KOR": "South Korea", "DEU": "Germany"}Estimated duration: 35min
You are writing a small program for a local weather station.
Create a file problem1.py.
input(), store it in a variable (as a float),
then print it, for example: You entered: 4.5 °C. (1
pt)Note: you may assume that the user always enters either a valid number or
stop. Invalid inputs will not be tested, so you do not need to handle them.
Write a function
describe_temperature(temp) that returns a
description of the temperature: (2 pts)
"Freezing" if the temperature is below 0"Cold" if it is at least 0 and below 15"Comfortable" if it is at least 15 and at most 25"Hot" if it is above 25Test it by calling it with the temperature entered in question 1, and print the result.
Modify your program so that it keeps asking
for a temperature until the user types "stop" using a
while loop. Each temperature entered must be categorized by calling your
function describe_temperature. (Hint: check for
"stop" before converting the input to a
float.) (2 pts)
Hint (the blanks ____ are to be completed; the same name
is used in the two places where a variable is expected):
while ____:
answer = ____
if answer == "stop":
____
# convert, categorize, print...Expected behavior:
Enter a temperature (or 'stop'): 4.5
You entered: 4.5 °C ==> Cold
Enter a temperature (or 'stop'): -2.1
Enter a temperature (or 'stop'): stop
At the beginning of your program, create a
dictionary counts whose keys are the four descriptions
("Freezing", "Cold",
"Comfortable", "Hot") and whose values are all
initialized to 0. Inside your loop,
increment the value corresponding to each temperature
entered. (1.5 pts)
At the end of the program, print a summary
containing the total number of temperatures entered, then the content of
the dictionary counts using a for loop. (1.5
pts)
Expected output:
Enter a temperature (or 'stop'): 4.5
You entered: 4.5 °C ==> Cold
Enter a temperature (or 'stop'): -2.1
You entered: -2.1 °C ==> Freezing
Enter a temperature (or 'stop'): 26.5
You entered: 26.5 °C ==> Hot
Enter a temperature (or 'stop'): -0.5
You entered: -0.5 °C ==> Freezing
Enter a temperature (or 'stop'): stop
=== SUMMARY ===
Total Days: 4
Freezing: 2
Cold: 1
Comfortable: 0
Hot: 1
Expected output:
=== SUMMARY ===
Total Days: 4
Total Freezing Days: 2
Highest Temperature: 26.5 °C
Lowest Temperature: -2.1 °C
Estimated duration: 35min
You are analyzing the number of steps walked by a person during 14 consecutive days. The daily goal is 10,000 steps.
Create a file problem1.py starting with
the following code:
#Copy/Paste this code
steps = [6500, 8200, 12000, 4300, 9800, 15000, 3000,
7000, 11000, 8800, 5200, 13500, 9500, 7800]Convert the list into a NumPy array.
Print the mean and the median of the daily steps. What
is the meaning of the median? (answer in the
README) (1.5 pts)
One step is about 0.75 m. Write a function
steps_to_km(steps_array) that takes a NumPy array of steps
and returns an array of distances in
kilometers. Use it to print the total
distance over the 14 days. (1.5 pts)
Create a new array containing, for each day, the gap to the goal of 10,000 steps (a negative value means the goal was not reached). Print this array and the total gap over the 14 days converted in kilometers (1.5 pts)
Using a for loop over the list
steps, count the days on which the goal of
10,000 steps was reached and compute the percentage of
days on which the goal was reached. Print both
values. (1.5 pts)
A friend also recorded their steps over the same 14 days:
#Copy/Paste this code
steps_friend = [5000, 6200, 7500, 8000, 6800, 9000, 4000,
7200, 8500, 9200, 6000, 10500, 8800, 13000]Using Matplotlib, plot both progressions on the same
figure as line plots (daily steps on the y-axis, day number on
the x-axis). Add a legend to tell the two lines apart
(“Me”, “Friend”), label your axes, add a title, and save the figure to
steps_line.png using plt.savefig(). (2
pts)
Before creating a new figure, close the current one
with the instruction plt.close().
Using plt.subplot, create another
figure with two side-by-side charts (subplots): (2 pts)
Add a title and axis labels to each subplot and save
the figure to steps_subplots.png.
Expected output:
Q1: Mean steps: ?
Q1: Median steps: ?
Q2: Total distance: ? km
Q3: Gap to goal: ?
Q3: Total gap: ? km
Q4: Days with goal reached: ?
Q4: Percentage of days: ? %
plt.axhline(). (0.5 pts)Replace all the
?by the correct value for each question!