Logo

Control Structures

Python uses the usual flow control statements known from other languages, with some twists.

if Statements

Perhaps the most well-known statement type is the if statement. For example:

 

 

There can be one or more elif statements, and the else statement is optional.

The keyword 'elif' is an abbreviation for 'else if' and can be used to avoid excessive indentation. An if... elif... elif... sequence is a replacement for switch or case statements in other programming languages.

 

for Statements

The for statement in Python varies slightly from what you are used to seeing in C or Pascal.

Python's for statement repeats over the items of any sequence (a list or a string), in the order that they show up in the sequence. As in case :

 

 

It can be difficult to write code that alters a selection while processing data over that same collection. Rather, it is generally easier to loop through a duplicate of the selection or to build a new collection.

 

The range() Function

If you really need to loop over a set of numbers, the built-in function range() is useful. It creates the respective arithmetic progressions:

 

 

The given end point is not ever included in the generated sequence, example : range(10) returns 10 values. Which are the legal indices for items in a 10-item sequence.

It is possible to start the range at a different number or to specify a different increment (even a negative one; sometimes this is referred to as the 'step'):

 

 

To repeat over a sequence's index values, merge range() and len() as shown in:

 

 

In most such cases, however, it is convenient to use the enumerate() function, as demonstrated below.

 

 

If you are curious to try to print range, you would be shown the starting and ending positions of the range values.

 

Range

Figure 8.1. Output produced upon printing the range function.

 

In several ways, the object returned by range() behaves like a list, but it isn't.

This is an object that, when iterated over, returns the successive items of the desired sequence, but this does not actually make the list, saving space.

We call such an object iterable because it can be used as a target for functions and constructs that expect something from which they can obtain successive items until the supply is depleted.

The for statement is an example of such a construct, and sum() is an example of a function that takes an iterable:

 

 

More functions that return iterables as well as take iterables as arguments will be introduced later.

Finally, perhaps you're inquisitive about how to generate a list from a range. Here's how to fix it:

 

 

Break,Else and Continue

The break statement exits the for or while loop's innermost containing for or while loop.

An else clause can be used in loop statements. it is executed when the loop terminates due to iterable exhaustion (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

The following loop, which searches for prime numbers, exemplifies this:

 

 

If we look closely, we can see that the else clause belongs to the for loop, not the if statement.

When used with a loop, the else clause is more similar to the else clause of a try statement than it is to the else clause of an if statement.

The else clause of a try statement runs when no exception occurs, whereas the else clause of a loop runs when no break occurs.

See Handling Exceptions for more information on the try statement and exceptions.

The next iteration of the loop is continued by the continue statement:

 

 

pass Statements

The pass statement has no effect. It can be used when a statement is required syntactically but no action is required by the program. As an example:

 

Pass

Figure 8.2. Demonstration of pass statement.

 

Defining Functions

We can write the Fibonacci series function:

 

 

A function definition is introduced by the keyword 'def'.

It must be followed by the function name and a list of formal parameters in parentheses.

The statements that make up the function's body begin on the next line and must be indented.

The first line of the function definition is a string literal that serves as the documentation string, or docstring. Include docstrings in your code as a matter of course; make it a habit.

Here the series is created by the sum of the two preceding ones The sequence usually begins with 0 and 1 and increments till end value 2000.

The output of the same can be also seen in the console.

Instead of printing the Fibonacci series, it is simple to write a function that returns a list of the numbers in the series:

 

 

The return statement returns the result of a function.

The statement result.append(a) invokes a method of the result list object.

A method is a function that 'belongs' to an object, which is denoted by the letter obj. methodname, where obj is an object (it could be an expression) and methodname is the name of a method defined by the object's type.

Different types of methods can have the same name without causing ambiguity. (Using classes, you can define your own object types and methods; see Classes for more information.)

The method append() in the example is defined for list objects; it adds a new element to the list's end.

It is equivalent to result = result + [a] in this example, but more efficient.

The most practical form is to set a default value for one or more arguments.

This results in a function that can be called with fewer arguments than its definition allows. As an example:

 

 

Note :  The in keyword tests whether or not a sequence contains a certain value.

The default values are evaluated at the point of function definition in the defining scope, so that.

 

 

The default value is only evaluated once. When the default is a mutable object, such as a list, dictionary, or instances of most classes, this makes a difference.

 

 

If you don't want the default to be shared between subsequent calls, write the function as follows:

 

 

Keyword Arguments

Keyword arguments of the form kwarg=value can also be used to call functions. Consider the following function:

 

 

Keyword arguments must come before positional arguments in a function call.

All keyword arguments must match one of the arguments accepted by the function (for example, actor is not a valid argument for the parrot function), and their order is unimportant.

This includes non-optional arguments (for example, parrot(voltage=1000) is also valid).

A value may not be assigned to an argument more than once.

Here's an example that fails because of this constraint:

 

 

When a final formal parameter of the form **name is present, a dictionary (see Mapping Types — dict) containing all keyword arguments except those corresponding to a formal parameter is returned.

This can be combined with a formal parameter of the form *name (described in the following subsection), which receives a tuple containing the positional arguments that are not included in the formal parameter list. (*name has to come before **name.)

For example, consider the following function:

 

 

It's worth noting that the order in which the keyword arguments are displayed is assured to match the sequence in that they were passed to the function call.

 

Special parameters

By default, arguments to a Python function could be passed either by position or explicitly by keyword.

For readability and performance, it stands to reason to limit the types of arguments which can be passed so that a developer only needs to look at the function definition to determine whether items are passed by position, by position and keyword, or by keyword.

 

Arguments

Figure 8.3. Parameters inside a function.

 

where the characters / and * are optional.

These symbols, if present, indicate the type of parameter by indicating how the arguments may be passed to the function: positional-only, positional-or-keyword, and keyword-only.

Named parameters are another name for keyword parameters.

 


________________________________________________________________________________________________________________________________
Footer
________________________________________________________________________________________________________________________________

Copyright © 2022-2023. Anoop Johny. All Rights Reserved.