0% found this document useful (0 votes)
16 views7 pages

Class 03

The document provides a comprehensive overview of Python programming concepts, focusing on iterators, loops, and functional programming techniques such as lambda, map, filter, and reduce functions. It includes examples of conditional statements, loops, and functions, along with practical applications like checking even/odd numbers, age restrictions, and discount calculations. Additionally, it covers pattern printing and augmented operators for concise coding.

Uploaded by

ahmedfaraz1102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views7 pages

Class 03

The document provides a comprehensive overview of Python programming concepts, focusing on iterators, loops, and functional programming techniques such as lambda, map, filter, and reduce functions. It includes examples of conditional statements, loops, and functions, along with practical applications like checking even/odd numbers, age restrictions, and discount calculations. Additionally, it covers pattern printing and augmented operators for concise coding.

Uploaded by

ahmedfaraz1102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

11/03/2025, 09:47 Class03.

ipynb - Colab

keyboard_arrow_down Class 03
1. iterators and loops

2. lambda, map , filter and reduce functions

keyboard_arrow_down Write a program to check value in variable x is even or odd

x = 25677777
if x%2 == 0:
print(x,"is a even number")
else:
print(x,"is a odd number")

keyboard_arrow_down Write a program to accept age of visitor and allows him to PM's party only if he is above 60 years or below 18 years of age

x = int(input("Enter your age:"))


if x <= 18 or x >= 60:
print("Welcome to PM's party")
else:
print("Sorry! you do not fit in PM's party age criteria")

Enter your age: 80


Welcome to PM's party

keyboard_arrow_down Write a program which offers various discounts on purchase bills

# constructing multiple if statements


shopping_total = int(input("Enter the total bill amount"))
if shopping_total > 5000:
print("You have won a discount voucher of 1000 on your next purchase")
elif shopping_total >= 2500:
print("You have won a discount voucher of 500 on your next purchase")
elif shopping_total >= 1000:
print("You have won a discount voucher of 100 on your next purchase")
else:
print("OOPS! there is no discount!")

Enter the total bill amount 7500


You have won a discount voucher of 1000 on your next purchase

## if , else , elif, def, for, while if end with a : and indentation (tab space) in the next line

keyboard_arrow_down Write a program to accepts three numbers from user and print the largest of three numbers

world_cups = {2019:['England','New Zealand'], 2015:['Australia','New Zealand'], 2011:['India','Sri Lanka'],2007:['Australia'

year = int(input("Enter the year to check if India made it to the finals"))

if year in world_cups:
if "India" in world_cups[year]:
print("India made it to the finals")
else:
print("India could not make it to finals")
else:
print("World cup wasn't played in the year ", year)

Enter the year to check if India made it to the finals 2011


India made it to the finals

Iteration

# iterate over list of integers

l = [1,3,5,7,9,10]
for i in l:
print(i)

https://colab.research.google.com/drive/15zXJpdAwXdPo2r34zRCnKgG0GTJtly1e#printMode=true 1/7
11/03/2025, 09:47 Class03.ipynb - Colab
1
3
5
7
9
10

# iterate over a string


string = "HIMACHAL PRADESH"
for ch in string:
print(ch) # by defaut it will take new line

H
I
M
A
C
H
A
L

P
R
A
D
E
S
H

# iterate over a string - modify print using end


string = "HIMACHAL PRADESH"
for ch in string:
print(ch, end = ":")

H:I:M:A:C:H:A:L: :P:R:A:D:E:S:H:

# iterating over a dictionary

student_data = {1:['Sam',24], 2:['Sharma',21],3:['Seema',23],4:['Saif',20],5:['Varun',25]}


for key,val in student_data.items():
print(key,val)

1 ['Sam', 24]
2 ['Sharma', 21]
3 ['Seema', 23]
4 ['Saif', 20]
5 ['Varun', 25]

# iterate over keys of a dictionary


for key in student_data.keys():
print(key)

1
2
3
4
5

# Generate range of values.


range(1,101)

range(1, 101)

# Iterate over range of values


for i in range(1,101):
print(i,end=',')

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,

# different variations in range


# gives numbers from 1 to 100 with a step count of 2
range(1,101,2)

range(1, 101, 2)

for i in range(1,101,2):
print(i,end=',')

1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83

https://colab.research.google.com/drive/15zXJpdAwXdPo2r34zRCnKgG0GTJtly1e#printMode=true 2/7
11/03/2025, 09:47 Class03.ipynb - Colab
# gives a reversed sequence of numbers from 100 to 1
for i in range(100,0,-2):
print(i,end=',')

100,98,96,94,92,90,88,86,84,82,80,78,76,74,72,70,68,66,64,62,60,58,56,54,52,50,48,46,44,42,40,38,36,34,32,30,28,26,24,22

ch = ""
while ch != 'quit':
ch = input()
print(ch)

Sam
Sam
Rita
Rita
jshdkjh
jshdkjh
quit
quit

while True:
ch = input()
if ch == 'quit':
break
print(ch)

x
x
y
y
v
v
quit

# not divisible by 5
x = 0
while x <= 50:
x +=3 # augumented oprator x = x+3
if x % 5 == 0:
continue # if x is divisible by 5 it will skip the and continue
print(x, end = ' ')

3 6 9 12 18 21 24 27 33 36 39 42 48 51

l1 = ['Honda','Maruti','Benz','Morris Carriage','Automobiles']
l2 = []
for i in l1:
l2.append(len(i))
l2

[5, 6, 4, 15, 11]

l1 = ['Honda','Maruti','Benz','Morris Carriage','Automobiles']
l2 = [len(i) for i in l1]
print(l2)

[5, 6, 4, 15, 11]

keyboard_arrow_down Loops and iterators


are essential for performing repetitive tasks, processing collections of data, and iterating over sequences in Python.

They enable efficient and concise handling of data,allowing developers to write expressive and readable code.

Loops are control structures in programming


that execute a block of code repeatedly until a certain condition is met.

Python supports two main types of loops: for loop and while loop.

a. for loop:
It iterates over a sequence (such as a list, tuple, string, or range) or any iterable object.

b. while loop:

It repeats a block of code as long as a specified condition evaluates to True.

https://colab.research.google.com/drive/15zXJpdAwXdPo2r34zRCnKgG0GTJtly1e#printMode=true 3/7
11/03/2025, 09:47 Class03.ipynb - Colab
for i,j in zip(l1,l2):
print(i,"-",j)

Honda - 5
Maruti - 6
Benz - 4
Morris Carriage - 15
Automobiles - 11

l1 = ['Honda','Maruti','Benz','Morris Carriage','Automobiles']
d = {i:len(i) for i in l1}
print(d)

{'Honda': 5, 'Maruti': 6, 'Benz': 4, 'Morris Carriage': 15, 'Automobiles': 11}

#### Write a program which takes a word as input from user and returns vowels from the word

word = input("Enter the word")


vowels = {i for i in word if i in "aeiouAEIOU"}
print(vowels)

Enter the word Aeroplane


{'e', 'A', 'o', 'a'}

keyboard_arrow_down Augmented Operators:

shorthand notations that combine arithmetic and assignment operations.

They provide a more concise way to modify variables by performing an operation on the variable's current value and assigning the result back
to the variable.

instead of writing: x = x + 5 You can use the += operator: x += 5

# Define functions
#Write a function which takes a value as a parameter and returns its factorial
# factorial numbers 5! = 5X4X3X2X1

def factorial(n):
fact = 1
for i in range(1,n+1):
fact *= i # augumented operator
return fact

print(factorial(5))

120

print(factorial(9))

362880

def func(name, age=22):


print("Name:",name)
print("Age:",age)

func("Jane",20)

Name: Jane
Age: 20

def func(name, age=22, city="Mumbai"):


print("Name:",name)
print("Age:",age)
print('city:',city)

func("Jane",city='Bangalore')

Name: Jane
Age: 22
city: Bangalore

def var_func(*args):
print(args)

var_func(1,3,'abc')

(1, 3, 'abc')

https://colab.research.google.com/drive/15zXJpdAwXdPo2r34zRCnKgG0GTJtly1e#printMode=true 4/7
11/03/2025, 09:47 Class03.ipynb - Colab

keyboard_arrow_down map() and lambda functions are built-in functions and features of Python itself

Lambda functions:
You've written your very own Python functions using the def keyword, function headers, docstrings and function bodies.

There is a quicker way to write functions on the fly and they are called lambda function because you use the keyword lambda.

To do so, after the keyword lambda, we specify the names of the arguments; then we use a colon followed by the expression that specifies
what we wish the function to return.

Lambda functions allow you to write functions in a quick and potentially unscientific but there are situations when they can come in very
handy.

Lambda functions, also known as anonymous functions, are small, inline functions that can have any number of parameters but can only
have one expression.

They are often used when a simple function is needed for a short period of time, such as within higher-order functions like map(), filter(), and
reduce().

# Lambda functions
# Write a lambda funtion to check a number is even or odd
f = lambda x:"even" if x%2 == 0 else "odd"
f(15)

'odd'

#Write a lambda function to perform addition of two numbers


p = lambda x,y : x+y
p(3,5)

keyboard_arrow_down Map Function:

Here map function has two arguments and it applies this defined function to all elements in the sequence.

This func can be a list, we can pass lambda functions to map without even naming them and such situations we refer them as anonymous
function.

Syntax: map(func, iterable)

# map
#map the list to obtain the names of countries in upper case
countries = ['India','Japan','Italy','France']
list(map(lambda x:x.upper(), countries))

['INDIA', 'JAPAN', 'ITALY', 'FRANCE']

keyboard_arrow_down filter() Function:


The filter() function is used to filter elements from an iterable (such as a list) based on a specified condition.

It returns an iterator containing the elements for which the function returns true.

Syntax: filter(function, iterable)

#filter the countries names starting with "I"


list(filter(lambda x:x.startswith("I"),countries))

['India', 'Italy']

keyboard_arrow_down reduce() Function:

The reduce() function is used to apply a rolling computation to sequential pairs of elements in an iterable. It repeatedly applies a function to
the elements, reducing them to a single value.

Syntax: reduce(function, iterable[, initializer])

from functools import reduce


# reduce the list to concatante the countries names into a single string variable seperated by " "
reduce(lambda x,y:x+ " "+y, countries)

https://colab.research.google.com/drive/15zXJpdAwXdPo2r34zRCnKgG0GTJtly1e#printMode=true 5/7
11/03/2025, 09:47 Class03.ipynb - Colab
'India Japan Italy France'

#Some more examples on map - filter - reduce


q = reduce(lambda x,y:x**y, range(2,6))
print(q)

1152921504606846976

L1 = [2,4,5]
print(list(map(lambda x:x**2,L1)))

[4, 16, 25]

#Defining a function and using it in map


L1 = [2,4,5]
def squareit(n):
return n**2

print(list(map(squareit,L1)))

[4, 16, 25]

# Filter function to return the multiples of 3

my_list = [3,4,5,6,7,8,9]
divby3 = lambda x: x%3 == 0
div = filter(divby3,my_list)
print(list(div))

[3, 6, 9]

# Write a python program to count the students above 18

student_data = {1:['Sam',10], 2:['Sharma',16],3:['Seema',23],4:['Saif',20],5:['Varun',25]}


list(filter(lambda x:x[1] > 18, student_data.values()))

[['Seema', 23], ['Saif', 20], ['Varun', 25]]

# pattern printing
# Pyramid Pattern printing
n = 5
for i in range(1,(n+1)): # for in range 1 to n

print(' '*(n-i) + '*' * (2*i-1))

*
***
*****
*******
*********

# Right angle triangle pattern

n = 5
for i in range(1, n + 1):
print('*' * i)

*
**
***
****
*****

#inverted triangle
n = 5
for i in range(n, 0, -1):
print('*' * i)

*****
****
***
**
*

# Number pyramid
n = 5

https://colab.research.google.com/drive/15zXJpdAwXdPo2r34zRCnKgG0GTJtly1e#printMode=true 6/7
11/03/2025, 09:47 Class03.ipynb - Colab
for i in range(1,n+1):
print(" "*(n-i) + ' '.join(str(x) for x in range(1,i+1)))

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

# Diamond Shape
n = 5
# Upper Part
for i in range(1,n+1):
print(' '*(n-i) + '*' *(2*i-1))
# Lower Part
for i in range(n-1,0,-1):
print(' '*(n-i)+'*'*(2*i-1))

*
***
*****
*******
*********
*******
*****
***
*

# Alphabet triangle
n = 5
for i in range(1,n+1):
print(' '*(n-i)+' '.join(chr(65 +j) for j in range(i)))

A
A B
A B C
A B C D
A B C D E

# Floyd's triangle
# Floyd’s Triangle is a right-angled triangular number pattern introduced by Robert W. Floyd, an American computer scientist

n = 5
num = 1
for i in range (1,n+1):
for j in range(1, i+1):
print(num , end=' ')
num += 1
print()

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Start coding or generate with AI.

https://colab.research.google.com/drive/15zXJpdAwXdPo2r34zRCnKgG0GTJtly1e#printMode=true 7/7

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy