Python – Control Strucuture


If  :
Do something

Importance of Indentation :
The statement needs to be indented with a tab.  Any outside an indentation is not part of if statement.

For example:

If i>10 and j<8:
Print (c)

In above example print statement will not work as its not part of indentation.
If-else Statement:
If :
do something
do something else
Similarly you can have elif statement
If :
do something
Elif :
do something else
do something else


For Loop:

Like other languages in python also we have various loops. For loop is used widely.  Indentation is important in for loop and works in similar ways it works for conditional statements.
Format is ==> for xxxx in yyy :
do something
For i in range(1,5):
Tweet = “#beautiful #morning it is looking good”
For word in tweet.split():
if word.startswith(‘#’):
As you can see we can use conditional formatting inside the for loop indented under.

While Loop:

While loop can be used where you need to run the same loop multiple times or more than once.
#while Loop
Total = 0
While start < 51:
As you can see while loop will run 51 times starting from 21  and keep on adding the values to total, which is defined at zero. Final value of total is printed at the end of the program.  As print(total) is not indented under while loop it will only be printed once.


Functions as name suggests performs a task or function. They are blocks of code that can be reused at various parts of the code as well as various files. When you import any package and call any of its methods, you make use of the functions defined in it. This makes determining the use of each portion of the code significantly easier.
Functions give freedom to use the same code multiple times in a program. Similar to if-else and the for loop, the parts belonging to a function are indented on it.
Create a function squared(),  which takes x and y as arguments and returns the x**y value. For e.g., if x = 2  and y = 3 , then the output is 8.
def squared(x,y):
    out = x**y

1. Lambda function:

The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). The lambda feature was added to Python due to the demand from Lisp programmers.
Indentation is used in same manner as for other operators in python. (:)
f = lambda x, y : x + y
Create a lambda function ‘greater’, which takes two arguments x and y and return x if x>y otherwise y.
If x = 2 and y= 3, then the output should be 3.
a = int(input_list[0])
b = int(input_list[1])
greater = lambda x,y : x if x>y else y

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.