- There are three control flow statements in Python – if, for and while.
- Python programming language assumes any non-zero and non-null values as true and if it is either zero or null then it is assumed as false value.
Decision making statements
- if statements – An if statement consists of a boolean expression followed by one or more statements.
- if – else statements – An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
- Nested-if statements – You can use one if or else if statement inside another if or else if statement.
- While-loop – Repeats a statement or group of statements while a given condition is TRUE and tests the condition before executing.
- For-loop – Execute a sequence of statements multiple times and also abbreviates the code that manages the loop variable.
- Nested-loop – You can use a loop inside another loop.
Loop control statements
- break statement – break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.
- continue statement – continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition. It continues with the next cycle of the nearest enclosing loop.
- pass statement – pass is a null operation –when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.
Iterator and Generator
- Iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation.
- In Python, an iterator object implements two methods, iter() and next().
- The built-in function iter() takes an iterable object and returns an iterator.
- Each time we call the next method on the iterator gives us the next element. If there are no more elements, it raises a StopIteration.
- A generator is a function that yields a sequence of values using yield method.
- When a generator function is called, it returns a generator object without even beginning execution of the function.