Convert the following loops as directed.
1. while => for
X=5
while(x<10):
print(x+10)
X+=2
2. for => while
for x in range(5,20,5):
print(x)
Answers
Explanation:
Now!
Loops
There are two types of loops in Python, for and while.
The "for" loop
For loops iterate over a given sequence. Here is an example:
script.py
IPython Shell
Run
Powered by DataCamp
For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange). Note that the range function is zero based.
script.py
IPython Shell
Run
Powered by DataCamp
"while" loops
While loops repeat as long as a certain boolean condition is met. For example:
script.py
IPython Shell
Run
Powered by DataCamp
"break" and "continue" statements
break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few examples: