0% found this document useful (0 votes)
13 views

Chapter 1

Python

Uploaded by

archanasarangi5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter 1

Python

Uploaded by

archanasarangi5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter-3

 Conditional Statements
if Statement
Sometimes the programmer needs to check the evaluation of
certain expression(s), whether the expression(s) evaluate to
True or False. If the expression evaluates to False, then the
program execution follows a different path then it would have if
the expression had evaluated to True.
Based on this, the conditional statements are further
classified into following types; if, if……else, elif, nested
if.

if Statement:

A simple if statement works on following principle,

 execute the block of code inside if statement if the


expression evaluates True.
 ignore the block of code inside if statement if the
expression evaluates False and return to the code
outside if statement.
Example:

applePrice = 180
budget = 200
if (applePrice <= budget):
print("Alexa, add 1kg Apples to the cart.")
Output:

Alexa, add 1kg Apples to the cart.

if-else Statement
An if……else statement works on the following principle,

 execute the block of code inside if statement if the


expression evaluates True. After execution return to the
code out of the if……else block.
 execute the block of code inside else statement if the
expression evaluates False. After execution return to the
code out of the if……else block.
Example:

applePrice = 210
budget = 200
if (applePrice <= budget):
print("Alexa, add 1kg Apples to the cart.")
else:
print("Alexa, do not add Apples to the cart.")

Copy
Output:
Alexa, do not add Apples to the cart.

elif Statement
Sometimes, the programmer may want to evaluate more than
one condition, this can be done using an elif statement.

An elif statement works on the following principle,

 execute the block of code inside if statement if the


initial expression evaluates to True. After execution
return to the code out of the if block.
 execute the block of code inside the first elif statement
if the expression inside it evaluates True. After execution
return to the code out of the if block.
 execute the block of code inside the second elif
statement if the expression inside it evaluates True.
After execution return to the code out of the if block.
.
.
.
 execute the block of code inside the nth elif statement if
the expression inside it evaluates True. After execution
return to the code out of the if block.
 execute the block of code inside else statement if none
of the expression evaluates to True. After execution
return to the code out of the if block.
Example:

num = 0
if (num < 0):
print("Number is negative.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is positive.")
Number vNested if Statement
We can use if, if….else, elif statements inside other if
statements.

Example:

num = 18
if (num < 0):
print("Number is negative.")
elif (num > 0):
if (num <= 10):
print("Number is between 1-10")
elif (num > 10 and num <= 20):
print("Number is between 11-20")
else:
print("Number is greater than 20")
else:
print("Number is zero")

Copy
Output:Number is zero

Number is between 11-20Python for Loop


Sometimes a programmer wants to execute a group of
statements a certain number of times. This can be done using
loops. Based on this loops are further classified into following
types; for loop, while loop, nested loops.

for Loop

for loops can iterate over a sequence of iterable objects in


python. Iterating over a sequence is nothing but iterating over
strings, lists, tuples, sets and dictionaries.

Example: iterating over a string:


name = 'Abhishek'
for i in name:
print(i, end=", ")

Copy
Output:

A, b, h, i, s, h, e, k,

Copy

Example: iterating over a tuple:

colors = ("Red", "Green", "Blue", "Yellow")


for x in colors:
print(x)

Copy
Output:

Red
Green
Blue
Yellow

Copy

Similarly, we can use loops for lists, sets and dictionaries.


What if we do not want to iterate over a sequence? What
if we want to use for loop for a specific number of times?
Here, we can use the range() function.
Example:

for k in range(5):
print(k)

Copy
Output:

0
1
2
3
4

Copy
Here, we can see that the loop starts from 0 by default and
increments at each iteration.

But we can also loop over a specific range.


Example:

for k in range(4,9):
print(k)

Copy
Output:

4
5
6
7

8Python while Loop


As the name suggests, while loops execute statements while
the condition is True. As soon as the condition becomes False,
the interpreter comes out of the while loop.
Example:

count = 5
while (count > 0):
print(count)
count = count - 1

Copy
Output:

5
4
3
2
1
Copy
Here, the count variable is set to 5 which decrements after each
iteration. Depending upon the while loop condition, we need to
either increment or decrement the counter variable (the
variable count, in our case) or the loop will continue forever.

We can even use the else statement with the while loop.
Essentially what the else statement does is that as soon as the
while loop condition becomes False, the interpreter comes out
of the while loop and the else statement is executed.
Example:

x = 5
while (x > 0):
print(x)
x = x - 1
else:
print('counter is 0')

Copy
Output:

5
4
3
2
1

counter is 0Nested Loops


We can use loops inside other loops, such types of loops are
called as nested loops.

Example: nesting for loop in while loop

while (i<=3):
for k in range(1, 4):
print(i, "*", k, "=", (i*k))
i = i + 1
print()

Copy
Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

Copy

Example: nesting while loop in for loop

for i in range(1, 4):


k = 1
while (k<=3):
print(i, "*", k, "=", (i*k))
k = k + 1
print()

Copy
Output:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

3 * 1 = 3
3 * 2 = 6

3 * 3 = 9Break Statement
The break statement in Python brings control out of the loop.
Example: In this Python code, it iterates through the characters of
the string ‘geeksforgeeks’. When it encounters the
characters ‘e’ or ‘s’, it uses the break statement to exit the loop.
After the loop is terminated, it prints “Current Letter :” followed
by the last character encountered in the loop (either ‘e’ or ‘s’). So,
the output will display “Current Letter :” followed by the first
occurrence of ‘e’ or ‘s’ in the string.
 Python3

for letter in 'geeksforgeeks':

if letter == 'e' or letter == 's':

break

print('Current Letter :', letter)

Output
Current Letter : e
Pass Statement
We use pass statement in Python to write empty loops. Pass is also
used for empty control statements, functions and classes.
Example: This Python code iterates through the characters of the
string ‘geeksforgeeks’ using a ‘for' loop. However, it doesn’t
perform any specific action within the loop, and
the ‘pass' statement is used. After the loop, it prints “Last
Letter :” followed by the last character in the string, which is ‘s’.
 Python3

for letter in 'geeksforgeeks':

pass

print('Last Letter :', letter)

Output
Last Letter : s
How for loop in Python works internally?
Before proceeding to this section, you should have a prior
understanding of Python Iterators.
Firstly, lets see how a simple for loop looks like.
Example: This Python code iterates through a list called fruits,
containing “apple”, “orange” and “kiwi.” It prints each fruit
name on a separate line, displaying them in the order they appear
in the list.
 Python3

fruits = ["apple", "orange", "kiwi"]

for fruit in fruits:

print(fruit)

Output
apple
orange
kiwi
Here we can see the for loops iterates over iterable object fruit
which is a list. Lists, sets, dictionaries are few iterable objects while
an integer object is not an iterable object. For loops can iterate
over any of these iterable objects.
This Python code manually iterates through a list of fruits using an
iterator. It prints each fruit’s name one by one and stops when
there are no more items in the list.
 Python3

fruits = ["apple", "orange", "kiwi"]

iter_obj = iter(fruits)

while True:

try:

fruit = next(iter_obj)

print(fruit)

except StopIteration:

break

You might also like