Convert the following program code to while loop. 2
for i in range(2,50,2)
print i
Answers
Answer:
Toggle navigation
1. Input, print and numbers
2. Integer and float numbers
3. Conditions: if, then, else
4. For loop with range
5. Strings
6. While loop
List of squares
Least divisor
The power of two
Morning jog
The length of the sequence
The sum of the sequence
The average of the sequence
The maximum of the sequence
The index of the maximum of a sequence
The number of even elements of the sequence
The number of elements that are greater than the previous one
The second maximum
The number of elements equal to the maximum
Fibonacci numbers
The index of a Fibonacci number
The maximum number of consecutive equal elements
7. Lists
8. Functions and recursion
9. Two-dimensional lists (arrays)
10. Sets
11. Dictionaries
12. JavaScript
13. HTML5 and CSS
14. Responsive Design with Bootstrap
15. jQuery
Lesson 6
While loop
Theory
Steps
Problems
1. While loop
while loop repeats the sequence of actions many times until some condition evaluates to False. The condition is given before the loop body and is checked before each execution of the loop body. Typically, the while loop is used when it is impossible to determine the exact number of loop iterations in advance.
The syntax of the while loop in the simplest case looks like this:
while some condition:
a block of statements
Python firstly checks the condition. If it is False, then the loop is terminated and control is passed to the next statement after the while loop body. If the condition is True, then the loop body is executed, and then the condition is checked again. This continues while the condition is True. Once the condition becomes False, the loop terminates and control is passed to the next statement after the loop.
For example, the following program fragment prints the squares of all integers from 1 to 10. Here one can replace the "while" loop by the for ... in range(...) loop:
step by step
In this example, the variable i inside the loop iterates from 1 to 10. Such a variable whose value changes with each new loop iteration is called a counter. Note that after executing this fragment the value of the variable i is defined and is equal to 11, because when i == 11 the condition i <= 10 is False for the first time.
Here is another example use of the while loop to determine the number of digits of an integer n:
step by step
On each iteration we cut the last digit of the number using integer division by 10 (n //= 10). In the variable length we count how many times we did that.
In Python there is another, easier way to solve this problem: length = len(str(i)).