Python Exercise - Loops 2
Introduction
This unit covers how to work with user input and loops in Python. You will practice collecting input from the user, performing operations on lists, and implementing password checks with limited attempts.
Task 1: Enter Numbers, Find Maximum and Minimum, and Sort the List
Description:
Write a program that asks the user to enter 5 numbers, stores them in a list, finds the minimum and maximum numbers, and outputs the sorted list.
Explanation:
- Initialize an empty list:
number_list
is initialized as an empty list to store the entered numbers. - Loop: The
while
loop runs as long as theattempt
is less than or equal to 5. - Enter numbers: Inside the loop, the user is asked to input a number, which is then added to the
number_list
usingappend()
. - Find minimum and maximum: After all numbers are entered, the minimum is found using
min(number_list)
and the maximum usingmax(number_list)
. - Sort the list: The list
number_list
is sorted using thesort()
method. - Output: The stored numbers, the minimum, and the maximum are displayed.
Task 2: Password Input with Limited Attempts
Description:
Write a program that implements a password prompt. The program asks the user for a password and allows them to guess up to five times. If the correct password is entered, the program displays a success message. After five incorrect attempts, the program displays an error message.
Explanation:
- Correct password: The correct password is defined.
- Initialize variables: The number of attempts is set to 0, and the maximum number of attempts is set to 5.
- Loop: The
while
loop runs as long as the number of attempts is less than the maximum number of attempts. - Password input: Inside the
while
loop, the user is asked to input the password. - Password verification: The entered password is checked.
- If the password is correct, a success message is displayed and the loop is terminated using
break
. - If the password is incorrect and the number of attempts has not been exhausted, an error message is displayed.
- If the number of attempts is exhausted, an error message is displayed stating that too many incorrect attempts have been made.
- If the password is correct, a success message is displayed and the loop is terminated using