Python Control Flow Statements Tutorial For Beginners 2020. Here in this blog post Coding compiler sharing Python 3 programming control flow statements tutorial for beginners. This Python tutorial is for absolute beginners who are looking for learning Python programming. Let’s start learning Python 3.
Python Control Flow Statements
In addition to the while statements introduced earlier , Python also borrowed some of the flow control features from other languages and changed them.
Related Articles: Python Getting Started Guide
1. if statement
Perhaps the most famous is the if statement. E.g:
>>> x = int ( input ( "Please enter an integer: " ))
Please enter an integer: 42
>>> if x < 0 :
... x = 0
... print ( 'Negative changed to zero' )
... elif x == 0 :
... print ( 'Zero' )
... elif x == 1 :
... print ( 'Single' )
... else :
... print ( 'More' )
...
More
There may be zero or more elif sections, and else is optional. The keyword ‘ elif ‘ is an abbreviation for ‘else if’, which can effectively avoid excessive indentation. IF … elif … elif … sequence is a substitute other languages switch
or case
statements.
2. For statement
The for statement in Python is slightly different from C or Pascal. Ordinary loops may be based on an arithmetic step process (such as Pascal), or the user defines iterative steps and abort conditions (such as C).
Python’s for statement is based on children in any sequence (list or string). , Iterate through their order in the sequence. For example (without implied):
>>> # Measure some strings:
... words = [ 'cat' , 'window' , 'defenestrate' ]
>>> for w in words :
... print ( w , len ( w ))
...
cat 3
window 6
defenestrate 12
Modifying iterative sequences during iteration is not safe (this is only possible when using variable sequences such as linked lists).
If you want to modify your iterative sequence (for example, copy options), you can iterate over its copy. You can do this easily by using the cut logo:
>>> for w in words [:]: # Loop over a slice copy of the entire list.
... if len ( w ) > 6 :
... words . insert ( 0 , w )
...
>>> words
[ 'defenestrate', 'CAT', 'window', 'defenestrate']
3. The range() Function
If you need a numeric sequence, the built-in function range() is convenient. It generates an arithmetic progression list:
>>> for i in range ( 5 ):
... print ( i )
...
0
1
2
3
4
range(10)
A list of 10 values is generated, which populates this list of length 10 with the index of the linked list.
Related Article: Python Interpreter Tutorial
The generated list does not include the end value in the range. It is also possible to let the range() operation start from another value, or you can specify a different step (even a negative number, sometimes called a “step”):
Range ( 5 , 10 )
5 through 9
Range ( 0 , 10 , 3 )
0 , 3 , 6 , 9
Range ( - 10 , - 100 , - 30 )
- 10 , - 40 , - 70
If iterative list indexing is needed, combine range() and len() as shown below
>>> a = [ 'Mary' , 'had' , 'a' , 'little' , 'lamb' ]
>>> for i in range ( len ( a )):
... print ( i , a [ i ])
...
0 Mary
1 had
2 a
3 little
4 lamb
However, this situation can easily use the enumerate () .
If you just print a sequence, strange things happen:
>>> print ( range ( 10 ))
range(0, 10)
The object returned by the range() function in different aspects behaves as if it were a list, but in fact it is not. When you iterate over it, it is an object that returns consecutive items like the expected sequence; but to save space, it doesn’t really construct lists.
We call such objects are iterable , that is suitable for those who expect something from successive terms until a target (parameters) the end of the function or structure.
The for statement we have seen is such an iterator. The list() function is another (an iterator ) that creates a list from iterable (objects):
>>> list ( range ( 5 ))
[0, 1, 2, 3, 4]
Later we will see more functions that return iterables (objects) and parameters that can be iterated (objects).
4. break and continue Statements, and the else Clause in a Loop
The break statement is similar to C and is used to jump out of the most recent level of a for or whileloop.
Cycle may have a else
clause; it is in the loop iterations complete list (with for ) or when the condition becomes false (with while execution), the cycle but is break the case does not suspend the execution.
The following sample program for searching for prime numbers demonstrates this clause:
>>> for n in range ( 2 , 10 ):
... for x in range ( 2 , n ):
... if n % x == 0 :
... print ( n , 'equals' , x , '*' , n // x )
... break
... else :
... # loop fell through without finding a factor
... print (n , 'is a prime number' )
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
(Yes, this is the correct code. Look carefully: else
Statements are in the for loop, not the if statement.)
When used with the cycle, else
clauses and try statement else
clause ratio if have more in common with the statement: try statement else
clause run when an exception does not appear, circulating else
clause does not appear in the break
running.
The continue statement is borrowed from C, which means that the loop continues to execute the next iteration:
>>> for num in range ( 2 , 10 ):
... if num % 2 == 0 :
... print ( "Found an even number" , num )
... continue
... print ( "Found a Number" , num )
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
5. The pass statement
The pass statement does nothing. It is used for those grammars that must have what statements, but the program does nothing, such as:
>>> while True :
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is usually used to create a minimally structured class:
>>> class MyEmptyClass :
... pass
...
On the other hand, pass can be used as a placeholder for functions or control bodies when creating new code. Allows you to think at a more abstract level. Pass can be silently ignored:
>>> def initlog ( * args ):
... pass # Remember to implement this!
...
6. Defining Functions
We can create a function to generate the Fibonacci sequence of the specified boundary:
>>> def fib ( n ): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a , b = 0 , 1
... while a < n :
... print ( a , end = ' ' )
... a , b = b , a + b
... print ()
...
>>> # Now call the function we just defined:
...Fib ( 2000 )
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Keyword def introduces a function definitions . It must be followed by a function name and parentheses that include formal parameters. The function body statement starts from the next line and must be indented.
The first line of a function body can be an optional string literal, which is a function’s document string, or docstring . Tools automatically generate some documents online or printable by docstrings, or let users browse interactively through the code; include docstrings is a good practice in your code, it Become accustomed to it.
Function calls will generate a new symbol table as a function of local variables. Specifically, variable assignments in all functions store values in local symbol tables.
Related Article: Python For Machine Learning
The variable reference is first looked up in the local symbol table, then the local symbol table containing the function, then the global symbol table, and finally the built-in name table.
Therefore, global variables cannot be assigned directly to functions (unless they are named using global statements), although they can be referenced.
The actual function parameters are introduced in the function call in the local symbol table, therefore, the argument always call-by (where the value is always an object reference, rather than the value of the object). When a function is called by another function, a new local symbol table is created during the call.
A function definition will introduce the function name in the current symbol table. It refers to the value of the function name (i.e., the function thereof) has been identified as a Python interpreter user-defined function types.
This value can be given another name (that is, the variable name), and it can also be used as a function. This can be used as a generic rename mechanism:
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f ( 100 )
0 1 1 2 3 5 8 13 21 34 55 89
If you have used other languages, you may object to saying: fib
Not a function, but a method because it does not return any value. In fact, a function without a return statement does return a value, albeit a rather boring one (None).
This value is called None
(this is a built-in name). If the None
value is the only value to be written, then at the time of writing is often overlooked interpreter (ie, does not output anything). If you really want to see the output of this value, use the print() function:
>>> fib ( 0 )
>>> print ( fib ( 0 ))
None
Defining a function that returns a list of Fibonacci numbers rather than printing it is simple:
>>> def fib2 ( n ): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a , b = 0 , 1
... while a < n :
... result . append ( a ) # see below
... a , b = b , a + b
... return result
...
>>> f100 = fib2 ( 100 ) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
As before, this example demonstrates some of the new Python features:
-
return statement returns a value from the function without an expression return return
None
.It will also return after the process ends
None
. -
Statement
result.append(b)
called list objectresult
one method . The method is a “belongs to” an object function, which is namedobj.methodename
, hereobj
is an object (an expression may be),methodename
is the name of a method in the object type definition.Different types define different methods. Different types may have the same name, but they will not be confused. (When you define your own object types and methods, it may happen, classdefinitions are detailed in class ).
- In the example,
append()
methods defined list objects that a new element is added to the list. In the example it is equivalent to , but more efficient.result = result + [a]
7. In-depth Python function definition
In Python, you can also define functions that contain several parameters. There are three available forms here and they can also be mixed.
Related Article: Introduction to Python Programming
7.1. Default Parameter Values
One of the most common forms is to specify default values for one or more parameters. This creates a function that can be called with fewer arguments than allowed during the definition, for example:
Def ask_ok ( prompt , retries = 4 , complaint = 'Yes or no, please!' ):
while True :
ok = input ( prompt )
if ok in ( 'y' , 'ye' , 'yes' ):
return True
if Ok in ( 'n' , 'no' , 'nop' , 'nope' ):
return False
retries = retries - . 1
IF retries < 0 :
The raise OSError ( 'User uncooperative' )
Print ( Complaint )
This function can be called in several different ways:
-
Only give the necessary parameters:
ask_ok('Do you really want to quit?')
-
Give an optional parameter:
ask_ok('OK to overwrite the file?', 2)
-
Or give all the parameters:
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
This example also introduces the in keyword. It determines if a certain value is included in the sequence.
The default value of the function defined is resolved scope, as follows:
i = 5
Def f ( arg = i ):
print ( arg )
i = 6
f ()
Will output 5
.
Important warning: The default value is only assigned once. This makes it different when the default value is mutable, such as lists, dictionaries, or instances of most classes. For example, the following function accumulates (previously) the parameters passed to it during subsequent calls:
Def f ( a , L = []):
L . append ( a )
return L
Print ( f ( 1 ))
print ( f ( 2 ))
print ( f ( 3 ))
This will output:
[ 1 ]
[ 1 , 2 ]
[ 1 , 2 , 3 ]
If you don’t want the default value to accumulate in subsequent calls, you can define the function as follows:
Def f ( a , L = None ):
if L is None :
L = []
L . append ( a )
return L
7.2. Keyword Parameters
It can function key parameter to the call of the form, the form . For example, the following function:keyword = value
Def parrot ( voltage , state = 'a stiff' , action = 'voom' , type = 'Norwegian Blue' ):
print ( "-- This parrot wouldn't" , action , end = ' ' )
print ( "if you Put" , voltage , "volts through it." )
print ( "-- Lovely plumage, the" , type )
print ( "-- It's" , State , "!")
Receiving a mandatory parameter ( voltage
) and three optional parameters ( state
, action
, and type
). It can be called with any of the following methods:
Parrot ( 1000 ) # 1 positional argument
parrot ( voltage = 1000 ) # 1 keyword argument
parrot ( voltage = 1000000 , action = 'VOOOOOM' ) # 2 keyword arguments
parrot ( action = 'VOOOOOM' , voltage = 1000000 ) # 2 keyword arguments
Parrot ( 'a million' , 'bereft of life' , 'jump' ) # 3 positional arguments
parrot ('a thousand' , state = 'pushing up the daisies' ) # 1 positional, 1 keyword
However, the following types of calls are invalid:
Parrot () # required argument missing
parrot ( voltage = 5.0 , 'dead' ) # non-keyword argument after a keyword argument
parrot ( 110 , voltage = 220 ) # duplicate value for the same argument
parrot ( actor = 'John Cleese' ) # unknown keyword argument
In a function call, the argument of the keyword must follow the positional argument. All keyword arguments passed must match the function accepts a parameter (eg actor
not a parrot
valid argument to the function), their order is not important.
It also includes a non-optional parameters (e.g., parrot(voltage=1000)
is also effective). No parameter can be assigned multiple times. The following example will fail due to this restriction:
>>> def function ( a ):
... pass
...
>>> function ( 0 , a = 0 )
Traceback (most recent call last):
File "<stdin>" , line 1 , in ?
TypeError : function () got multiple values for keyword argument 'a'
The introduction of a shape **name
parameter, which receives a dictionary (see the Mapping Types – dict ), which comprises all the dictionary does not appear in the form of a parameter list keyword parameters.
There may also be a combination *name
of formal parameters such as (described in detail in the next section) that receive a tuple (detailed in the next section) containing all parameter values that are not present in the formal parameter list ( *name
must in the **name
prior appearance). For example, we define a function like this:
Def cheeseshop ( kind , * arguments , ** keywords ):
print ( "-- Do you have any" , kind , "?" )
print ( "-- I'm sorry, we're all out of" , kind )
For arg in arguments :
print ( arg )
print ( "-" * 40 )
keys = sorted ( keywords . keys ())
for kw In keys :
print ( kw , ":" , keywords [ kw ])
It can be called like this:
Cheeseshop ( "Limburger" , "It's very runny, sir." ,
"It's really very, VERY runny, sir." ,
shopkeeper = "Michael Palin" ,
client = "John Cleese" ,
sketch = "Cheese Shop Sketch" )
Of course it prints as follows:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
Client : John Cleese
Shopkeeper : Michael Palin
Sketch : Cheese Shop Sketch
Note Before printing keyword arguments by keyword dictionary keys()
to sort the results of a method to generate a list of keyword argument names; If you do not, print out the order of the arguments is undefined.
7.3. Variable Parameter List
Finally, one of the least common choices is to make the function call a variable number of arguments. These parameters are packaged into a tuple (see tuples and sequences ). Before these variable numbers of parameters, there can be zero or more common parameters:
Def write_multiple_items ( file , separator , * args ):
file . write ( separator . join ( args ))
Typically, these parameters are the last parameters in the list, because they will pass all of the remaining input parameters to the function. Any appears in *args
the argument is the key parameter, which means they can only be used as a keyword, rather than positional parameters:
>>> def concat ( * args , sep = "/" ):
... return sep . join ( args )
...
>>> concat ( "earth" , "mars" , "venus" )
'earth/mars /venus'
>>> concat ( "earth" , "mars" , "venus" , sep = "." )
'earth.mars.venus'
7.4. Splitting the parameter list
The other case is the opposite: When the argument you are passing is already a list, the function to be called accepts a separate argument value. At this point you have to split the existing list.
For example, the built-in function range() requires separate start and stop parameters. You can add in a function call *
operator to automatically open the parameter list:
>>> list ( range ( 3 , 6 )) # normal call with separate arguments
[3, 4, 5]
>>> args = [ 3 , 6 ]
>>> list ( range ( * args )) # call with arguments Unpacked from a list
[3, 4, 5]
In the same manner, using **
the operator key parameters split dictionary:
>>> def parrot ( voltage , state = 'a stiff' , action = 'voom' ):
... print ( "-- This parrot wouldn't" , action , end = '' )
... print ( " If you put" , voltage , "volts through it." , end = '' )
... print ( "E's" , state , "!" )
...
>>> d = { "voltage" : "four million" , "state" : "bleedin' demised" , "action" : "VOOM" }
>>> parrot ( ** d )
-- This parrot wouldn't VOOM if you put four Million volts through it. E's bleedin' demised !
7.5. Lambda Form
For practical purposes, there are several features that are commonly found in functional programming languages such as Lisp added to Python. With the lambda keyword, you can create short anonymous functions. There is a function that returns its two arguments: . The Lambda form can be used for any desired function object. For syntax restrictions, they can only have a single expression. Semantically, they are just a syntactical technique in the definition of ordinary functions. Similar to a nested function definition, the lambda form can refer to a variable from an external scope:lambda a, b: a+b
>>> def make_incrementor ( n ):
... return lambda x : x + n
...
>>> f = make_incrementor ( 42 )
>>> f ( 0 )
42
>>> f ( 1 )
43
The above example uses a lambda expression to return a function. Another use is to pass a small function as a parameter:
>>> pairs = [( 1 , 'one' ), ( 2 , 'two' ], ( 3 , 'three' ), ( 4 , 'four' ]]
>>> pairs . sort ( key = lambda pair : Pair [ 1 ])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
7.6. Document String
The concept and format of the docstrings introduced here.
The first line should be a brief introduction to the purpose of the object. For the sake of brevity, there is no need to explicitly state object names or types because they can be learned from other sources (unless the name happens to be a verb describing the operation of the function). This line should begin with a capital letter and end with a period.
If the docstring has more than one line, the second line should be vacant and clearly separated from the following detailed description. The next document should have one or more paragraphs describing the object’s calling convention, boundary effects, and so on.
The Python interpreter does not remove indentations from multi-line docstrings, so you should clear the indentations yourself when necessary. This is in line with the usual habits.
The first non-blank line after the first line determines the indentation format of the entire document. (We don’t use the first line because it’s usually close to the initial quotation mark. The indentation format isn’t clear.) The blank “equivalent” is the starting indentation of the string.
Each line should not be indented. If there is indentation, all the blanks should be removed. The length of the white space should be equal to the width of the extended tab (usually 8 spaces).
The following is an example of a multi-line docstring:
>>> def my_function ():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print ( my_function . __doc__ )
Do nothing, but document it.
No, really, it doesn't do anything.
7.7. Function annotations
Function annotations are completely optional, arbitrary metadata information about user-defined functions. Function annotations are not used in Python itself or in the standard library; this section only describes the syntax. Third-party projects are free to choose function annotations for documentation, type checking, and other uses.
Annotations are stored in a dictionary function __annotations__
attributes, there is no effect on other parts of the function. Parameter annotations are defined after the colon of the parameter name, followed by a worthwhile expression used to represent the annotation.
Note return (Return annotations) is defined in a ->
rear, immediately following an expression in the colon and ->
between. The following example contains a positional parameter, a keyword parameter, and a meaningless return value comment:
>>> def f ( ham : 42 , eggs : int = 'spam' ) -> "Nothing to see here" :
... print ( "Annotations:" , f . __annotations__ )
... print ( "Arguments:" , ham , eggs )
...
>>> f ( 'wonderful' )
Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42}
Arguments:Wonderful spam
Related Articles:
Python Programming Interview Questions