Sei sulla pagina 1di 12

1|Page Introduction to programming using Python

Python Decision Making Statements

Sometimes, in a program, we may want to make a decision based on a condition. We know that an
expression’s value can be True or False. We may want to do something only when a certain condition is
true. For example, assume variables a and b. If a is greater, then we want to print “a is greater”.
Otherwise, we want to print “b is greater”. For this, we use an if-statement. Also, operators come in
handy when you want to join conditions to make a composite one.
Python if Statements

An if statement in python takes an expression with it. If the expression amounts to True, then the block
of statements under it is executed. If it amounts to False, then the block is skipped and control transfers
to the statements after the block. But remember to indent the statements in a block equally. This is
because we don’t use curly braces to delimit blocks. Also, use a colon (:) after the condition.

7 is good

Here, since 7>6, the condition is true. So, it prints the given string.

We know, 1 has a Boolean value of True. So, the condition is true,


and it prints ‘boolean value 1 for true’. Python if Statement
2|Page Introduction to programming using Python

Python if-else Statements

What happens when the condition is untrue? We can mention that it in the block after the else statement.
An else statement comes right after the block after ‘if’.

Pay attention to the indent. The else keyword does not appear in the if-block.
Press Backspace to undo the automatic indent. Here, 2 is not less than 1.
So, the statements in the else-block are executed. It prints 1.
Chained Conditionals (elif ladder)
Python allows the elif keyword as a replacement to the else-if statements
in Java or C++. When we have more than one condition to check,
we can use it. If condition 1 isn’t True, condition 2 is checked.
If it isn’t true, condition 3 is checked.
Python if else Statement

As we saw, else if causes a syntax error. We must use elif.


Here, 2 is not less than 1, so, the condition with elif is checked.
Since it is true (1<3), it prints 1.
Also, you can put an else statement after your elif statements
if you want. Since in the last example,
the first two conditions are false, the else is executed. So, it prints 1.

Python Chained operators


3|Page Introduction to programming using Python

6. Nested if Statements in Python

You can put an if statement in the block under another if statement. This is to implement further checks.

a is 1 and b is 2

Here, a is 1. So, b is checked. Since it is 2, it prints the given string. Not every if block has to have
statements though.

7. Single Statement Condition in Python


If you only need to write a single statement under if,
you can write it in the same line using single statement
python decision making constructs.

Greater

Here, we wrote it in one line, but it works without a problem.

Nested if Statements in Python


Hi
Works
4|Page Introduction to programming using Python

Python for Loop, Nested for Loop


When you want some statements to execute a hundred
times, you don’t repeat them 100 times. Think of when
you want to print numbers 1 to 99. Or that you want to
say Hello to 99 friends. In such a case, you can use
loops in python.

Here, we will discuss 4 types of Python Loop:

Python for Loop


Python While Loop
Python Loop Control Statements
Nested for Loop in Python

Python While Loop


while loop in python iterates till its condition becomes
False. In other words, it executes the statements under
itself while the condition it takes is True.

When the program control reaches the while loop, the


condition is checked. If the condition is true, the block
of code under it is executed. Remember to indent all
statements under the loop equally. After that, the
condition is checked again. This continues until the
condition becomes false. Then, the first statement, if
any, after the loop is executed.

3
2
1
This loop prints numbers from 3 to 1. In Python, a—wouldn’t work. We use a-=1 for the
same.
5|Page Introduction to programming using Python

An Infinite Loop
Be careful while using a while loop. Because if
you forget to increment the counter variable in
python, or write flawed logic, the condition may
never become false. In such a case, the loop will
run infinitely, and the conditions after the loop
will starve. To stop execution, press Ctrl+C.
However, an infinite loop may actually be useful.
This in cases when a semaphore is needed, or for
client/server programming. A semaphore is a
variable used solely for synchronization in
accessing shared resources.

The else statement for while loop

A while loop may have an else statement after it. When the condition becomes false, the block under the
else statement is executed. However, it doesn’t execute if you break out of the loop or if an exception is
raised.

3
2
1

Reached 0

In the following code, we put a break statement in the body of the while loop for a==1. So, when that
happens, the statement in the else block is not executed.

3
2
6|Page Introduction to programming using Python

Single Statement while

Like an if statement, if we have only one statement in while’s body, we can write it all in one line.

3
2
1
You can see that there were two statements in while’s body, but we used semicolons to separate them.
Without the second statement, it would form an infinite loop.

Python for Loop

Python for loop can iterate over a sequence of items. The structure of a for loop in Python is different
than that in C++ or Java. That is, for (int i=0; i<n; i++) won’t work here. In Python, we use
the ‘in’ keyword.

0
1
2
If we wanted to print 1 to 3, we could write the following code.

1
2
3
7|Page Introduction to programming using Python

The range() function

This function yields a sequence of numbers. When called


with one argument, say n, it creates a sequence of numbers
from 0 to n-1.

print (list (range (10)))


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We use the list function to convert the range object into a


list object.
Calling it with two arguments creates a sequence of
numbers from the first to the second.

print (list (range (2,7)))

[2, 3, 4, 5, 6]

You can also pass three arguments. The third argument is the interval.

print (list (range (2,12,2)))

[2, 4, 6, 8, 10]

Remember, the interval can also be negative.

print (list (range (12,2, -2)))


[12, 10, 8, 6, 4]

However, the following codes will return an empty list.

print (list (range (12,2)))

[]

print (list (range (2,12, -2)))

[]

print (list (range (12,2,2)))

[]
Iterating on lists or similar constructs

You aren’t bound to use the range() function, though. You can use the loop to iterate on a list or a
similar construct.
8|Page Introduction to programming using Python

1
2
3

2
3
4
You can also iterate on a string.

w
i
s
d
o
m

Iterating on indices of a list or a similar construct

The len() function returns the length of the list. When you apply the range() function on that, it
returns the indices of the list on a range object. You can iterate on that.

Romanian
Spanish
Gujarati

The else statement for for-loop

Like a while loop, a for-loop may also have an else statement after it. When the loop is exhausted, the
block under the else statement executes.

0
1
2
3
Reached else
Like in the while loop, it doesn’t execute if you break out of the loop or if an exception is raised.
9|Page Introduction to programming using Python

0
1
2
3
Nested for Loops Python
You can also nest a loop inside another. You can put a for loop inside a while, or a while inside a for, or
a for inside a for, or a while inside a while. Or you can put a loop inside a loop inside a loop. You can go
as far as you want.

*
**
***
****
*****
Let’s look at some nested while loops to print the same pattern.

*
**
***
****
*****
10 | P a g e Introduction to programming using Python

Loop Control Statements in Python

Sometimes, you may want to break out of normal execution in a loop. For this, we have three keywords
in Python- break, continue, and pass.

break statement

When you put a break statement in the body of a loop, the loop stops executing, and control
shifts to the first statement outside it. You can put it in a for or while loop.

b
r
e
a

continue statement

When the program control reaches the continue statement, it skips the statements after ‘continue’. It then
shifts to the next item in the sequence and executes the block of code for it. You can use it with both for
and while loops.

1
2
3
4
5
7
8
If here, the iteration i+=1 succeeds the if condition, it prints to 5 and gets stuck in an infinite loop. You
can break out of an infinite loop by pressing Ctrl+C.
11 | P a g e Introduction to programming using Python

0
1
2
3
4
5

Traceback (most recent call last):


File “<pyshell#14>”, line 1, in <module>
while(i<8):
KeyboardInterrupt

pass statement

In Python, we use the pass statement to implement stubs. When we need a particular loop, class, or
function in our program, but don’t know what goes in it, we place the pass statement in it. It is a null
statement. The interpreter does not ignore it, but it performs a no-operation (NOP).

>>> for i in 'selfhelp':

pass

>>> print(i)

p
To run this code, save it in a .py file, and press F5. It causes a syntax error in the shell.