Flow Controls¶
Python uses the usual flow control statements known from other languages, with some twists.
There are three control flow statements in Python - if
, for
and while
.
if
Statement¶
The most well-known statement type is the if statement. For example:
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
<ipython-input-2-5712790f94ca> in <module>
----> 1 x = int(input("Please enter an integer: "))
2 if x < 0:
3 x = 0
4 print('Negative changed to zero')
5 elif x == 0: # keyword ‘elif’ is short for ‘else if’
/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
852 """
853 if not self._allow_stdin:
--> 854 raise StdinNotImplementedError(
855 "raw_input was called, but this frontend does not support input requests."
856 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
for
Statement¶
The for statement in Python differs a bit from what you may be used to in C or Pascal. Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):
The range()
function¶
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy.
We can get a list from a range
break
, continue
and else
¶
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
When used with a loop, the else
clause has more in common with the else
clause of a try
statement than it does with that of if
statements: a try
statement’s else
clause runs when no exception occurs, and a loop’s else
clause runs when no break
occurs.
The continue
statement, also borrowed from C, continues with the next iteration of the loop:
pass
statement¶
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
pass
can also be used as a place-holder for a function or conditional body when you are working on something new, to allow you to keep thinking at a more abstract level.
Exercise:¶
Print 1 - 10.
Print 1 - 10 except 5 and 8
Print if a number is even or odd
Print all divisor of number