Introduction to Programming with Python - Problem sheet

Solve the different problems by writing Python programs.

Module 02/03: Python basics and functions #

Problem 1: Variables, arithmetic and comparison operators

  1. Write a Python program that uses two variables 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:

  1. Modify the program so that it asks the user to enter number1 and number2 using the input() function. (Hint: Remember to convert the input string to a number with the casting function int())
  2. Introduce a third variable LIMIT, a constant, and use it in your comparison instead of hardcoding the number 1000.
  3. Add a check: if either number is equal to 0, print “Zero multiplication detected” instead of computing the result.
  4. Check whether each number is even or odd using the modulus operator (%) and print the result (e.g., “20 is Even”, “31 is Odd”).
  5. Bonus: Wrap your program in a while loop to continuously prompt the user for new pairs of numbers. The loop should stop when the user enters 0 for 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 program

Problem 2: Using loops and Loop Control

  1. Write a for loop that displays the following output in the console:
1
2
3
4
5
6
7
8
9
10
  1. Write a for loop that displays the following output in the console:
0
2
4
6
8
12
14

Note: Notice that 10 is skipped in the output sequence!

  1. Write a for loop that displays the following output in the console:
1
2
4
8
16
32
64
128
256
  1. Write a for loop that displays the following output in the console:
-1
1
-1
1
-1
1
-1
1
  1. Write a for loop that displays the following outputs in the console:
"Yes!"
"No!"
"Yes!"
"No!"
"Yes!"
"No!"

Then, modify this loop to display the following output:

"Yes!"
"No!"
"Yess!"
"Noo!"
"Yesss!"
"Noooo!"
  1. Rewrite all the previous loops using a while loop this time.

Problem 3: Preparing an invoice

We want to write a program that calculates and prints the details of an invoice.

  1. Declare a variable set to the VAT rate percentage (20%). Choose the appropriate name and formatting.
  2. Declare a variable that will store the subtotal amount in euros (before tax). Choose a relevant name in snake_case.
  3. Declare a variable that will store True if VAT is applicable, or False if not.
  4. Write a procedure that calculates the total amount including tax based on whether VAT applies or not for one invoice. Sample inputs:
  1. Display the results in the console using the following format:
VAT=20%

Invoice {} :
Subtotal   : {} EUROS
Tax Amount : {} EUROS
Total (incl. taxes): {} EUROS

{ } are placeholders: fill with appropriate variables and values.

  1. Use the 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 EUROS

Problem 4: Invoicing with Discount

Write 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.00

Problem 5: Infinite loop and Loop Control

  1. Write a Python program that runs an infinite loop using while and print “infinite loop” at each iteration. Terminate its execution manually using Ctrl+C (interrupt).
  2. Modify the program so that it stops the loop after the 7th iteration using the 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)

Problem 6: The Parrot program

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 program

Problem 7: Drawings

  1. Write a Python program named triangle.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.
  1. Building on the logic developed in the previous program, write a Python program named 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.
  1. Write a program named rectangle.py that :
    1. Prompts the user to enter the dimensions (width and height) of the rectangle
    2. Prints the rectangle using asterisks (*) to the standard output

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

**********
**********
**********
  1. Bonus: Building on the logic developed in the 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

   *
  ***
 *****
*******
 *****
  ***
   *

Problem 8: Fizzbuzz

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 NN, 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 Buzz

Problem 9: Guess my number game

Write 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.

Try 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.

Problem 10 : Data manipulation with functions

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:

  1. Returns the sum of the numbers contained in the numbers list;
  2. Returns the average of the numbers contained in the numbers list;
  3. Returns the maximum and minimum values of the numbers contained in the numbers list;
  4. Returns the concatenation of the letters contained in the letters list;
  5. Prints for each letter, whether it is a vowel or a consonant;
  6. Returns the list of numbers with its elements sorted from smallest to largest;
  7. Returns the list of letters with its elements sorted in alphabetical order;
  8. Bonus: Returns the median value of the numbers contained in the numbers list.

Problem 11: Rolling dices and experiments

  1. Write a function d6 that simulates a single roll of a six-sided die.
  2. Using this function, simulate rolling a six-sided die 50 times (or rolling 50 dices simultaneously!). Print the number of times a 6 was rolled, along with the empirical probability pp of rolling a 6. (Recall that the probability of an event is defined as the number of successful outcomes divided by the total number of trials.)
  3. Assuming the die is fair, what theoretical value ptheoreticalp_{\text{theoretical}} should you expect?
  4. Simulate a series of nn die rolls, where nn ranges from 10 to 100,000, multiplying nn by 10 at each step. For each value of nn, display the calculated probability pp of rolling a 6.

Expected output:

n=10   p=..
n=100  p=..
n=1000 p=..
# etc.
  1. Observe the evolution of the difference as n increases. Does the empirical probability stabilize around ptheoreticalp_{\text{theoretical}}? Which fundamental theorem of probability theory does this experiment illustrate?

Problem 12 : Band name generator

Write a program that allows the user to generate random band names. 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 the program with the following functions:

  1. find_adjectives() and find_nouns(): functions that retrieve the list of adjectives and nouns from the database.
  2. A function that generates the band names. It must takes as input the number of band names to generate and both lists of adjectives and nouns. Find an appropriate name for the function and parameters. It must return a list of generated band names
  3. A function that displays the band names generated by the previous function. Find an appropriate signature or interface.

Additional exercises and problems to solve (practice!) #