Exercises
Complete the following exercises using the while loop.
4.1 — Write a program that reads a number from user input, computes the average between 0 and that number rounded to two decimal places, and prints the results to the screen.
4.2 — Write a program that asks the user to guess a number between 1 and 10 and tells the user if their guess is correct or not.
With each run of the program, the secret number to guess is chosen randomly between 1 and 10 and stored in a variable.
The user should be allowed up to 5 guesses before the program terminates. If the user correctly guesses the secret number, the program prints "Correct!" and exits. If the guess if less than the secret number, the program prints "Too low" and lets the user guess again. If the guess is greater than the secret number, the program prints "Too high" and lets the user guess again.
After 5 incorrect guesses, the program print "Incorrect", reveal the secret number,
and exists. Implement this using the loop's else clause.
4.3 — Write a program that prints the multiplication table for a number
the user enters (7 x 1 = 7 … 7 x 10 = 70). Use string formatting to
produce a clean and properly aligned output.
4.4 — Write a program that reads numbers until the user enters 0,
then print how many they entered (excluding the 0) and their sum.
4.5 — Write a program that uses a while loop to count the digits
in a string typed by the user.
4.6 — Write a program that prints a right triangle of stars of a height the user enters.
For example, if the user enteres 3, the program would output:
*
**
***
4.7 — Write a program fizzbuzz.py. For numbers 1 to 30, print Fizz if divisible by 3, Buzz
if by 5, FizzBuzz if by both, otherwise the number.
Hints
- 4.1 — The average is the sum divided by total count
- 4.2 —
random.randint(1, 10)gives you a number between 1 and 10, all inclusive. - 4.5 —
.isdigit()returns true if a string contains only digits. You can use it to check each individual character in the string.my_str[i]returns the character at positioni, andlen(my_str)gives you the length of the string. The last position in the string islen(my_str) - 1 - 4.6 — use the
endargument ofprint()to control when a new line is printed. - 4.7 — The order of checks is important here. For example, it is important to check if a number
is divisible by both
3and5before checking if it is divisible by either.