Python programs consist of a sequence of statements. The interpreter executes each statement in order until there are no more statements. This is true if files run as the main program, as well as if they are loaded via import. All statements, including variable assignment, function definitions, class definitions, and module imports, have equal status. There are no special statements that have higher priority than any other, and every statement can be placed anywhere in a program. All the instructions/statements in the program are executed in sequence in general. However, there are two main ways of controlling the flow of program execution—conditional statements and loops.
The if...else and elif statements control the conditional execution of statements. The general format is a series of if and elif statements followed by a final else statement:
else: print('Something else')
Note the use of the == operator to compare the two values. This returns True if both the values are equal; it returns False otherwise. Note also that setting x to a string will return Something else rather than generate a type error as may happen in languages that are not dynamically typed. Dynamically typed languages, such as Python, allow flexible assignment of objects with different types.
The other way of controlling program flow is with loops. Python offers two ways of constructing looping, such as the while and for loop statements. A while loop repeats executing statements until a Boolean condition is true. A for loop provides a way of repeating the execution into the loop through a series of elements. Here is an example:
In this example, the while loop executes the statements until the condition x < 3 is true. Let's consider another example that uses a for loop:
>>>words = ['cat', 'dog', 'elephant']
>>> for w in words:
In this example, the for loop executes iterating for all the items over the list.