184.108.40.206 write program code using a While loop
Python. WHILE Loop
Why do we need loops?
We have already learned how to check a condition in a program. But what if certain actions are repeated several times? Of course, you can write program code for each of these actions. But if these actions are repeated dozens, hundreds, thousands, millions of times, then our program will be very long.
To repeat actions in the program several times, we use the loops.
We will first explore the use of the while loop. The while statement ("bye") checks the condition and performs some actions (the body of the loop ) while the loop condition is true.
A preconditioned loop has the following structure:
To make it easier to understand the program, the entire body of the loop and its bounding parentheses are shifted to the right.
There are a few more important concepts to know:
Features of the while loop:
Task 1 . Write a program that asks for a password until "qwerty" is entered.
It is often, impossible to say in advance how many times an operation needs to be performed, but it is possible to determine the condition under which it should end.
In this program, the user can enter the password incorrectly; then, the program will report an error and ask for it again until the correct password is entered.
To solve this problem, we must use a loop condition to validate the password after each input. For this, the password will be entered at the beginning of the program and inside the loop.
Consider another use of the while loop.
Task 2. Calculate the sum of the sequence 1 + 3 + 5 + ... + n
You can use a loop to calculate the amount. In this sequence, you can notice that each next term is increased by 2. Let us denote the term by the variable i and will change it in the loop. The initial value of the variable i is 1, the final value is n.
To calculate the amount, we will use the formulas:
|Просмотров: 59 | ||
|Всего комментариев: 0|