0% found this document useful (0 votes)
53 views28 pages

While Loop Termination in Python

Uploaded by

NIRANJAN BEHERA
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)
53 views28 pages

While Loop Termination in Python

Uploaded by

NIRANJAN BEHERA
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

ex2:

PYTHON x=input(“enter an alphabet”)


if x in “aeiou”:
print(“vowel”)
UNIT-II else:
print(“consonant”)

syntax of elif:
statements are of 3 types: if(condition):
Statement1
 Sequential statements elif(condition):
 Selection control statements Statement2
else:
 Loop control statements statement3

Selection control statements: ex:


x=int(input("enter a number"))
If statement:
y=int(input("enter a number"))
It can used in 4 ways:
z=int(input("enter a number"))
If statement, if..else, elif and nested if
if(x>y and x>z):
print("%d is big"%x)
*python do not allow {} while writing block of statements, rather we need to follow
elif(y>z):
indenting.
print("%d is big"%y)
else:
Syntax of if:
print("%d is big"%z)
if(condition):
Statement
ex:
Ex:
hungry=True
x=20
if(hungry):
y=10
print("feed me")
if(x>y):
else:
print("%d is big"%x)
print("i am not hungry")
o/p:
o/p
20 is big
feed me
syntax of if..else
ex:
if(condition):
location="bank"
Statement1
if(location=="market"):
else:
print("purchase vegetables")
statement2
else:
ex1:
print("withdraw money")
x=int(input("enter a number"))
y=int(input("enter a number"))
ex:
z=int(input("enter a number"))
list1=["bank","market","office"]
if(x>y and x>z):
for location in list1:
print("%d is big"%x)
if(location=="market"):
else:
print("purchase vegetables")
print("%d is not big"%x)
elif(location=="bank"):
By - Murali Krishna Senapaty
print("withdraw money") ex1:
else: n=int(input(“enter a number”))
print("do work") if(n>=0):
o/p: if(n==0):
withdraw money print(“zero”)
purchase vegetables else:
do work print(“positive number”)
else:
ex: print(“negative number”)
name="sam"
if(name=="sam"):
print("hello sam") ex2:
elif(name=="john"): check for leap year or not?
print("hi john") year=int(input(“enter the year”))
else: if(year%4==0):
print("good morning everybody") if(year%100==0):
if(year%400==0):
* the else is optional in elif statement print(“{0} leap year” .format(year))
else:
Shorthand if: print(“{0} not a leap year” .format(year))
if we have only one statement to execute then we can put it in the same line as: else:
Ex: print(“{0} leap year” .format(year))
a=20;b=10 else:
if(a>b): print("%d is big"%a) print(“{0} not a leap year” .format(year))

short hand if..else:


we can write if..else also in same line as:
ex:find greatest among two numbers
Python Loops:
a=int(input("enter 1st no")) It is having two loop controls.
b=int(input("enter 2nd no")) They are:
print("A") if(a>b) else print("B") 1) While loop
2) For loop
ex: find a>b or a=b or a<b
a=int(input("enter 1st no")) While loop: We can execute a set of statements as long as the condition is true.
b=int(input("enter 2nd no")) Syntax:
print("A") if(a>b) else print("equal") if(a==b) else print("B") while(condition):
statement block
print(“A”) if(a>b and a>c) else print(“B”) if(b>c) else print(“C”) ex1:
i=1
Nested if: while(i<=10):
When we write an if statement inside another if then it is called nested if. print(i)
Syntax: i=i+1
if(condition1):
if(condition2): ex2:
statement block1 i=1
else: while(i<=10):
statement block2 print(i)
i+=2
By - Murali Krishna Senapaty
Exit the loop when i is 3:
ex3: i=1
Generate multiplication table? while i < 6:
i=1 print(i)
n=int(input(“enter a no”)) if i == 3:
while(i<=10): break
print(“%d X %d = %d \n” %(n,i,n*i)) i += 1
i+=1
infinite loops: The continue Statement
if the condition given in while will never become false then it will never terminate. With the continue statement we can stop the current iteration, and continue with
Ex1: the next:
while(1): Example
print(“never ends”) Continue to the next iteration if i is 3:
ex2: i=0
v=2 while i < 6:
while(v!=3): i += 1
i=int(input(“enter a no”)) if i == 3:
print(“the no is %d” %(i)) continue
print(i)
using of else with while loop:
Example: Write a program to test a number is prime or not.
we can write else block for while loop. Here the else block will be program:
executed when the while loop condition becomes false. num = 13
Ex1: if (num > 1):
i=1 i=2
while(i<=500): while(i<=num//2):
print(i) if (num % i == 0):
i=i+1 print(num, "is not a prime number")
else: break
print(“loop ended”) i=i+1
else:
 When a while loop is terminated with break statement then print(num, "is a prime number")
in that instance the else block will not be executed. else:
Ex2: print(num, "is not a prime number")
i=1
while(i<=5): o/p:
print(i) it is a prime number
i=i+1
if(i==3): Example10: Test a number is Armstrong or not ( ex: 153)
break; program:
else: num = int(input("Enter a number: ")) //153
print(“loop ended”) sum = 0
temp = num
#here the else block will not be executed.
while temp > 0:
The break Statement digit = temp % 10
: sum += digit ** 3
Example temp //= 10
By - Murali Krishna Senapaty
else:
if num == sum: print("The number isn't a palindrome!")
print(num,"is an Armstrong number") o/p:
else: enter number: 121
print(num,"is not an Armstrong number") the number is a palindrome

o/p:
Enter a number: 152 Example14 :Test a string is palindrome or not
Answer:
152 is not an Armstrong number string=input("Enter a string:")
if(string==string[::-1]):
Example11: Test a number is strong or not print("The string is a palindrome")
Program: else:
# Python Program to find Strong Number print("Not a palindrome")
Number = int(input(" Please Enter any Number: "))
Sum = 0 Example15 : Find GCD or 2 numbers
Temp = Number Answer:solution1
while(Temp > 0): # Python Program to find GCD of Two Numbers
Factorial = 1
i=1 a = float(input(" Please Enter the First Value a: "))……12
Reminder = Temp % 10 b = float(input(" Please Enter the Second Value b: "))……18
while(i <= Reminder):
Factorial = Factorial * i i=1
i=i+1 while(i <= a and i <= b):
print("\n Factorial of %d = %d" %(Reminder, Factorial)) if(a % i == 0 and b % i == 0):
Sum = Sum + Factorial gcd = i
Temp = Temp // 10 i=i+1

print("\n Sum of Factorials of a Given Number %d = %d" %(Number, print("\n HCF of {0} and {1} = {2}".format(a, b, gcd))
Sum))
solution2:
if (Sum == Number):
print(" %d is a Strong Number" %Number) num1 = float(input(" Please Enter the First Value Num1 : "))
else: num2 = float(input(" Please Enter the Second Value Num2 : "))
print(" %d is not a Strong Number" %Number)
o/p: a = num1
b = num2
Example12 :Test a number is palindrome or not
Program: while(num2 != 0):
n=int(input("Enter number:")) temp = num2
temp=n num2 = num1 % num2
rev=0 num1 = temp
while(n>0):
dig=n%10 gcd = num1
rev=rev*10+dig print("\n HCF of {0} and {1} = {2}".format(a, b, gcd))
n=n//10
if(temp==rev): Example16 : Generate Fibonacci series
print("The number is a palindrome!") Answer:
By - Murali Krishna Senapaty
# Program to display the Fibonacci sequence up to n-th term This is less like the for keyword in other programming languages, and works
nterms = int(input("How many terms? ")) more like an iterator method as found in other object-orientated programming
# first two terms languages.
n1, n2 = 0, 1 With the for loop we can execute a set of statements, once for each item in a list,
count = 0 tuple, set etc.
The syntax of for loop in python is given below.
# check if the number of terms is valid for iterating_var in sequence:
if nterms <= 0: statement(s)
print("Please enter a positive integer")
elif nterms == 1: Example
print("Fibonacci sequence upto",nterms,":") Print each fruit in a fruit list:
print(n1) fruits = ["apple", "banana", "cherry"]
else: for x in fruits:
print("Fibonacci sequence:") print(x)
while count < nterms:
nth = n1 + n2 ex:
print(nth) >>> # Measure some strings:
n1 = n2 ... words = ['cat', 'window', 'defenestrate']
n2 = nth >>> for w in words:
count += 1 ... print(w, len(w))
...
o/p:
How many terms? 7 ex:
Fibonacci sequence: tuple1=(1,2,3)
0 for item in tuple1:
1 print(item)
1
2 ex:
3 mylist1=[(1,2), (3,4), (5,6)]
5 for (a,b) in mylist:
8 print(a)
print(b)
o/p:
Example17: Print reverse of a number 1
Solution: 2
# Python Program to Reverse a Number using While loop 3
Number = int(input("Please Enter any Number: ")) 4
Reverse = 0 5
while(Number > 0): 6
Reminder = Number %10
Reverse = (Reverse *10) + Reminder Ex:
Number = Number //10 mylist1=[(1,2,3), (4,5,6), (7,8,9)]
print("\n Reverse of entered number is = %d" %Reverse) for a,b,c in mylist1:
print(b)
o/p:
Python For Loops 2
A for loop is used for iterating over a sequence 5
(that is either a list, a tuple, a dictionary, a set, or a string). 8
By - Murali Krishna Senapaty
i=1
Ex:
Dict1={‘K1’:100, ‘K2’:200, ‘K3’:300}
For i in dict1:
Print(i) num=int(input(“enter a no”))
o/p: for i in range(1,11):
‘K1’ print(%d X %d = %d”%(num,i,num*i))
‘K2’
‘K3’ o/p:
//here by default the keys will be printed as because in dictionary we iterate only 10X1 = 10
through keys 10X2 = 20
…..
Ex:
Dict1={‘K2’:1, ‘K2’:2, ‘K3’:3} Example4:
For i in dict1.item(): Suppose we have a list and we need to print items of it.
Print(i) mylist1=[1,2,3,4,5]
o/p: for i in mylist1:
(‘K1’,1) print(i)
(‘K2’,2) o/p:
(‘K3’,3) 1
2
Ex: 3
Dict1={‘K1’:1, ‘K2’:2, ‘K3’:3} 4
For key, value in dict1.item(): 5
Print(value)
o/p: Example5:
1 Suppose we have a list and we need to print items of it.
2 mylist1=[1,2,3,4,5]
3 for i in mylist1:
print(“hello”)
Or o/p:
d={‘K1’:1, ‘K2’:2, ‘K3’:3} hello
For x in d.values(): hello
Print(x) hello
o/p: hello
1 hello
2
3 Example6:
Suppose we have a list and we need to print even items of it.
Example2: mylist1=[1,2,3,4,5,6]
for i in range(1, 100): for i in mylist1:
print(i, end= ‘ ‘) If i%2==0:
print(i)
o/p: 1 2 …..99 o/p:
2
Example3: 4
generate multiplication table: 6

By - Murali Krishna Senapaty


Example7: elif num == 0:
Write a program to find sum of items in a list print("The factorial of 0 is 1")
else:
mylist1=[1,2,3,4,5] fact=factorial(num)
sum=0 print(“Factorial value is “,fact)
for i in mylist1:
sum=sum+i Example13 : Test a number is perfect or not
print(sum) # Python Program to find Perfect Number using For loop
Number = int(input(" Please Enter any Number: "))
example8: Sum = 0
to print characters from a string. for i in range(1, Number):
mystring=”hello friends” if(Number % i == 0):
for i in mystring: Sum = Sum + i
print(i ) if (Sum == Number):
o/p: print(" %d is a Perfect Number" %Number)
h else:
e print(" %d is not a Perfect Number" %Number)
l
l for loop with else
o A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts.
f break statement can be used to stop a for loop. In such case, the else part is
r ignored.
i Hence, a for loop's else part runs if no break occurs.
e Ex:
n digits = [0, 1, 5]
d
for i in digits:
Example9: Write a program to find factorial of a given integer. print(i)
Program: else:
num=5 print("No items left.")
factorial = 1
o/p:
# check if the number is negative, positive or zero 0
if num < 0: 1
print("Sorry, factorial does not exist for negative numbers") 5
elif num == 0: No items left.
print("The factorial of 0 is 1")
else: Ex:
for i in range(1,num + 1): Loop through the letters in the word "banana":
factorial = factorial*i for x in "banana":
print("The factorial of",num,"is",factorial) print(x)
o/p:
solution2: b
num=int(input(“enter a no”)) a
# check if the number is negative, positive or zero n
if num < 0: a
print("Sorry, factorial does not exist for negative numbers") n
By - Murali Krishna Senapaty
a for x in range(2, 6):
print(x)
The break Statement The range() function defaults to increment the sequence by 1,
With the break statement we can stop the loop before it has looped through all however it is possible to specify the increment value by adding a
the items: third parameter: range(2, 30, 3):

Example Example3:
Exit the loop when x is "banana", but this time the break comes before the print: Increment the sequence with 3 (default is 1):
fruits = ["apple", "banana", "cherry"] for x in range(2, 30, 3):
for x in fruits: print(x)
if x == "banana": o/p:
break 2
print(x) 5
8
The continue Statement 11
With the continue statement we can stop the current iteration of the loop, and 14
continue with the next: Etc
Example
Do not print banana: Ex4:
fruits = ["apple", "banana", "cherry"] for x in range(100,0,-5):
for x in fruits: print(x)
if x == "banana": o/p:
continue 100
print(x) 95
Etc
The range() Function
Ex5:using the range() for inputting values for a list.
To loop through a set of code a specified number of times, we can use the
List1(range(0,11,1))
range() function,
The range() function returns a sequence of numbers, starting value is 0 by
default, and increments by 1 (by default), and ends at a specified number. Enumerate(): it is used with any iterative control statement
Syntax: to represent the index count.
Range(starting value, last value, change in value) Ex:
word=”hello”
for i in enumerate(word):
Example1 print(i)
Using the range() function: o/p:
for x in range(6): (0,’h’)
print(x) (1, ‘e’)
Etc
Here Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
Zip(): the zip method is used with lists to combine multiple lists
The range() function defaults to 0 as a starting value, together.
however it is possible to specify the starting value by adding a parameter: Ex:
range(2, 6), Mylist1=[1,2,3]
which means values from 2 to 6 (but not including 6): Mylist2=[‘a’,’b’,’c’]
For item in zip(mylist1,mylist2):
Example2: Print(item)
Using the start parameter: o/p:
By - Murali Krishna Senapaty
(1, ‘a’) mylist
(2, ‘b’) o/p:
(3,’c’) [‘w’,’o’,’r’,’d’]

Note: the zip method can combine the lists as per the shortest list. Ex:
mylist=[x for x in range(1,11)]
Else in For Loop mylist
The else keyword in a for loop specifies a block of code to be executed
when the loop is finished: o/p:
Example [1,2,3,4,5,6,7,8,9,10]
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6): Ex: create a list having elements from 1 to n, where n is given as input
print(x) n=int(input(“enter a no”))
else: mylist=[x for x in range(1,n+1)]
print("Finally finished!") mylist

The pass Statement o/p:


for loops cannot be empty, but if you for some reason have a enter a no 8
for loop with no content, put in the pass statement to avoid getting an error. [1,2,3,4,5,6,7,8]
Example
For x in range(1,100,3): Ex:
Pass mylist=[num**2 for num in range(0,5)]
Ex: mylist
for x in [0, 100, 2]:
pass o/p:
[0,1,4,9,16]
use of for statement for creating a list: Ex:
ex: creating a list using string Mylist=[]
mystring=”hello” For x in range(0,11):
mylist=[] If(x%2==0):
for x in mystring: Mylist.append(x)
mylist.append(x) (or)
mylist
mylist=[x for x in range(0,11) if x%2==0]
o/p: mylist
[‘h’,’e’,’l’,’l’,’o’] o/p:
[0,2,4,6,8,10]
Ex2:
mystring=”hello” Ex: find the Fahrenheit for given Celsius from the list.
mylist=[x for x in mystring] Celsius=[0,10,20,34.5]
mylist Fah=[ ((9/5)*t+32) for t in Celsius]
o/p: Fah
[‘h’,’e’,’l’,’l’,’o’] o/p:
[32.0, 50.0, 68.0, 94.1]
#here each element from mystring is copied into mylist.
OR
Ex:
mylist=[x for x in “word”]
By - Murali Krishna Senapaty
Fah=[] red cherry
For t in Celsius: big apple
Fah.append((9/5)*t+32) big banana
big cherry
We can also change the order of use of for statement and etc
if statement inside the list as:
Ex: ex:
Result=[x if x%2==0 else “ODD” for x in range(0,5)] mylist=[]
Result for x in [2,4,6]:
for y in [100, 200, 300]:
o/p: mylist.append(x*y)
[0,”ODD”,2,”ODD”,4] mylist
o/p:
Nested for loop in python [200, 400, 600, 400, 800, 1200, 600, 1200, 1800]
Python allows us to nest any number of for loops inside a for loop.
The inner loop is executed n number of times for every iteration of Ex:
the outer loop. The syntax of the nested for loop in python is given below. Print the words in a sentence
St=”print only the words that start with s in this sentence”
for iterating_var1 in sequence: St.split()
for iterating_var2 in sequence: o/p:
#block of statements ‘print’
#Other statements ‘only’
‘the’
Example 1: generate a shape of triangle using *. ‘words’
n = int(input("Enter the number of rows you want to print?")) ‘that’
i,j=0,0 ‘start’
for i in range(0,n): ‘with’
print() ‘s’
for j in range(0,i+1): ‘in’
print("*",end="") ‘this’
Output: ‘sentence’
Enter the number of rows you want to print?5
* Ex:to print the words that starts with s are:
** St=”print only the words that start with s in this sentence”
*** For word in st.split():
**** If word[0]==’s’ or word[0]==’S’:
***** Print(word)
o/p:
Example start
Print each adjective for every fruit: s
adj = ["red", "big", "tasty"] sentence
fruits = ["apple", "banana", "cherry"]
for x in adj: ex: print all the words that have even number of characters from a
for y in fruits: sentence:
print(x, y) St=”print only the words that start with s in this sentence”
o/p: For word in st.split():
red apple If len(word)%2==0:
red banana Print(word+”is even”)
By - Murali Krishna Senapaty
o/p: return(c)
only is even
that is even z=add(10,20)
with is even q=add(‘a’,’b’)
in is even
this is even def greet(name):
sentence is even print(“hello”,name)

ex:generate shape: function calling statement:


a a function must be defined before calling it. Else python will give error.
aba Syntax:
abcba Function name(parameters)
abcdcba
#here ord() used to find ASCII value and chr() to find equivalent character. Ex1:
char ch=’a’ fun()
n=int(input(“how many lines”)) Ex2:
for i in range(1,n+1): Add(10,20)
for sp in range(n,1,-1): Ex3:
print(“ “) Greet(“sam”)
for j in range(1,2*i,1):
if(j<i): #A function can be called by another function or from the python prompt.
print(ch) Return statement:
ch=chr(ord(ch)+1) Return statement is used to come out of function and
else: return back to the place where it was called.
print(ch) Syntax:
ch=chr(ord(ch)-1) Return <expression list>

python functions: Ex1:


return x
A function can be defined as an organised clock which contains reusable codes.
Functions enables modularity and clarity to understand the program. when there is no return value then the return statement
is not necessary. In that case the function returns None object.
How to create a function:
def keyword is used. Ex1:
Syntax: Print(greet(“sam”))
def function name (parameters): o/p:
Statements in body hello sam
return(expression) None

Here parameters are the arguments to be passed and they are optional. Ex2: a function to find absolute value.
return statement is optional. It is used to return a value. def absvalue(num):
The body statements are to be written with indenting. if num>=0:
Ex1: return num
else:
def fun(): return (-num)
print(“hello python”)
print(absvalue(-2))
def add(a,b): o/p:
c=a+b 2
By - Murali Krishna Senapaty
Scope and life time of variable: ex4:
c1=1
The variables can be local and global. def add():
Local variables: c=c+2
The local variables defined inside a function is not visible outside. print(c)
Hence they are having local scope. add()
The life time is also local. o/p:
error
Global variables:
A variable written outside having a global scope. ex5:
We can read these variables inside a function but we cannot change. c1=1
To get accessibility to change we need to use keyword global. def add():
Ex1: global c
def myfun(): c=c+2
X=10 print(c)
print(“values inside “,x) add()
print(c)
X=20 o/p:
myfun() 3
print(“value outside”,x) 3

o/p: Types of functions:


value inside 10 1) Built in functions
value outside 20 2) User defined functions

ex2: Built in functions are the library functions which we are using
def fun(): such as: abs(), max(), min() etc.
global x
print(x) User defined functions are defined by programmer.
x=”hi” Parameters: Using these we pass input data to a function.
print(x) The parameters are actual parameters and formal parameters.
The actual parameters are the variables we represent in a function
x=”hello” calling statement.
fun() The formal parameters are the variables which
print(x) we represent in the function body definition. These variables receive
the input for the function.
o/p: In a function we can write any number of parameters separated by comma.
hello Ex1:
hi WAp to perform multiplication of 2 numbers.
hi def product(a,b): #here a and b are formal parameters
return (a*b)
ex3: x=int(input(“enter 1st no”))
c1=1 y=int(input(“enter 2nd no”))
def add(): print(“the product is “,product(x,y)) # here a and y are actual parameters
print(c) o/p:
add() enter 1st no 10
o/p: 1 enter 2nd no 20
By - Murali Krishna Senapaty
product is 200 ````````````````````````````````````````````
call by reference: In python we can define a function which can take variable no. of arguments.
================== They are 4 types:
in python all the functions are called by reference, 1) required arguments
i.e: all the changes made to the reference variable 2) default arguments
inside the function reverts back to the original variable 3) keyword arguments
outside. 4) arbitrary arguments
Note: the changes made to the immutable objects will not
reflect outside the function.
Required arguments or positional
++++++++++++++++++++++++++++++++++++++
Mutable vs Immutable Objects in Python
++++++++++++++++++++++++++++++++++++++
arguments:
‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’
The mutable objects can change their state or contents It is the general way of writing the function and calling the function. Here the
and immutable objects can’t change their state or content. arguments are required at the time of function call. If they are not provided
properly during calling statement then it leads to error.
Immutable Objects : These are of in-built types Ex:
like int, float, bool, string, unicode, tuple def fun(name):
msg=”hello ”+name
Mutable Objects : These are of type list, dict, set return msg
name=input(“enter your name”)
print(fun(name))
Ex1: using mutable object :list o/p:
def update(list1): enter your name alok
list1.append(22) hello alok
list1.append(33)
print(“inside”,list1) questions:
list1=[10,30,40,50] 1) Write a program to find greatest among 3 numbers.
update(list1) 2) Write a program to find sum of 10 numbers given.
print(“outside”,list1) 3) Write a program to find LCM, GCD of 2 numbers.
o/p:
inside 10,30,40,50,20,30
outside 10,30,40,50,20,30
default arguments:
the function arguments can have default values in python. We can provide a
default value to an argument by using assignment operator =
Ex:using immutable object :string
def upstr(str1):
Ex:
str1=str1+”how are you”
def greet(name, msg=”good morning”):
print(“inside”,str1)
print(“hello”,name+msg)
str1=”hi”
greet(“kate”)
upstr(str1)
greet(“bruce”,”how are you”)
print(“outside”,str)
o/p:
o/p:
hello kate good morning
inside hi how are you
hello bruce how are you
outside hi
note:
variable function arguments:
By - Murali Krishna Senapaty
Example
 when a parameter having a default value then during function call it is
optional to input for the parameter.
 when we provide a value then it sill over write the default Value.
 In a function any no. of parameters can have default value. But they need def myfun(*args):
to be written as per right side as possible. return sum(args*5)
myfun(40,60,100)
It means if we write: o/p:
def greet(msg=”good morning”,name): 1000
print(“hello”,msg+name)
o/p:
error myfun(40,60,100, 1,34)
o/p:
python allows to change the position of the arguments.
Ex1: greet(name=”bruce”,msg=”hello”)
Ex2: greet(msg=”hello”, name=”bruce”)
Example
Introduction to *args and **kwargs in myfun(*args):
print(args)
Python myfun(40,60,100,1,34)
In Python, we can pass a variable number of arguments to a o/p:
function using special symbols. There are two special symbols: 40,60,100,1,34
1. *args (Arbitrary Arguments)
2. **kwargs (Keyword Arguments) Example
def my_function(*kids):
Python *args print("The youngest child is " + kids[2])

Arbitrary Arguments, *args my_function("Emil", "Tobias", "Linus")


If you do not know how many arguments that will be passed
into your function, add a * before the parameter name in the Example
function definition. It is also known as variable length
arguments. def greet( *names):
for n in names:
print(“hello”,n)
This way the function will receive a tuple of arguments,
and can access the items accordingly: greet(“monika”, “ludo”, “john”, “kate”)

Note: generally used *args.


Example
Here *args is just a conventional name taken. The name can
be anything preceded by * such as *names, *data etc
By - Murali Krishna Senapaty
def adder(*num):
sum = 0
Python **kwargs
for n in num:
sum = sum + n Arbitrary Keyword Arguments, **kwargs
print("Sum:",sum)
Python passes variable length non keyword argument to
adder(3,5) function using *args but we cannot use this to pass keyword
adder(4,5,6,7) argument or dictionary items.
adder(1,2,3,5,6)
If you do not know how many keyword arguments that will be
passed into your function, add two asterisk: ** before the
Example parameter name in the function definition.

This way the function will receive a dictionary of arguments,


def myFun(*argv): and can access the items accordingly:
for arg in argv:
print (arg)
Example
myFun('Hello', 'Welcome', 'to', 'HOME')
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Example
# Python program to illustrate Example
# *args with first extra argument
def myFun(arg1, *argv):
print ("First argument :", arg1) # Python program to illustrate
for arg in argv: # *kwargs for variable number of keyword arguments
print("Next argument through *argv :", arg)
def myFun(**kwargs):
myFun('Hello', 'Welcome', 'to', 'Home') for key, value in kwargs.items():
print ("%s == %s" %(key, value))
o/p:
First argument : Hello # Driver code
myFun(first ='welcome', mid ='to', last='class')
Next argument through *argv : Welcome
o/p:
Next argument through *argv : to last == welcome
Next argument through *argv : Home
By - Murali Krishna Senapaty
mid == to myfunc(fruit=”apple”, vegi=”potato”, food=”rice”)
o/p:
first == class { ‘fruit’:’apple’, ‘vegi’:’potato’, ‘food’:’rice’}

Example
# Python program to illustrate **kwargs for
Example
# variable number of keyword arguments with def myfunc(*args, **kwargs):
# one extra argument. print(args)
print(kwargs)
def myFun(arg1, **kwargs): myfunc(10,20,30, fruit=’orange’, food=’eggs’, animal=’dog’)
for key, value in kwargs.items(): o/p:
print ("%s == %s" %(key, value)) (10,20,30)
{ ‘fruit’:’orange’, ‘food’: ‘eggs’, ‘animal’:’dog’}
# Driver code
myFun("Hi", first ='murali', mid ='for',last='krishna') Example
Output: def myfunc(*args, **kwargs):
last == krishna print(“I like {} {}”.format(args[0], kwargs[‘food’]))
myfunc(10,20,30, fruit=’apples’, food=’eggs’, dryfruit=’dates’)
mid == for o/p:
I like 10 eggs
first == murali

Example Exercises:
1) Write a program to create an UDF which tests a number is prime or not.
def myfun(**kwargs): 2) Write a program to generate Fibonacci series using UDF
if “fruit” in kwargs: 3) Write a program to store 10 no.s into a list. Find largest and smallest
print(“my fruit of choice is element present using UDF.
{}”.format(kwargs[‘fruit’]))
else:
print(“I did not find any fruit”) Python recursion:
myfun(fruit=”apple”)
When a function calls itself then the process is called recursion.
myfun(fruit=”apple”, veggie=”lettuce”)
o/p: advantages:
my fruit of choice is apple. 1) It makes the code look clean
my fruit of choice is apple. 2) Complex program can be broken into simple sub programs

Example 3) Sequence generation is easier with recursion.


Drawbacks:
def myfunc(**kwargs): 1) Logic behind the recursion is hard to follow
print(kwargs)
2) Recursion requires more memory and time
By - Murali Krishna Senapaty
3) Recursive function is hard to debug. fib(b,c,n-1)
x=-1
y=1
Ex1:Find the factorial of x
n=int(input(“enter a no”))
def fact(x):
fib(x,y,n)
if x==1:
return 1
else:
return(x*fact(x-1)) Lambda function or Anonymous Function:
num=5 An anonymous function is a function that is defined without a
print(“factorial value is “,fact(num))
name. While normal functions are defined using the def keyword
o/p: in Python,
factorial value is 120
anonymous functions are defined using the lambda keyword.
Ex2: find sum of natural no.s using recursion. Hence, anonymous functions are also called lambda functions.
def sum(n):
if (n==1):
return 1 So, a lambda function is also known as anonymous function.
else:
return n+sum(n-1) A lambda function can take any number of arguments, but can
only have one expression.
n=int(input(“enter a positive no”))
print(“sum of series is”,sum(n))

o/p: Syntax
ex3: find GCD of 2 no.s using recursion. lambda arguments : expression
def gcd(x.y):
if x>y:
small=y Example
else:
small=x Add 10 to argument a, and return the result:
for i in range(1,small+1):
if((x%i==0) and (y%i==0)): x = lambda a : a + 10
gcd=i
print(x(5))
return gcd

num1=int(input(“enter 1st no”)) Note:


num2=int(input(“enter 2nd no”)) here x is of class function type.
h=gcd(num1,num2) a is the argument variable and a+10 is the expression.
print(“gcd is”,h) We need to send the argument to the lambda function x as:
e.g: x(5)
Ex4: generate Fibonacci series using recursion.
def fib(a,b,n):
if(n>0):
c=a+b
print(c)
Example
By - Murali Krishna Senapaty
Multiply argument a with argument b and return the result: def myfunc(n):
return lambda a : a * n
x = lambda a, b : a * b
print(x(5, 6)) mydoubler = myfunc(2)
mytripler = myfunc(3)

Summarize argument a, b, and c and return the result: print(mydoubler(11))


print(mytripler(11))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2)) Practice questions:
1) Write a function that returns the smaller of 2 given nos : if both numbers
are even, but returns larger: if one or both numbers are odd.
The power of lambda is better shown when you use Solution:
them as an anonymous function inside another def two_even (a,b):
function. if a%2==0 and b%2==0:
if(a<b):
result=a
Example:lambda with UDF else:
result=b
def myfunc(n):
else:
return lambda a : a * n if(a>b):
mydoubler = myfunc(2) result=a
else:
print(mydoubler(11)) result=b
o/p: return result
22 data1=two_even(10,20)
print(data1)
Example data2=two_even(21,11)
print(data2)
def myfunc(n):
OR
return lambda a : a * n
def fun1(a,b):
mytripler = myfunc(3) if a%2==0 and b%2==0:
r=min(a,b)
print(mytripler(11)) else:
r=max(a,b)
return r
data2=two_even(21,11)
print(data2)
the same function definition to make both functions, in the
same program: 2) Write a program using UDF that takes two strings and returns TRUE if both
words are begins with same letters.

Example Solution:
def compare(text):
By - Murali Krishna Senapaty
wordlist=text.split() check(20,5)
print(wordlist) o/p:
first=wordlist[0] False
second=wordlist[1] True
return (first[0]==second[0]) True

4) Write a function that capitalize the 1st and 4th letters of a name.
compare(“Hello Friend”) Solution:
o/p:
def funcap(name):
[‘Hello’, ‘Friend’]
False firstletter=name[0]
inbetween=name[1:3]
Compare(“Hello Hina”) fourthletter=name[3]
o/p: rest=name[4:]
[‘Hello’, ‘Hina’] return
True firstletter.upper()+inbetween+fourthletter.upper()+rest
OR funcap(“oldmcdonald”)
def compare(text): o/p:
wordlist=text.split() OldMcdonald

return (wordlist[0][0]==wordlist[1][0]) Or
compare(“Hello Hina”)
def funcap(name):
o/p: Firstpart=name[:3]
[‘Hello’, ‘Hina’] Secondpart=name[3:]
True
return
Note: Here the sentence’s each word is stored in to a list called wordlist and then firstpart.capitalize()+secondpart.capitalize()
we can refer to each word with index i.e: word index & character index. Funcap(“oldmcdonald”)
We can store all words in lower case or in upper case as: Note : Capitalize() :it makes capital for 1st letter.
o/p:
wordlist=text.lower().split() OldMcdonald
Or
wordlist=text.upper().split()
Ex:To capitalize each word in a sentence:
3) Write a program to create a function which returns True if sum of 2 numbers is def cap(sentence):
20, or any of two numbers is 20 wordlist=sentence.split()
Solution: for word in wordlist:
def check(n1, n2): word.capitalize()
return (((n1+n2)==20) or (n1==20 or n2==20)) print(wordlist)
check(10,5) cap(“hello friends, how are you”)
check(18,2)
By - Murali Krishna Senapaty
o/p: o/p:
Hello Friends, How Are You a+b+c

Use of join(): Example:


Join all items in a tuple into a string, using a hash character ‘ ‘.join(mylist)
as separator o/p:
Syntax: abc
string.join(iterable)
Example:
example: ‘’.join(mylist)
list1=[“hello”, “friends”, “how”, “is”, “life”] o/p:
str1=“#”.join(list1) abc
print(str1)
o/p: Example:
hello#friends#how#is#life text = ['Python', 'is', 'a', 'fun', 'programming', 'language']

# join elements of text with space


The join() method takes all items in an iterable and joins print(' '.join(text))
them into one string. Any iterable object where all the
returned values are strings. Ex: To display the reverse order of all the words in a sentence is:

A string must be specified as the separator. Solution:


def myfun(sentence):
wordlist=sentence.split()
revwordlist=wordlist[::-1]
Example: return ‘ ‘.join(revwordlist)
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple) Myfun(“I am at home”)
print(x) o/p:
Here “#” is the separator or delimiter given between words. home at am I

ex4:
Given a list of integers. Return True if the array contains 3 next to a 3 value
Example: somewhere.
myDict = {"name": "John", "country": "Norway"} For example
mySeparator = "TEST" check(1,3,3,1) = TRUE
x = mySeparator.join(myDict) check(1,3,1,3) = FALSE
print(x) Program:
def check(numberlist):
Example: for i in range(0, len(numberlist)-1):
mylist=[‘a’,’b’,’c’] if numberlist[i]==3 and
‘+’.join(mylist)
By - Murali Krishna Senapaty
numberlist[i+1]==3: 1) Return the sum of numbers from a list, but when the sequence is in
return True between 6 to 9 then ignore that portion for adding.
Ex: list1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
return False 2) Write a program that takes a list of integers and return TRUE if it contains
007 in order.
check([1,3,3]) Ex: check(1,2,0,0,4,7,6,0,0,7]
o/p: true
o/p: Ex: check(1,2,0,0,4,7,6,0,7,0]
True o/p: false
3) Write a program to input a paragraph and find how many palindromes
OR exist in it.

def check(numlist): map():


for i in range(0,len(numlist)-1):
if numlist[i:i+2]==[3,3] It is meant for mapping a function to a list of objects.
return True The map() function executes a specified function for each item in an
else: iterable. The item is sent to the function as a parameter.
return False
check([1,3,3])
o/p:
Syntax
True
map(function, iterables)
Ex5:
Paper doll Problem: here iterables is a sequence, collection or an iterator object.
Suppose given string “hello”, then print “hhheeellllllooo” ex1:without map()
Print each character 3 times. def sqr(num):
return num**2
Program:
list1=[1,2,3,4,5]
def paperdoll(text,n):
for x in list1:
result=''
print(sqr(x))
for ch in text:
result+=ch*n ex2: using map() the above example:
return result def sqr(num):
return num**2
x=input("enter string: ") list1=[1,2,3,4,5]
n=int(input("no of times: ")) for x in map(sqr,list1):
paperdoll(x,n) print(x)
o/p:
o/p:
enter string: arupa 1
no of times: 5 4
'aaaaarrrrruuuuupppppaaaaa' 9
Assignment Problems:
16
By - Murali Krishna Senapaty
25 revlist=list(map(lambda x:x[::-1],
wordlist))
OR print(revlist)
x=input("enter :")
def sqr(num): find(x)
return num**2
list1=[1,2,3,4,5] o/p:
x=list(map(sqr,list1)) enter :hello friends how are you i am fine
print(x) ['olleh', 'sdneirf', 'woh', 'era', 'uoy', 'i', 'ma', 'enif']

Ex3:
Enter a sentence and print only that words who have even number of characters.
def find(x):
if(len(x)%2==0): filter():
print(x) The filter() function returns an iterator were the items are
filtered through a function to test if the item is accepted or
str1=input("enter sentence") not.
list1=str1.split() The filter() function extracts elements from an iterable (list,
result=list(map(find,list1)) tuple etc.) for which a function returns True .

map() using lambda function: Syntax:


filter(function, iterable)
given example:
def sqr(x): Example
return x**2 ages = [5, 12, 17, 18, 24, 32]
sqr(5) def myFunc(x):
if x < 18:
this example we can write as: return False
sqr= lambda x: x**2 else:
sqr(5) return True
suppose give list adults = filter(myFunc, ages)
list1=[1,2,3,4,5] for x in adults:
list(map(sqr,list1)) print(x)

or Example
list(map(lambda x: x**2,list1)) list1=[1,2,3,4,5,6]
list(filter(lambda x: x%2==0,list1))
Example o/p:
def find(sentence): [2,4,6]
wordlist=sentence.split()
Example
By - Murali Krishna Senapaty
def find(x): print(“Hi”+name)
return(len(x)%2==0)
str1=input("enter:") To import this module or file in another program we can do in two ways:
list1=str1.split() 1) Using import statement
result=list(filter(find,list1)) 2) Using from -import statement
print(result)
Using import:
o/p: Ex:
enter:good morning import file1
['good'] name=input(“enter ur name”)
file1.msg(name)

#we can call any function of module file1 with reference to the module name.
Example
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] Using From – import:
Instead of accessing the whole file if we need to access only some functions then
# a function that returns True if letter is vowel we can use from import.
def filter_vowels(letter): Ex:
vowels = ['a', 'e', 'i', 'o', 'u'] from file1 import msg
return True if letter in vowels else False name=input(“enter ur name”)
msg(name)
filtered_vowels = filter(filter_vowels, letters)
ex2:
# converting to tuple create a module func.py
vowels = tuple(filtered_vowels) def add(x,y):
print(vowels) return x+y
def sub(x,y):
Example return x-y
def mul(x,y):
numbers = [1, 2, 3, 4, 5, 6, 7] return x*y

# the lambda function returns True for even numbers 2nd program: p1.py
even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers) from func import add
print(add(10,20))
# converting to list
even_numbers = list(even_numbers_iterator) to rename a module:
print(even_numbers) python provides flexibility to import a module with another name or alias name.
syntax:
import <module name> as <alternate name>
Python modules: ex:
import calculate as calc
A module can be defined as a python program file which contains python code a=int(input(“enter 1st no”))
that includes functions, classes, variables etc. This file will have extension .py b=int(input(“enter 2nd no”))
print(“sum=”, calc.sum(a,b))
Ex: create a python module file1.py
---------------------------------------------- o/p:
def msg(name): enter 1st no 5
By - Murali Krishna Senapaty
enter 2nd no 10
sum=15 In python we can treat these folders as packages and the .py files as modules
inside package.
python module search: To treat a directory as package, we need to create and store a file
while importing a module python search for it in the _ _init_ _.py inside of it. This file can be an empty file.
1) Current directory.
2) In the directory specified in PYTHONPATH environment variable. Ex: create main directory game as package. It contains sub directories sound,
It is available at: image, levels as sub packages. We need to add _ _init_ _.py in each folder.
This PC, properties, advanced system setting, Environment variables,
3) Default directory of installation. To import a module as can write with dot operator as:
import game.level.start
Where start.py is the module.
If start.py contains a function difficulty.py() then we can access as:
Reloading a module: game.level.start.difficulty(2)
if we need to access the module func.py by again updating some more features
and functions, then to import we need the help of reload function, as import is not otherwise we can import in another way as:
applicable for 2nd time. from game.level import start
For it we need to write: start.difficulty(2)
import importlib
importlib.reload(func)
Built-in Functions:
Global Variables across Python modules: The Python built-in functions are defined as the functions whose functionality is
We can create a module to hold global variables. pre-defined in Python.
Ex:
Create config.py file and store: dir() :
a=0 we can use this built in function to see all the names that are defined inside a
b=”empty” module in sorted manner.
Ex:
create update.py file and change global variable data: >>>dir(mod1)
import config Where mod1.py is the module exist.
config.a=10
config.b=”alphabets” abs() :
The python abs() function is used to return the absolute value of a number. It
now create main.py file and test: takes only one argument, a number whose absolute value is to be returned.
import config
import update # integer number
print(config.a) integer = -20
print(config.b) print('Absolute value of -40 is:', abs(integer))

when we run main.py file the output will be: # floating number
10 floating = -20.83
Alphabets print('Absolute value of -40.83 is:', abs(floating))
Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83

Python package:
When we develop project we write any files and stores in different folders and sub all() :
folders and then access them.
By - Murali Krishna Senapaty
This function accepts an iterable object (such as list, dictionary, etc.). It returns If no parameter is passed, then by default it returns False.
true if all items in passed iterable are true. Otherwise, it returns False. If the So, passing a parameter is optional.
iterable object is empty, the all() function returns True.
Example It can return one of the two values.
It returns True if the parameter or value passed is True.
# all values true It returns False if the parameter or value passed is False.
k = [1, 3, 4, 6] Here are few cases, in which Python’s bool() method returns false. Except these all other
print(all(k)) values return True.
Output:  If a False value is passed.
True
 If None is passed.
# all values false  If an empty sequence is passed, such as (), [], ”, etc
k = [0, False]  If Zero is passed in any numeric type, such as 0, 0.0 etc
print(all(k))  If an empty mapping is passed, such as {}.
Output:  If Objects of Classes having __bool__() or __len()__ method,
False returning 0 or False
# Python program to illustrate
# built-in method bool()
# one false value
k = [1, 3, 7, 0] # Returns False as x is False
print(all(k)) x = False
Output: print(bool(x))
False o/p:
false
# one true value
k = [0, False, 5] # Returns True as x is True
x = True
print(all(k)) print(bool(x))
Output: o/p:
False True

# empty iterable # Returns False as x is not equal to y


k = [] x= 5
y = 10
print(all(k)) print(bool(x==y))
Output: o/p:
True false

bin() : # Returns False as x is None


function is used to return the binary representation of a specified integer. A result x = None
print(bool(x))
always starts with the prefix 0b.
o/p:
Python bin() Function Example
false
x = 10
y = bin(x) # Returns False as x is an empty sequence
print (y) x = ()
Output: print(bool(x))
0b1010 o/p:
false
bool(): method is used to return or convert a value to a Boolean value i.e., True or False,
using the standard truth testing procedure.
Syntax: # Returns False as x is 0
bool([x]) x = 0.0
print(bool(x))
The bool() method in general takes only one parameter(here x) o/p:

By - Murali Krishna Senapaty


false x=8
print(eval('x + 1'))
# Returns True as x is a non empty string
Output:
x = 'hello friends'
9
print(bool(x))
o/p:
true Ex2:
>>> x=10
>>> y='A'
>>> eval('x+ord(y)')
sum(): o/p:
This function is used to get the sum of numbers of an iterable, i.e., list. 75
Example
s = sum([1, 2,4 ]) iter() :
print(s) this function is used to return an iterator object.
It creates an object which can be iterated one element at a time.
s = sum([1, 2, 4], 10)
print(s) Example
Output: # list of numbers
7
17 list = [1,2,3,4,5]

listIter = iter(list)
any() :
function returns true if any item in an iterable is true. Otherwise, it returns False.
# prints '1'
print(next(listIter))
Example
L = [4, 3, 2, 0]
# prints '2'
print(any(L))
print(next(listIter))
o/p:
true
# prints '3'
L = [0, False]
print(next(listIter))
print(any(L))
o/p:
# prints '4'
false
print(next(listIter))
L = [0, False, 5]
# prints '5'
print(any(L))
print(next(listIter))
o/p:
Output:
True 1
2
L = [] 3
print(any(L)) 4
5
o/p:
false
next() :
Python eval() Function This function is used to fetch next item from the collection. It takes two
arguments, i.e., an iterator and a default value, and returns an element.
The python eval() function parses the expression passed to it and runs python
This method calls on iterator and throws an error if no item is present. To avoid
expression(code) within the program.
the error, we can set a default value.
Python next() Function Example
Ex1:
By - Murali Krishna Senapaty
number = iter([256, 32, 82]) # Creating iterator (5, 1)
# Calling function
item = next(number) hex() :
# Displaying result This function is used to generate hex value of an integer argument. It takes an
print(item) integer argument and returns an integer converted into a hexadecimal string.
# second item Ex1:
item = next(number) >>> hex(15)
print(item) o/p:
'0xf'
len() : Ex2:
function is used to return the length (the number of items) of an object. >>> hex(14)
Python len() Function Example o/p:
strA = 'Python' '0xe'
print(len(strA))
Output: sorted() :
6
This function is used to sort elements. By default, it sorts elements in an
ascending order but can be sorted in descending also. It takes four arguments
chr() : and returns a collection in sorted order. In the case of a dictionary, it sorts only
function is used to get a string representing a character which points to a Unicode keys, not values.
code integer. For example, chr(97) returns the string 'a'.
ex: Example
>>>chr(65) >>> str="javatpoint"
o/p: >>> sorted(str)
‘A’ o/p:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
ord():
This function returns ascii value for a character. oct() :
Ex: This function is used to get an octal value of an integer number. This method
>>>ord(‘A’) takes an argument and returns an integer converted into an octal string. It throws
o/p: an error TypeError, if argument type is other than an integer.
65 Python oct() function Example
# Calling function
complex() : val = oct(10)
This function is used to convert numbers or string into a complex number. This # Displaying result
method takes two optional parameters and returns a complex number. The first print("Octal value of 10:",val)
parameter is called a real and second as imaginary parts. Output:
Ex: Octal value of 10: 0o12
>>> complex(1,2)
o/p:
(1+2j) pow() :
This function is used to compute the power of a number. It returns x to the power
divmod() : of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e.
This function is used to get remainder and quotient of two numbers. This function (x, y) % z.
takes two numeric arguments and returns a tuple. Both arguments are required Python pow() function Example
and numeric. # positive x, positive y (x**y)
Ex: print(pow(4, 2))
>>> divmod(21,4)
o/p: # negative x, positive y
By - Murali Krishna Senapaty
print(pow(-4, 2)) print(type(Dict))
Output:
<class 'list'>
<class 'dict'>
reversed() :
This function returns the reversed iterator of the given sequence.
Python reversed() function Example
# for string
String = 'Java'
print(list(reversed(String)))

# for tuple
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))

# for range
Range = range(8, 12)
print(list(reversed(Range)))

# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))
Output:
['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]

round() :
This function rounds off the digits of a number and returns the floating point
number.

Example
# for floating point
print(round(10.8))

# even choice
print(round(6.2))
Output:
11
6

type() :
It returns the type of the specified object if a single argument is passed to the
type() built in function.
Example
List = [4, 5]
print(type(List))

dict = {4: 'four', 5: 'five'}


By - Murali Krishna Senapaty

You might also like