Unit III
Unit III
x> 0 and x < 10 is true only if x is greater than 0 and less than 10.
Here, the program evaluates the TEST EXPRESSION and will execute
statement(s) only if the text expression is True. If the text expression is
False, the statement(s) is not executed.
Example:
mark = 102
if mark >= 100:
The boolean expression after the if
print(mark, " is not a valid mark.")
statement is called the condition. If
print("This is always printed.")
it is true, then all the indented
Output
statements get executed.
102 is a not a valid mark.
This is always printed.
Alternative execution (if… else)
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax looks like
this:
if TEST EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Example
age=20
if age >= 18:
print("Eligible to vote")
else:
print("Not Eligible to vote")
Output:
Eligible to vote
Chained Conditionals
Sometimes there are more than two possibilities and we need more than two branches. The
syntax looks like this:
if TEST EXPRESSION1:
STATEMENTS_A
elif TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E
print(a);
Logical operators often provide a way to simplify nested conditional
statements. Example: Greatest of three numbers with
nested if
a=10 a=10
b=20 b=20
c=5 c=5
if a>b and a>c: if a>b:
print("Greatest number is ",a) if a>c:
elif b>a and b>c: print("Greatest number is ",a)
print("Greatest number is ",b) else:
else: print("Greatest number is ",c)
print("Greatest number is ",c) else:
if b>c:
print("Greatest number is ",b)
else:
print("Greatest number is ",c)
Output:
Greatest number is 20
Example: check if the number is Example: check if the number is positive
positive or negative or zero or negative or zero with nested if
while TEST_EXPRESSION:
STATEMENTS
Example Example
sequence = {'p', 'a', 's', 's'} def function(args):
for val in sequence: pass
pass
Sum of n numbers Sum of n numbers using for loop:
using while loop: n=int(input("enter n"))
n=int(input(“Enter n")) sum=0
i=1
for i in range(1,n+1,1):
sum=0
while(i<=n): sum=sum+i
sum=sum+i print(sum)
i=i+1
print(sum)
output
Enter n
10
55
Factorial of a numbers: n=5
n=int(input(“Enter n:")) i=1
i=1
fact=1 fact=1
while(i<=n): 1<=5, fact=1*1=1, i=1+1=2
fact=fact*i 2<=5, fact=1*2=2, i=2+1=3
i=i+1
print(fact)
3<=5, fact=2*3=6, i=3+1=4
4<=5, fact=6*4=24, i=4+1=5
output 5<=5, fact= 24*5=120, i=5+1=6
Enter n: 5 6<=5
120
Sum of digits of a number:
n=123
n=int(input(“Enter a number"))
sum=0
sum=0
123>0
while(n>0):
a=123%10=3, sum=0+3=3,n=123//10=12
a=n%10
12>0
sum=sum+a
a=12%10=2, sum=3+2=5, n=12//10=1
n=n//10
1>0
print(sum)
a=1%10=1, sum=5+1=6, n=1//10=0
0>0
Output
Enter a number
123=1+2+3=6
6
Reverse the given number:
n=int(input(“Enter a number"))
sum=0+3=3
sum=0
while(n>0): sum=3*10+2=32
a=n%10 sum=32*10+1=321
sum=sum*10+a
n=n//10
print(sum)
Output
Enter a number
123
321
Palindrome or not Palindrome or not
n=int(input(“Enter a number")) n=int(input(“Enter a number"))
org=n x=str(n)
sum=0 org=n
while(n>0): sum=0
a=n%10 for i in range(len(x)):
sum=sum*10+a a=n%10
n=n//10 sum=sum*10+a
if(sum==org): n=n//10
print("The given no is palindrome") if(sum==org):
else: print("The given no is palindrome")
print("The given no is not palindrome") else:
Output print("The given no is not palindrome")
Enter a number121 Output
The given no is palindrome Enter a number121
The given no is palindrome
Armstrong number or not (only for 3 digits)
n=int(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a**3
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
output
enter a number 153 (13 +53+33 )=153
The given number is Armstrong number
Armstrong number or not(any digit)
n=int(input(“Enter a number"))
x=str(n)
y=len(x)
org=n
sum=0
while(n>0):
a=n%10
sum=sum+pow(a,y)
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
Output
enter a number 54748=55 +45 + 75 +45 +85
The given number is Armstrong number
Program to print fibonacci series.
a=0
Output
b=1
Enter the number of terms: 5
n=int(input("Enter the number of terms: "))
Fibonacci Series:
print("Fibonacci Series: ")
0
print(a,b)
1
for i in range(1,n-1,1):
1
c=a+b
2
print(c)
3
a=b
b=c
Program to check whether the number is a prime number or not
n=int(input("Enter the value of n"))
for i in range(2,n//2+1):
if(n%i==0):
print(“Not Prime”)
break
else:
print("Prime")
Output
Enter the value of n 151
Prime
Fruitful Function
• Fruitful function
• Void function
• Return values
• Parameters
• Local and global scope
• Function composition
• Recursion
Fruitful function:
A function that returns a value is called fruitful function.
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
OUTPUT:
30
Void Function
A function that perform action but don’t return any value.
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Output:
30
Return values:
example:
return( a) – return 1 variable
return (a,b ) – return 2 variables
return (a,b,c ) – return 3 variables
return (a+b) – return expression
return (8) – return value
Calculate area of circle using function:
def cal(r1):
return 3.14*r1*r1
r=int(input("enter r"))
print(cal(r))
OUTPUT:
enter r: 2
ans=
12.56
Find arithmetic operation of given number using function
def cal(a,b):
c=a+b
d=a*b
e=a-b
f=a//b
return (c,d,e,f)
a=int(input("enter a value :"))
b=int(input("enter b value : "))
print("addition , subraction, multiplicaion, division”)
print(cal(a,b))
Output
enter a value :34
enter b value : 23
addition ,subraction,multiplicaion,division of given values= (57, 782, 11, 1)
PARAMETERS / ARGUMENTS:
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with number of
arguments in the function call.
Example:
def student( name, roll ):
print("STUDENT NAME IS ",name)
print("STUDENT ROLL NO IS",roll)
student("George",98)
OUTPUT:
STUDENT NAME IS George
STUDENT ROLL NO IS 98
Keyword Parameters:
Python interpreter is able to use the keywords provided to match the values
with parameters even though if they are arranged in out of order.
Example:
def my_details(name,age):
print(“Name:”, name)
print(“Age:”, age)
return
my_details(age=56,name=“George)
Output
Name: George
Age: 56
Default parameter:
Python allows function parameter to have default values; if the function is called
without the argument, the argument gets its default value in function definition.
Example :
def greet(name, msg="Good morning!"):
print("Hello", name + ', ' + msg)
greet("Kate")
greet("Bruce", "How do you do?")
OUTPUT:
Hello Kate, Good morning!
Hello Bruce, How do you do?
Variable length parameter
• Sometimes, we do not know in advance the number of arguments that will be
passed into a function.
• Python allows us to handle this kind of situation through function calls with
number of arguments.
• In the function definition we use an asterisk (*) before the parameter name to
denote this is variable length of parameter.
Example:
def student(*mark):
print("STUDENT NAME ,STUDENT RGNO, TOTAL, PERCENTAGE:",
mark)
student ("bala",102,450,90)
Output:
STUDENT NAME ,STUDENT REGNO,TOTAL,PERCENTAGE: ('bala', 102, 450, 90)
Local and Global Scope
Global Scope
• The scope of a variable refers to the places that you can see or access a
variable.
• A variable with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the function
Local Scope :
A variable with local scope can be used only within the function
def add():
b=20 Output
print(b) 20
c=a+b 70
print(c) 20
def sub(): 50
b=30 error
c=a-b
print(c)
a=50
add()
sub()
print(a)
print(b)
Function Composition:
• Function Composition is the ability to call one function from within
another function
• It is a way of combining functions such that the result of each function is
passed as the argument of the next function.
• In other words the output of one function is given as the input of another
function is known as function composition.
# Function to add 2 to a number
def add(x):
add(5)
return x + 2 Function call return 7
multiply(add(5)) multiply(7)
# Function to multiply 2 to a number return 14
def multiply(x):
return x * 2
# Printing the result of composition of add and multiply to add 2 to a number and then
multiply by 2
print("Adding 2 to 5 and multiplying the result with 2: ", multiply(add(5)))
Output:
Adding 2 to 5 and multiplying the result with 2: 14
Recursion
A function calling itself till it reaches the base
value - stop point of function call. Example: 5
factorial of a given number using recursion
Factorial of n fact(5)
def fact(n): 5*fact(4)
if(n==1 or n==0): 5*4*fact(3)
return 1
else:
5*4*3*fact(2)
return n*fact(n-1) 5*4*3*2*fact(1)
n=int(input("enter no. to find fact:")) 5*4*3*2*1
f=fact(n)
print("Fact is",f)
Output
enter no. to find fact:5
Fact is 120
5*fact(5-1) 5*fact(5-1)
5*4*fact(4-1) 5*4*fact(4-1)
5*4*3*fact(3-1) 5*4*3*fact(3-1)
5*4*3*2*fact(2-1) 5*4*3*2*fact(2-1)
5*4*3*2*1 5*4*3*2*1
Sum of n numbers using recursion
def sum(n):
if(n==0):
return 0 N=5
else: 5+sum(4)
return n+sum(n-1) 5+4+sum(3)
n=int(input("enter no. to find sum:")) 5+4+3+sum(2)
sum=sum(n) 5+4+3+2+sum(1)
print(sum) 5+4+3+2+1+sum(0)
N=1
Output 1+sum(0)
enter no. to find sum:10 1+0=1
output is 55
# Function to combine two function which it accepts as argument
def composite_function(f, g): Trace Program
return lambda x : f(g(x)) composite_function(multiply, add)
add_(multiply(5))
# Function to add 2 Order of Execution:
def add(x): lambda x : f(g(x))
g(5) =add(5)->return 7
return x + 2 f(7)= multiply(7)->return 14
# Function to multiply 2
def multiply(x): OUTPUT:
14
return x * 2
# Composite function returns a lambda function. Here add_multiply
# will store lambda x : multiply(add(x))
add_multiply = composite_function(multiply, add)
print("Adding 2 to 5 and multiplying the result with 2: ", add_multiply(5))
Strings:
• Strings
• String slices
• Immutability
• String functions and methods
• String module
Strings:
• String is defined as sequence of characters represented in quotation
marks (either single quotes ( ‘ ) or double quotes ( “ ).
• An individual character in a string is accessed using a index.
• The index should always be an integer (positive or negative).
• A index starts from 0 to n-1.
• Strings are immutable i.e. the contents of the string cannot be changed after it
is created.
• Python will get the input at run time by default as a string.
• Python does not support character data type. A string of size 1 can be treated
as characters.
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
Immutability:
• Python strings are “immutable” as they cannot be changed after they are
created.
• Therefore [ ] operator cannot be used on the left side of an assignment.
Example Output
a="python" TypeError: 'str' object does not support item
a[1]="m" assignment
a="python" TypeError: 'str' object doesn't support item deletion
del a[1]
a="python" The string get deleted
del a
string built in functions and methods:
A method is a function that “belongs to” an object.
Syntax to access the method
Stringname.method()
a=”happy birthday”
here, a is the string name.
String modules:
• A module is a file containing Python definitions, functions, statements.
• Standard library of Python is extended as modules.
• To use these modules in a program, programmer needs to import the
module.
• Once we import a module, we can reference or use to any of its functions
or variables in our code.
• There is large number of standard modules also available in python.
• Standard modules can be imported the same way as we import our user-
defined modules.
Syntax:
import module_name
Example
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)
List as array:
Array:
• Array is a collection of similar elements.
• Elements in the array can be accessed by index.
• Index starts with 0.
• Array can be handled in python by module named array.
• To create array have to import array module in the program.
Syntax :
import array
def sqrt(n):
approx=0.5*n
accurate=0.5*(approx+n/approx)
while (accurate!=approx):
approx=accurate
accurate=0.5*(approx+n/approx)
return approx
print("The square root is",sqrt(3))
Output:
enter number to find Sqrt: 9
ILLUSTRATIVE PROGRAMS:
GCD of two numbers
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a % b)
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print(gcd(a, b))
output
Enter the first number54
Enter the second number24
6
ILLUSTRATIVE PROGRAMS:
Exponent of number
base= int(input("Enter base:"))
exp= int(input("Enter exponential value:"))
power=1
for i in range(1, exp+1):
power=power*base
print("power of a number is", power)
Output:
Enter base:6
Enter exponential value:4
Result:1296
ILLUSTRATIVE PROGRAMS:
Sum of array elements:
a=[2,3,4,5,6,7,8]
sum=0
for i in a:
sum=sum+i
print(“The sum is",sum)
output:
The sum is 35
ILLUSTRATIVE PROGRAMS:
Linear search
a=[20,30,40,50,60,70,89] Output
Enter the element to be searched 40
Element is found at position 2
print(a)
search=int(input(“Enter the element to be searched:"))
for i in range(0,len(a),1):
if(search==a[i]):
print(a)
Output
search=int(input(“Enter the element to be searched:"))
Enter the Element to be Search: 30
start=0 Element 30 Found at Position 1
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")