Python Control Flow Tools for Programmers | Python Developer

Updated:
Python control flow tools | Gamosoft Studio
(Python control flow tools)

Python uses the same general control statements as other programming languages with some twists.

if statements

"if" is a more general and versatile statement and it is found in every programming language. This is a very important statement as it is mostly used by programmers. This can be easily understood by every programmer from beginner to pro.

                    
                        x = int(input("Enter any number: "))
                        if x > 500:
                            print("The input number is more than 500")
                        elif x > 200 and x < 500:
                            print("The input number is more than 200 and less then 500")
                        elif x > 100 and x < 200:
                            print("The input number is more than 100 and less then 200")
                        else:
                            print("The input number is less then 200")

                        '''output:
                                    Enter any number: 236 
                                    The input number is more than 200 and less then 500'''
                    
                

The statement may contain zero or more "elif" parts, "else" is optional here, so you can skip if you don't have the requirements. The keyword "elif" is an abbreviation for the else if statement to avoid excessive indentation.

There may be a conflict between the "elif" sequence and the "match case". Who is closer to the "switch case"? Although the official documentation states that An "elif...elif...elif..."" sequence is a substitute for a switch statement in python because there is no switch case in python like in other programming languages, but the "match" "case" is closer to "switch case" in my view. I'll show you why I think so.

We choose a popular language JavaScript, here's what the "switch case" looks like, other programming languages also have a similar pattern.

                    
                        switch (expression) {
                            case value1:
                              // code to be executed if expression === value1
                              break;
                            case value2:
                              // code to be executed if expression === value2
                              break;
                            default:
                              // code to be executed if expression doesn't match any of the above cases
                              break;
                        }
                    
                

Now it comes to the "match case" in Python, whose statement looks like this.

                    
                        match (expression) {
                            case value1:
                              # code to be executed if expression === value1
                            case value2:
                              # code to be executed if expression === value2
                            case _:
                              # code to be executed if expression doesn't match any of the above cases
                        }
                    
                

Here you can say that "match case" is similar to "switch case", we will explain more about the "match" statement later.

for statements

The "for" loop in Python is written in a slightly different way, as we know that in most programming languages arithmetic progression of numbers is performed, but this is not the case in Python's "for" loop. If you need this you have to use "range()" function in "for" loop, we will talk about it in detail later. Typically, in Python's "for" loop, a sequence (list or string) of items is iterated over and over in the order in which they occur in the sequence.

                    
                        fruits = ["Apple", "Banana", "Orange", "Grapes"]
                        for i in fruits:
                            print(f"Fruit name: {i}")

                        '''output:
                                    Fruit name: Apple
                                    Fruit name: Banana
                                    Fruit name: Orange
                                    Fruit name: Grapes'''
                    
                

The range() function

If you want to repeat the loop again and again with arithmetic progression, then this built-in range() function is very useful. You can use this range() function in many places according to your need. Through range() it is possible that it can go from any starting number to the given number that too with certain increment which we can also call as step. Let's see how the range() function works.

                    
                        # To iterate over the indices of a sequence, you can combine range() and len() as follows:
                        fruits = ["Apple", "Banana", "Orange", "Grapes"]
                        for i in range(len(fruits)):
                            print(f"The name of the fruit at index {i} is: {fruits[i]}")

                        # list with range()
                        print(list(range(1,9)))

                        # step in range()
                        print(list(range(10,99, 15)))

                        '''output:
                                    The name of the fruit at index 0 is: Apple
                                    The name of the fruit at index 1 is: Banana
                                    The name of the fruit at index 2 is: Orange
                                    The name of the fruit at index 3 is: Grapes
                                    [1, 2, 3, 4, 5, 6, 7, 8]
                                    [10, 25, 40, 55, 70, 85]'''
                    
                

break, continue statements and else clause in loops

The working of break statement here is same as in "C" programming, when we use this break statement it comes out from the inner circle of the loop. The loop statement can have an "else" clause whose job is to jump to the "else" cause when the "for" loop is complete, but if a "break" statement is used the "else" clause will be inactive. Let's see how.

                    
                        # break statement
                        for i in range(1, 10):
                            for i1 in range(1, i):
                                if (i % 2 == 0):
                                    print(f"The number {i} is an even number.")
                                    break
                            else:
                                print(f"The number {i} is an odd number.")

                        '''output:
                                    The number 1 is an odd number.
                                    The number 2 is an even number.
                                    The number 3 is an odd number.
                                    The number 4 is an even number.
                                    The number 5 is an odd number.
                                    The number 6 is an even number.
                                    The number 7 is an odd number.
                                    The number 8 is an even number.
                                    The number 9 is an odd number.'''
                    
                
You see here that we have used "else clause" not with "if statement" but with "for loop".

The "Continue Statement" here comes from "C" programming, its job is to keep the loop going.

                    
                        # continue statement
                        for i in range(1, 10):
                            if (i % 2 == 0):
                                print(f"The number {i} is an even number.")
                                continue
                        else:
                            print(f"The number {i} is an odd number.")

                        '''output:
                                    The number 1 is an odd number.
                                    The number 2 is an even number.
                                    The number 3 is an odd number.
                                    The number 4 is an even number.
                                    The number 5 is an odd number.
                                    The number 6 is an even number.
                                    The number 7 is an odd number.
                                    The number 8 is an even number.
                                    The number 9 is an odd number.'''
                    
                

pass statements

We use "pass" statement when we need a statement at some point of time, but we don't want to execute the block of that statement right now, then we use "pass" statement. It's very easy to do, let's see how:

                    
                        if True:
                            pass
                        class EmptyClass:
                            pass
                        def emptyFun(*args):
                            pass
                        for i in [0, 1, 2]:
                            pass
                    
                

match statements

In a "match" statement, we take an expression and compare it with one or more case blocks. The case block from which the expression is found first will be executed, and will skip all the rest. The "match" statement is similar to the "switch" statement in some programming languages such as "C, Java, or JavaScript", although it corresponds more to "Rust and Haskell".

                    
                        def getError(errCode):
                            match errCode:
                                case 400:
                                    print("Bad Request")
                                case 401 | 402 | 403:
                                    print("Unauthorized, Payment Required, Forbidden")
                                case 404:
                                    print("Not Found")
                                case 407:
                                    print("Proxy Authentication Required")
                                case _:
                                    print("Not Allowed")
                        getError(404)

                        # output: Not Found
                    
                
The last block in which "_" used, it acts like a wild card, if none of the cases match then this wild card expression will be executed.

If we are structuring the data, then after the class name, we can also specify the types of the variables in the argument list and use these attributes as variables as well.

Functions

Functions are a very useful thing in any programming language, you will find it in almost every programming language, just a change in the way of writing can be seen. To write a function in Python, the keyword "def" is used, followed by the name of the function and then parentheses. We can also use parameters in brackets, this is optional.

                    
                        def tableOf(n):
                            print(f"Table of {n}")
                            for i in range(1, 11):
                                print(f"{n} x {i} = {n*i}")

                        tableOf(17)

                        '''output: 
                                    Table of 17
                                    17 x 1 = 17
                                    17 x 2 = 34
                                    17 x 3 = 51
                                    17 x 4 = 68
                                    17 x 5 = 85
                                    17 x 6 = 102
                                    17 x 7 = 119
                                    17 x 8 = 136
                                    17 x 9 = 153
                                    17 x 10 = 170'''
                    
                

Default Argument Values

The function can contain one or more arguments, depending on how many arguments you need.

                    
                        def tableOf(n, start, end):
                            print(f"Table of {n}")
                            for i in range(start, end):
                                print(f"{n} x {i} = {n*i}")

                        tableOf(13, 1, 5)

                        '''output: 
                                    Table of 13
                                    13 x 1 = 13
                                    13 x 2 = 26
                                    13 x 3 = 39
                                    13 x 4 = 52
                                    13 x 5 = 65'''
                    
                

Here we have used many arguments in the function, in which a table of "n" is written which starts with 1 and ends at 5.

Keyword Arguments

We can also call the function through keyword argument, let us see how it is done.

                    
                        def animals(name, group = "mammals", color = "N/A", description = "N/A"):
                            print(f"The {name} belongs to the group of {group} and its color is {color}, described as {description}.")

                        animals("Tiger")
                        animals("Black-necked cobra", group="reptiles")
                        animals(name="Parrot", color="vividly coloured, and some are multi-coloured", group="birds", description="strong, curved bill, an upright stance, strong legs, and clawed zygodactyl feet")

                        '''output: 
                                    The Tiger belongs to the group of mammals and its color is N/A, described as N/A.
                                    The Black-necked cobra belongs to the group of reptiles and its color is N/A, described as N/A.
                                    The Parrot belongs to the group of birds and its color is vividly coloured, and some are multi-coloured, described as strong, curved bill, an upright stance, strong legs, and clawed zygodactyl feet.'''
                    
                

It will receive dictionary when formal parameter "**args" is present, which means it will take keyword and argument pair, before this we have to use "*args" for formal parameter which receives a tuple containing positional arguments beyond the formal parameter list. It is important to use "*args" before "**args".

                    
                        def restaurant(beverage, *arguments, **keyword):
                            print(f"Do you have {beverage}?")
                            print(f"Sorry sir, we don't have {beverage}.")
                            for args in arguments:
                                print(args,)
                            print("-" * 40)
                            for kwrd in keyword:
                                print(f"{kwrd} : {keyword[kwrd]}")

                        restaurant("pizza", "If you don't have the pizza, please get my order for the burger", "  with extra onions", "  and extra cheese.", waitre = "Would you like to have something else?", costumer = "No, thank you!", waitress = "Do you like mineral water or tap water?", client = "Tap water please.")

                        '''output: 
                                    Do you have pizza?
                                    Sorry sir, we don't have pizza.
                                    If you don't have the pizza, please get my order for the burger
                                    with extra onions
                                    and extra cheese.
                                    ----------------------------------------
                                    waitre : Would you like to have something else?
                                    costumer : No, thank you!
                                    waitress : Do you like mineral water or tap water?
                                    client : Tap water please.'''
                    
                

Special Parameters

Generally, arguments to a Python function are passed either by position or explicitly by keyword. For the convenience of the developer and the performance of the program, if we specify which is a positional argument and which is a keyword argument, it would be great for both the program and the developer.

A function definition might look like this:

python special parameters | Gamosoft Studio
(Python special parameters)

The "/" and "*" here are optional, if present to indicate which are positional-only arguments, positional-or-keywords arguments, and keyword-only arguments. We also call keyword parameters as named parameters.

Positional-or-Keyword Arguments

If "/" and "*" are not present in the function definition, it means a positional-or-keyword argument that will accept both positional and keyword arguments.

Positional-Only Parameters

For positional-only parameters we will use "/" in the function definition, whatever parameters are present before "/" will be positional-only parameters. Any parameters following the "/" can be either positional-or-keywords or keyword-only. If "/" is not present in the function definition, it cannot be a positional-only parameter.

Keyword-Only Arguments

"*" is used for keyword-only parameters in a function definition, and all subsequent parameters are keyword-only parameters.

Positional-or-Keyword, Positional-Only, Keyword-Only Arguments Function examples

                    
                        def stnd_args(args):
                            print(args)
                        def pos_only_args(args, /):
                            print(args)
                        def kwrd_only_args(*, args):
                            print(args)
                        def mixed_args(pos_only, /, pos_or_kwrd, *, kwrd_only):
                            print(pos_only, pos_or_kwrd, kwrd_only)
                    
                

The first function definition stnd_args is the most common and you'll see it in most places without any restrictions where you can use positional parameters or keyword parameters or both.

                    
                        stnd_args(23)
                        stnd_args(args = 23)

                        '''output: 
                                    23
                                    23'''
                    
                

The "/" is used in pos_only_args in the second function definition which means it will only take positional parameters.

                    
                        pos_only_args(6)
                        pos_only_args(args = 6)

                        '''output: 
                                    6
                                    
                                    Traceback (most recent call last):
                                    File "d:\exercise\python\python-control-flow-tools.py", line 124, in <module>
                                        pos_only_args(args = 6)
                                    TypeError: pos_only_args() got some positional-only arguments passed as keyword arguments: 'args''''
                    
                

In the third function definition "*" is used in kwrd_only_args which indicates that only keyword parameter will be used in it, if positional parameter is used in its place then interpreter will give an error.

                    
                        kwrd_only_args(39)
                        kwrd_only_args(args = 39)

                        '''output: 
                                    Traceback (most recent call last):
                                    File "d:\exercise\python\python-control-flow-tools.py", line 125, in <module>
                                        kwrd_only_args(39)
                                    TypeError: kwrd_only_args() takes 0 positional arguments but 1 was given
                                    
                                    39'''
                    
                

In the last function definition we will use all the parameters in mixed_args.

                    
                        mixed_args(29, 32, 64)
                        mixed_args(29, 32, kwrd_only = 64)
                        mixed_args(29, pos_or_kwrd = 32, kwrd_only = 64)

                        '''output: 
                                    Traceback (most recent call last):
                                    File "d:\exercise\python\python-control-flow-tools.py", line 127, in <module>
                                        mixed_args(29, 32, 64)
                                    TypeError: mixed_args() takes 2 positional arguments but 3 were given
                                    
                                    29 32 64

                                    29 32 64'''
                    
                

Now coming to function definition which has 'name' parameter and **kwrd in which 'name' key is also used, in such case interpreter will give error.

                    
                        def foo(name, **kwrd):
                            return 'name' in kwrd
                        print(foo(7, **{'name' : 27}))

                        '''output: 
                                    Traceback (most recent call last):
                                    File "d:\exercise\python\python-control-flow-tools.py", line 133, in <module>
                                        print(foo(7, **{'name' : 27}))
                                    TypeError: foo() got multiple values for argument 'name''''
                    
                

After using positional-only argument "/" it will take name as positional arguments and 'name' as key of keyword.

                    
                        def foo(name, /, **kwrd):
                            return 'name' in kwrd
                        print(foo(5, **{'name' : 39}))

                        # output: True
                    
                

Lambda Expressions

Lambda function is a very useful thing in Python programming and you can use it in many places while programming, let me tell you how. When we write a function that has to execute a simple expression, we can write that expression very easily if we use a lambda function instead of a traditional function. Here I will give some examples of traditional-function and Landa-function and explain the difference between the two. So let's see the example:

Lambda Function basic structure

                    
                        lambda argument : expression
                    
                
  • Here 'lambda' is a Python predefined keyword for defining an anonymous function.
  • 'argument(s)' It is a placeholder to hold the variable and it holds the value of the expression.
  • 'expression' It is an execution part where expression execution is done.

Here you must have noticed that the return part is missing which we get to see in traditional function in many cases, here in lambda function it returns its value so there is no need to write return.

                    
                        def foo(s):
                            return s**2
                        print(foo(4))

                        # output: 16
                    
                

Using the Lambda function

                    
                        print((lambda x : x ** 2)(9))

                        # output: 81
                    
                

We can also write it something like this:

                    
                        x = lambda g, h : g+h
                        print(x(5, 1))
                        x = lambda g, h, i : g*h+i
                        print(x(9, 2, 6))

                        '''output: 
                                    6
                                    24'''
                    
                

Lambda functions are most useful when we use them as anonymous functions inside another function. Let's see some examples here:

                    
                        def func(a):
                            return lambda x : x **a
                        square = func(2)
                        cube = func(3)
                        print(square(6))
                        print(cube(7))

                        '''output: 
                                    36
                                    343'''
                    
                

When should we use lambda function?

We should use lambda function when there is no complex structure like if-else, for-loop etc.

Here we read about many control flow tools used in python and also know how to use it. Any programming language seems difficult until we try to understand it in simple language, if all those things are explained to you in simple language then you can easily learn it without any problem. Here I have tried my best to give you all the information related to Python Programming in simple language.

In this article

If you find this blog useful, please consider buying me a coffee. Buy Me A Coffee

author image

Rajiv Ranjan

As a digital content creator and blogger with expertise in mobile and web app development, I have a passion for creating engaging and informative content that helps to educate and inform my audience. Whether it's through writing blogs, creating videos, or designing interactive graphics, I strive to create high-quality content that adds value to my audience.

Connect me:

assistant_navigation
×
test