Loops (Need) Exercises
Exercise 1 (Celsius to Fahrenheit) ☻
You are provided with the following list of temperatures in Celsius. Write a quick Python snippet that converts each temperature to Fahrenheit and prints both temperatures as a Celsius, Fahrenheit pair.
Exercise 2 (Multiplication table) ☻
You can put a loop within a loop to do doubly loopy stuff. Here is an example:
for letter in ['A', 'B', 'C']:
for number in [1, 2, 3]:
print(f'{letter}{number}', end='\t')
print('\n')A1 A2 A3
B1 B2 B3
C1 C2 C3
Try this out and explore.
Write a Python snippet that prints a multiplication table (up to 5) for numbers 1 through 5 using nested for loops. The output should be formatted as shown below:
1 : 1 2 3 4 5
2 : 2 4 6 8 10
3 : 3 6 9 12 15
4 : 4 8 12 16 20
5 : 5 10 15 20 25
Exercise 3 (Simulating a Coin Flip Experiment)
Let’s use NumPy to simulate a simple experiment. NumPy has a random module that allows us to generate random numbers. We can generate 10 numbers between 0 and 1 by:
array([0.87820881, 0.51408832, 0.5028915 , 0.59833137, 0.76499243,
0.40666847, 0.58407205, 0.00879205, 0.54712811, 0.95816881])
We can use this to simulate coin flips of a fair coin by considering values less than 0.5 as tails and values greater than 0.5 as heads. For example, in the above ‘experiment’ we have 8(!) heads.
Using a for loop, run this experiment 10 times and, for each iteration, print out the number of heads.
Your results should look something like:
Experiment 1: No. of Heads = 4
Experiment 2: No. of Heads = 2
Experiment 3: No. of Heads = 8
Experiment 4: No. of Heads = 5
Experiment 5: No. of Heads = 8
Experiment 6: No. of Heads = 5
Experiment 7: No. of Heads = 4
Experiment 8: No. of Heads = 6
Experiment 9: No. of Heads = 2
Experiment 10: No. of Heads = 4
Note that your numbers will not be the same as mine, because the numbers are meant to be random!