Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Decision making is an essential concept in any programming language and is required when

you want to execute code when a specific condition is satisfied.


If statements (also called conditionals or selection) change the flow of control through the
program so that some code is only run when something is true.
Conditional Statement
Conditional statements (if, else, and elif) are fundamental programming constructs that allow
you to control the flow of your program based on conditions that you specify. They provide a
way to make decisions in your program and execute different code based on those decisions.
In Python, there are three forms of the if...else statement.
1. if statement
2. if...else statement
3. if...elif...else statement

Python if statement
The most basic type of if statement in its simplest form, it looks like this:

if <expr>:
<statement>

• <expr> is an expression evaluated asaBoolean.


• <statement> is a valid Python statement, which must be indented.

If <expr> is true (evaluates to a value that is “truth”), then <statement> is executed.


If <expr> is false, then <statement> is skipped over and not executed.

Note that the colon (:) following <expr> is required.


Working of if Statement

Example:
number = 10
# check if number is greater than 0
if number > 0:
print('Number is positive.')
print('After if statement')

Output:
Number is positive.
After if statement

In the code below, both the print statements will be executed since a is greater than 50.

Since 20 is not greater than 50, the statement present inside the if block will not execute.
Instead, the statementpresent outside the if block is executed.
A compound if statement in Python looks like this:

if<expr>:
<statement>
<statement>
...
<statement>
<following_statement>

The entire block is executed if <expr> is true, or skipped over if <expr> is false. Either way,
execution proceeds with <following_statement> afterward.
Blocks can be nested to arbitrary depth. Each indent defines a new block, and each outdent
ends the preceding block. The resulting structure is straightforward, consistent, and intuitive.
Example:
x=0
y=5
ifx > y:
print('Expression was true')
print('Executing statement in suite')
print('...')
print('Done.')
print('After conditional')

Output:
After conditional
if...else Statement
Sometimes, you want to evaluate a condition and take one path if it is true but specify an
alternative path if it is not. This is accomplished with an else clause.

The if-else statement is used to execute both the true part and the false part of a given
condition. If the condition istrue, the if block code is executed and if the condition is false,
the else block code is executed.

The syntax of if...else statement is:

if<expr>:
<statement(s)>
else:
<statement(s)>

The if...else statement evaluates the given condition:

If the condition evaluates to True,


• the code inside if is executed
• the code inside else is skipped
If the condition evaluates to False,
• the code inside else is executed
• the code inside if is skipped
Working of if...else Statement

First, the test expression is checked. If it is true, the statements present in the body of the if
block will execute. Next, the statements present below the if block is executed. In case the
test expression has false results, the statements present in the else body are executed, and then
the statements below the if-else are executed.

The following is an example that better illustrates how if-else works


Python if...elif...else Statement

The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, then we use the
if...elif...else statement.

It checks the if statement condition. If that is false, the elif statement is evaluated. In case the
elif condition is false,
the else statement is evaluated.

The syntax of the if...elif...else statement is:


if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3

In Example below you want different printouts for numbers that are divisible by 2 and
3.Here, since z equals 3, the first condition is False, so it goes over to the next condition. The
next condition does hold True. Hence, the corresponding print statement is executed.

z=3
if z % 2 == 0:
print("z is divisible by 2")
elif z % 3 == 0:
print("z is divisible by 3")
else:
print("z is neither divisible by 2 or 3")

Output:
z is divisible by 3

Working of if...elif Statement


if-elif-else ladder

The most complex of these conditions is the if-elif-else condition. When you run into a
situation where you have several conditions, you can place as many elif conditions as
necessary between the if condition and the else condition.

For branching execution based on several alternatives., use one or more elif (short for else if)
clauses. Python evaluates each <expr> in turn and executes the suite/block corresponding to
the first that is true. If none of the expressions are true, and an else clause is specified, then its
suite/block is executed:

if <expr>:
<statement(s)>
elif<expr>:
<statement(s)>
elif<expr>:
<statement(s)>
...
else:
<statement(s)>

An arbitrary number of elif clauses can be specified. The else clause is optional. If it is
present, there can be only one, and it must be specified last.

Example:

number = 0
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')
Output:
Zero
This statement is always executed

Example:
x=5
if x > 10:
print('x > 10')
elif x > 5:
print('x > 5')
elif x > 0:
print('x > 0')
else:
print('x is not positive number')

Output:
x>0
Nested if statements
We can also use an if statement inside of an if statement. This is known as a nested
if statement.

The syntax of nested if statement is:

if boolean_expression:
if boolean_expression:
statement(s)
else:
statement(s)
else:
statement(s)

Example:
number = 5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')
# inner else statement
else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')

Output: Number is positive


Example:

x = 30
y = 10
if x >= y:
print("x is greater than or equals to y")
if x == y:
print("x is equals to y")
else:
print("x is greater than y")
else:
print("x is less than y")

x is greater than or equals to y


x is greater than y
Conditional Expressions (Python’s Ternary Operator)
It is also referred to as a conditional operator or ternary operator.
The syntax of the conditional expression is as follows:

<expr1>if<conditional_expr>else<expr2>

<conditional_expr> is evaluated first. If it is true, the expression evaluates to <expr1>. If it is


false, the expression evaluates to <expr2>.

Here are these operands:


• <conditional_expr>— a Boolean expression to test for true or false
• <expr1>— the value that will be returned if the condition is evaluated to be true
• <expr2>— the value that will be returned if the condition is evaluated to be false

Note that each operand of the Python ternary operator is an expression, not a statement,
meaning that we can't use assignment statements inside any of them

Examples:
# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)

The ternary operator is a way of writing simple if/else statements in a single line.

number = int(input("Enter a Number: "))


print("Even" if number % 2 == 0 else "Odd")

age = int(input("Enter Age: "))


ticket_price = 100 if age >= 18 else 50

Short-circuiting in Python is a technique by which execution of boolean expression


containing 'or' and 'and' operator in Python is halted as soon as the truth value of the
expression is determined.

Whenever we are evaluating an expression involving OR operator, we can stop checking the
condition as soon as we encounter the first operand that is true.

Even if one of the statements is false, then the result of the AND operation is false. It means
that if even one of the statements turns out to be false, the interpreter can stop examining the
other statements.

a=3
b=5
c=7
print((a<b) and (b<c))
print((a<b) or (b<c))
Loops in Python
A control statement is a statement that determines the control flow of a set of instructions.
A control structure is a set of instructions and the control statements controlling their
execution. Three fundamental forms of control in programming are sequential, selection,
and iterative control.

An iterative control statement is a control statement providing the repeated execution of a set
of instructions. An iterative control structure is a set of instructions and the iterative control
statement(s) controlling their execution. Because of their repeated execution, iterative control
structures are commonly referred to as “loops.”

An iterative control statement is a control statement that allows for the repeated execution
of a set of statements.

In Python we have For Loops& While Loops.

For Loops

The for loop is usually used when the number of iterations is known.

The syntax of a for loop is:


for <var> in <iterable>:
<statement(s)>
• <iterable> is a collection of objects—for example, a list, string or tuple (sequence).
• The <statement(s)> in the loop body are denoted by indentation, and are executed
once for each item in <iterable>.
• The loop variable <var> takes on the value of the next element in <iterable> each
time through the loop.The loop continues until we reach the last item in the sequence.

Iterable is an object which can be looped over or iterated over with the help of a for loop.
Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables.

In Python, a for loop is used to iterate over sequences such as lists, tuples, and string.

Iteration over a String

for x in 'Python':
print(x)

Output:
P
y
t
h
o
n

Iteration over a List

languages = ['Swift', 'Python', 'Go', 'JavaScript']


# run a loop for each item of the list
for language in languages:
print(language)

Output:
Swift
Python
Go
JavaScript

Tuple as an iterable

City= ("Nagpur", "Pune", "Nashik", "Mumbai", "Delhi", "Goa")


for c in City:
print(c)

Output:

Nagpur
Pune
Nashik
Mumbai
Delhi
Goa

Range Function
A range is a series of values between two numeric intervals.We use Python's range() to
define a range of values. For examplerange() function creates a collection of numbers on
the fly i.e. The range() function generates the immutable sequence of numbers.

The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.The numbers are produced
as they are needed rather than all created in advance.

for i in range(6):
print(i)

Output:
0
1
2
3
4
5

We got six integers starting from 0 to 5. If you notice, range() didn’t include 6 in its result
because it generates numbers up to the stop number but never includes the stop number in its
result.

The syntax of the range() function.

range(start, stop[, step])

It takes three arguments. Out of the three, two are optional. The start and step are optional
arguments and the stop is the mandatory argument.

start: (Lower limit) It is the starting position of the sequence. The default value is 0 if not
specified. For example, range(0, 10). Here, start=0 and stop = 10

stop: (Upper limit) generate numbers up to this number, i.e., An integer number specifying at
which position to stop (upper limit). The range() never includes the stop numberin its result

step: Specify the increment value. Each next number in the sequence is generated by adding
the step value to a preceding number. The default value is 1 if not specified. It is nothing but
a difference between each number in the result. For example, range(0, 6, 1). Here, step = 1.

Python range() function generates the immutable sequence of numbers starting from the
given start integer to the stop integer. The range()returns a range object that consists series
of integer numbers, which we can iterate using a for loop.
Range With For Loop

Iteration using range

# Generate numbers between 0 to 5, i.e 0 to stop-1 by default


for i in range(6):
print(i)

Output
0
1
2
3
4
5

Note: As you can see in the output, We got six integers starting from 0 to 5. If you notice,
range() didn’t include 6 in its result because it generates numbers up to the stop number but
never includes the stop number in its result.

range(start, stop[, step])

Range() returns the object of class range.


print(type(range(10)))
# Output <class 'range'>

The range() function generates a sequence of integer numbers as per the argument passed.
The below steps show how to use the range() function in Python.

Pass start and stop values to range()


For example, range(0, 6). Here, start=0 and stop = 6. It will generate integers starting from
the start number to stop -1. i.e., 0, 1, 2, 3, 4, 5

Pass the step value to range()


The step Specify the increment. For example, range(0, 6, 2). Here, step = 2. Result is 0, 2, 4

Use for loop to access each number


Use for loop to iterate and access a sequence of numbers returned by a range().
range(stop)
When you pass only one argument to the range(), it will generate a sequence of integers
starting from 0 to stop -1.

# Print first 10 numbers


# stop = 10
for i in range(10):
print(i, end=' ')

# Output 0 1 2 3 4 5 6 7 8 9

Here, start = 0 and step = 1 as a default value.

If you set the stop as a 0 or some negative value, then the range will return an empty
sequence.

If you want to start the range at 1 use range(1, 10).

range(start, stop)
When you pass two arguments to the range(), it will generate integers starting from the start
number to stop -1.

# Numbers from 10 to 15
# start = 10
# stop = 16
for i in range(10, 16):
print(i, end=' ')

# Output 10 11 12 13 14 15

Here, the step = 1 as a default value.


The range will return an empty sequence if you set the stop value lesser than the start.
range(start, stop, step)
When you pass all three arguments to the range(), it will return a sequence of numbers,
starting from the start number, increments by step number, and stops before a stop number.

Here you can specify a different increment by adding a step parameter.

# Numbers from 10 to 15
# start = 10
# stop = 50
# step = 5
for i in range(10, 50, 5):
print(i, end=' ')

# Output 10 15 20 25 30 35 40 45

The range() function only works with the integers, So all arguments must be integers. You
cannot use float numbers or any other data type as a start, stop, and step value. All three
arguments can be positive or negative.

The step value must not be zero. If a step=0, Python will raise a ValueError exception

Decrementing With range()


for i in range(10, -6, -2):
print(i)
The output of your decrementing loop will look like this:

10
8
6
4
2
0
-2
-4

Ex. Countdown
print("The New Year is upon us!")
for i in range(10, 0, -1):
print(str(i) + '...')
print("Happy New Year!")

Iteration over List


Use a for loop to iterate through that list, printing each name until it reached the end.

our_list = ['Lily', 'Brad', 'Fatima', 'Zining']


for name in our_list:
print(name)
Variable name is loop-variable.Each iteration assigns the loop variable to the next element in
the sequence, and then executes the statements in the body. The statement finishes when the
last element in the sequence is reached.

Running through all the items in a sequence is called traversing the sequence, or traversal.

fruits = ["apple","orange","banana","cherry"]
for afruit in fruits: # by item
print(afruit)

The anatomy of the accumulation pattern includes:


• initializing an “accumulator” variable to an initial value (such as 0 if accumulating a
sum)
• iterating (e.g., traversing the items in a sequence)
• updating the accumulator variable on each iteration (i.e., when processing each item
in the sequence)

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


accum = 0
for w in nums:
accum = accum + w
print(accum)

Iterating tuple using for loop


You can iterate over a tuple using a for loop in Python, it loops over each item in the tuple
and executes the intended code block once for each item.

Example:
# Iterate over tuple using for loop
tuples = ("Python", "Spark", "pandas")
for item in tuples:
print(item)

Output:
Python
Spark
pandas

Example: Sum of elements in a tuple


# Tuple for loop
tuples = (2, 4, 6, 8, 10)
sum = 0
for num in tuples:
sum += num
print(sum)
Iterating Through a Dictionary

d = {'Anita': 9, 'Brajesh': 7.5, 'Ronit': 8.3}


for k in d:
print(k)

Anita
Brajesh
Ronit

As you can see, when a for loop iterates through a dictionary, the loop variable is assigned to
the dictionary’s keys.

To access the dictionary values within the loop, you can make a dictionary reference using
the key as usual:

d = {'Anita': 9, 'Brajesh': 7.5, 'Ronit': 8.3}


for k in d:
print(d[k])

9
7.5
8.3

You can also use a while loop to iterate over the elements of a tuple in python. The while
loop continues to execute as long as the value of the index is less than the length of the tuples.

#Using a while loop


tuples = ("Python", "Spark", "pandas", "Java")
index = 0
while index <len(tuples):
print(tuples[index])
index = index + 1

Output:
Python
Spark
pandas
Java

Exercise

How many times is the letter p printed by the following statements?


s = "python"
for idx in range(len(s)):
print(s[idx % 2])
Python for loop with else, For…Else
A for loop can have an optional else block. The else part is executed when theloop is
exhausted (after the loop iterates through every item of a sequence).

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

Output:
0
1
5
No items left.

Break, Continue and Pass Statements

Break Statement in Python is used to exit from a loop under certain conditions.

The loop continues until the specified element is encountered. As soon as the
'green' element is encountered, the loop breaks.

colours = ['red','green', 'yellow', 'gray']


for x in colours:
if x == 'green':
break
print(x)

Output:
red

Continue Statement
Continue statement is to skip the current iteration of a loop and continuewith the next one.

colours = ['red', 'green', 'yellow', 'gray']


for x in colours:
if x == 'green':
continue
print(x)

Output:
red
yellow
gray

Pass Statement
Pass Statement in Python is used when the user doesn't know which particularcode should be
written.
This is also called a null statement. We usually write comments in the code, though it is
ignored by the interpreter and there is no effect on code.
In Python programming, the pass statement is a null statement which can be used as a
placeholder for future code.
a=40
b=20
if (a<b):
pass
else:
print("b<a")

The pass statement is used as a placeholder for future code. When pass statement is
executed, nothing happens, but you avoid getting an error when empty code is not
allowed. Empty code is not allowed in loops, function definitions, class definitions, or in
if statements.

Nested Loops
A loop inside a loop is known as a nested loop.

A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any
type, such as a while loop or for loop. For example, the outer for loop can contain a while
loop and vice versa.

The outer loop can contain more than one inner loop. There is no limitation on the chaining
of loops.

In the nested loop, the number of iterations will be equal to the number of iterations in the
outer loop multiplied by the iterations in the inner loop.

In each iteration of the outer loop inner loop execute all its iteration. For each iteration of an
outer loop the inner loop re-start and completes its execution before the outer loop can
continue to its next iteration.

Example:
In this example, we are using a for loop inside a for loop. In this example, we are printing a
multiplication table of the first ten numbers.
• The outer for loop uses the range() function to iterate over the first ten numbers
• The inner for loop will execute ten times for each outer number
• In the body of the inner loop, we will print the multiplication of the outer number and
current number
• The inner loop is nothing but a body of an outer loop.

for i in range(1, 11):


# nested loop
# to iterate from 1 to 10
for j in range(1, 11):
# print multiplication
print(i * j, end=' ')
print()
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Nested Loop to print Patterns


The most common use of nested loop is to print various star and number patterns.

row = 7
#outer loop
for i in range(1, row + 1):
#inner loop
for j in range(1, i+1):
print("*", end = " ")
print()

*
**
***
****
*****
******
*******
A while statement is an iterative control statement that repeatedly executes a set of
statements based on a provided Boolean expression (condition).

As long as the condition of a while statement is true, the statements within the loop are
(re)executed. Once the condition becomes false, the iteration terminates and control continues
with the first statement after the while loop.

Flowchart of Python while Loop

A while statement is an iterative control statement that repeatedly executes a set of statements
based on a provided Boolean expression.

An infinite loop is an iterative control structure that never terminates (or eventually
terminates with a system error). Infinite loops are generally the result of programming errors.

A definite loop is a program loop in which the number of times the loop will iterate can be
determined before the loop is executed.

An indefinite loop is a program loop in which the number of times the loop will iterate is not
known before the loop is executed.

A while statement can be used to construct both definite and indefinite loops.

Example:
# program to display numbers from 1 to 5
# initialize the variable
i=1
n=5
while i<= n:
print(i)
i=i+1

Example:sum the digits of a number


n = int(input("Enter a Positive Number: "))
tot = 0
num = n
if n > 0:
while n:
digit=n%10
tot = tot + digit
n = n // 10
print("Sum of digits of {} is {}".format(num,tot))
else:
print("Please Enter Positive Number.")

Example:
Program to calculate the sum of numbersuntil the user enters zero

total = 0
number = int(input('Enter a number: '))
# add numbers until number is zero
while number != 0:
total += number # total = total + number
# take integer input again
number = int(input('Enter a number: '))
print('total =', total)

The break statement is used to terminate the loop immediately when it isencountered.

The continue statement is used to skip the current iteration of the loop and the control flow
of the program goes to the next iteration.
Example: Break Statement
n=5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')

Output:
4
3
Loop ended.

Example: Continue Statement


n=5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('Loop ended.')

Output:
4
3
1
0
Loop ended.

Python While loop with else


In Python, a while loop may have an optional else block.Here, the else part is executed after
the condition of the loop evaluates to False.

Example
counter = 0
while counter < 3:
print('Inside loop')
counter = counter + 1
else:
print('Inside else')

Output:
Inside loop
Inside loop
Inside loop
Inside else
Note: The else block will not execute if the while loop is terminated by a break statement.

counter = 0
while counter < 3:
# loop ends because of break
# the else part is not executed
if counter == 1:
break
print('Inside loop')
counter = counter + 1
else:
print('Inside else')

Output:
Inside loop

Iterate through sequence using while loop

my_lst=['red', 'green', 'yellow', 'blue' ]


i=0
while i < len(my_lst):
print(my_lst[i])
i+=1
print("Out of loop")

t1 = ('Hi', 'Hey', 'Hello', 'Hell')


i=0
while i < len(my_lst):
print(my_lst[i])
i+=1

fruit = "Apple"
j=0
while j < len(fruit):
print(fruit[j])
j= j+1
Nested loops – We can use one type of loop inside another.

Various Types of Nested loops

The while loop statement repeatedly executes a code block while a particular condition is
true. We use a while loop when number iteration is not fixed.
The syntax to write a nested while loop statement in Python is as follows:
while expression:
while expression:
statement(s)
statement(s)

Example:
i=1
while i<=5:
j=1
while j<=i:
print(j, end=" ")
j=j+1
print("")
i=i+1

Output:
1
12
123
1234
12345

You might also like