Unit-III Python (1)
Unit-III Python (1)
BOOLEAN VALUES:
Boolean values can be tested for truth value, and used for IF and WHILE condition. There
are two values True and False. 0 is considered as False and all other values considered as True.
Boolean Operations:
3.1 OPERATORS:
Operators are the construct which can manipulate the value of operands.
Eg: 4+5=9
Where 4, 5, 9 are operand
+ is Addition Operator
= is Assignment Operator
Types of Operator:
1. Arithmetic Operator
2. Comparison Operator (or) Relational Operator
3. Assignment Operator
4. Logical Operator
5. Bitwise Operator
6. Membership Operator
7. Identity Operator
1. Arithmetic Operator
It provides some Arithmetic operators which perform some arithmetic operations
Consider the values of a=10, b=20 for the following table.
Operator Meaning Syntax Description
+ Addition a+b It adds and gives the value 30
Example Program:
1.Write a Python Program with all arithmetic operators
>>>num1 = int(input('Enter First number: '))
>>>num2 = int(input('Enter Second number '))
>>>add = num1 + num2
>>>dif = num1 - num2
>>>mul = num1 * num2
>>>div = num1 / num2
>>>modulus = num1 % num2
>>>power = num1 ** num2
>>>floor_div = num1 // num2
>>>print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
>>>print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
>>>print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
>>>print('Division of ',num1 ,'and' ,num2 ,'is :',div)
>>>print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)
>>>print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
>>>print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
Output:
>>>
Enter First number: 10
Enter Second number 20
Sum of 10 and 20 is : 30
Difference of 10 and 20 is : -10
Product of 10 and 20 is : 200
Division of 10 and 20 is : 0.5
Modulus of 10 and 20 is : 10
Exponent of 10 and 20 is : 100000000000000000000
Floor Division of 10 and 20 is : 0
>>>
3. Assignment Operator
Assignment operators are used to hold a value of an evaluated expression and used for
assigning the value of right operand to the left operand.
Consider the values of a=10, b=20 for the following table.
Operator Syntax Meaning Description
= a=b a=b It assigns the value of b to a.
+= a+=b a=a+b It adds the value of a and b and assign it to a.
-= a-=b a=a-b It subtract the value of a and b and assign it to a.
*= a*=b a=a*b It multiplies the value of a and b and assign it to a.
/= a/=b a=a/b It divides the value of a and b and assign it to a.
%= a%=b a=a%b It divides the value of a and b and assign the
remainder to a.
It takes ‘a’ as base value and ‘b’ as its power and
**= a**=b a=a**b
assign the answer to a.
It divides the value of a and b and takes the least
//= a//=b a=a//b
quotient and assign it to a.
4. Logical Operator
Logical Operators are used to combine two or more condition and perform logical
operations using Logical AND, Logical OR, Logical Not.
Consider the values of a=10, b=20 for the following table.
Operator Example Description
AND if(a<b and a!=b) Both Conditions are true
OR if(a<b or a!=b) Anyone of the condition should be true
The condition returns true but not
NOT not (a<b)
operator returns false
5. Bitwise Operator
Bitwise Operator works on bits and performs bit by bit operation.
Consider the values of a=60, b=13 for the following table.
Operator Syntax Example Description
Binary AND It do the and operation
& a&b= 12
between two operations
Binary OR It do the or operation between
| a|b= 61
two operations
Binary Ones It do the not operation
~ ~a=61
Complement between two operations
<< Binary Left Shift <<a It do the left shift operation
>> Binary Right Shift >>a It do the right shift operation
A B A&B A|B ~A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is -61
Line 4 - Value of c is 240
Line 5 - Value of c is 15
6. Membership Operator
Membership Operator test for membership in a sequence such as strings, lists or tuples.
Consider the values of a=10, b=[10,20,30,40,50] for the following table.
Operator Syntax Example Description
value in String or If the value is ‘in’ the list then
in a in b returns True
List or Tuple it returns True, else False
value not in String If the value is ‘not in’ the list
not in a not in b returns False
or List or Tuple then it returns True, else False
Example: Output:
x=’python programming’ False
print(‘program’ not in x) True
print(‘program‘ in x) False
print(‘ Program‘ in x)
7. Identity Operator
Identity Operators compare the memory locations of two objects.
Consider the values of a=10, b=20 for the following table.
Operator Syntax Example Description
If the variable 1 value is pointed
to the same object of variable 2
is variable 1 is variable 2 a is b returns False
value then it returns True, else
False
If the variable 1 value is not
variable 1 is not a is not b returns pointed to the same object of
is not
variable 2 False variable 2 value then it returns
True, else False
Example:
x1=7
y1=7
x2=’welcome’
y2=’Welcome’
print (x1 is y1)
print (x2 is y2)
print(x2 is not y2)
Output:
True
False
True
3.2CONTROL STRUCTURES
Control structures
if expression:
true statements
Flow Chart
Test False
Expressi
on
True
Body of if stmt
Example:
a=10
if a==10:
print(“a is equal to 10”)
Output:
a is equal to 10
2. if else statement
The second form of if statement is “alternative execution” in which there are two possibilities and
the condition determines which block of statement executes.
Syntax
if test_expression:
true statements
else:
false statements
If the testexpression evaluates to true then truestatements are executed else falsestatements are
executed.
Flow Chart
Test
Example: True Expressi False
on
a=10
if a==10:
print(“a is equal to 10”)
Body of if Body of else
else:
print(“a is not equal to 10”)
Output:
End of Code
a is equal to 10
if expression 1:
true statements
elif expression 2:
true statements
elif expression 3:
true statements
else:
false statement
Flow Chart
Test
Expression False
of if
Test
True Expression False
Body of if of elif
True
Body of elif Body of else
End of Code
Example:
a=9
if a==10:
print(“a is equal to 10”)
elif a<10:
print(“a is lesser than 10”)
elif a>10:
print(“a is greater than 10”)
else
print(“a is not equal to 10”)
Output::
a is less than 10
if expression 1:
true statements
else:
if expression 2:
true statements
else:
false statement
Flow Chart
Test
True Condition False
1
Body of if
Test
True Condition False
2
End of Code
Example:
a=10
if a==100:
print(“a is equal to 10”)
else:
if a>100:
print(“a is greater than 100”)
else
print(“a is lesser than 100”)
Output:
a is lesser than 100
3.1.2 Iteration (or) Looping Statement
An Iterative statement allows us to execute a statement or group of statement multiple
times. Repeated execution of a set of statements is called iteration or looping.
Types of Iterative Statement
1. while loop
2. for loop
3. Nested loop
1. while loop
A while loop executes a block of statements again and again until the condition gets false.
The while keyword is followed by test expression and a colon. Following the header is an
indented body.
Syntax
while expression:
true statements
Flow Chart
Entering While
loop
Test
Expression False
True
Body of while
Exit Loop
Example-1:
1.Write a python program to print the first 100 natural numbers
i=1
while (i<=100):
print(i)
i=i+1
Output:
Print numbers from 1 to 100
Example-2:
2. Write a python program to find factorial of n numbers.
n=int(input("Enter the number:"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print("The factorial is",fact)
Output:
Enter the number: 5
The factorial is 120
2. for loop
The for loop is used to iterate a sequence of elements (list, tuple, string) for a specified
number of times.
For loop in python starts with the keyword “for”followed by an arbitrary variable name,which
holds its value in the following sequence objects.
Syntax
for iterating_variable in sequence:
statements
A sequence represents a list or a tuple or a string. The iterating variable takes the first item
in the sequence. Next, the statement block is executed. Each item in the list is assigned to the
iterating variable and the statements will get executed until the last item in the sequence get
assigned.
Flow Chart
Entering for each item in
for loop sequence
Is Last
Item
Reached ?No Yes
Body of for
Exit Loop
Example-1:
for letter in”python”:
print(“The current letter:”, letter)
Output:
The current letter: p
The current letter: y
The current letter: t
The current letter: h
The current letter: o
The current letter: n
Example-2:
>>>fruit=[‘apple’, ‘orange’, ‘mango’]
>>>for f in fruit:
print(“The current fruit”, f)
>>>print(“End of for”)
Output:
The current fruit: apple
The current fruit: orange
The current fruit: mango
End of for
3.Nested loop
Python Programming allows using one loop inside another loop. For example using a
while loop or a for loop inside of another while or for loop.
3.1.3.Unconditional Statement
In a situation the code need to exit a loop completely when an external condition is
triggered or need to skip a part of the loop. In such situation python provide unconditional
statements.
Types of Unconditional looping Statement
1. break statement
2. continue statement
3. pass statement
1.break statement
A break statement terminates the current loop and transfers the execution to statement
immediately following the loop. The break statement is used when some external condition is
triggered.
Syntax
break
Flow Chart
Condition Code
If condition
is true break
Condition
If condition is False
Example:
for letter in”python”:
if letter==’h’:
break
print(letter)
print(“bye”)
Output:
pyt
bye
2. continue statement
A continue statement returns the control to the beginning of the loop statement. The
continue statement rejects all remaining statement and moves back to the top of the loop.
Syntax
continue
Flow Chart
Condition Code
If condition
is true
Condition contin
ue
If condition is False
Example:
for letter in”python”:
if letter==’h’:
continue
print(letter)
print(“bye”)
Output:
pyton
bye
3. pass statement
A pass statement is a null operation, and nothing happens when it executed.
Syntax
pass
Example:
for letter in”python”:
if letter==’h’:
pass
print(letter)
print(“bye”)
Output:
python
bye
len(variable) – which takes input as a string or a list and produce the length of string or a list as an
output.
range(start, stop, step) – which takes an integer as an input and return a list containing all the
numbers as the output.
Example-1:
Write a python program to find distance between two points:
import math
def distance(x1,y1,x2,y2): # Defining the Function Distance
dx=x2-x1
dy=y2-y1
print("The value of dx is", dx)
print("The value of dy is", dy)
d= (dx**2 + dy**2)
dist=math.sqrt(d)
return dist
x1 = float(input("Enter the first Number: ")) #Getting inputs from user
x2 = float(input("Enter the Second Number: "))
y1 = float(input("Enter the third number: "))
y2 = float(input("Enter the forth number: "))
print("The distance between two points are",distance(x1,x2,y1,y2))
#Calling the function distance
Output:
>>> Enter the first Number: 2
Enter the Second Number: 4
Enter the third number: 6
Enter the forth number: 12
The value of dx is 4.0
The value of dy is 8.0
The distance between two points are 8.94427190999916
>>>
Explanation for Example 1:
Function Name – ‘distance()’
Function Definition – def distance(x1, y1, x2, y2)
Formal Parameters - x1, y1, x2, y2
Actual Parameter – dx, dy
Return Keyword – return the output value ‘dist’
Function Calling – distance(x1, y1, x2, y2)
Once the function is defined,it can be called from main program or from another function.
Function call statement syntax
Result=function_name(param1,param2)
Parameter is the input data that is sent from one function to another. The parameters are of two
types
1. Formal parameter
The parameter defined as part of the function definition.
The actual parameter is received by the formal parameter.
2. Actual parameter
The parameter is defined in the function call
Example-1:
def cube(x):
return x*x*x #x is the formal parameter
a=input(“Enter the number=”)
b=cube(a) #a is the actual parameter
print”cube of given number=”,b
Output:
Enter the number=2
Cube of given number=8
3.3 Composition:
A Composition is calling one function from another function definition.
Example:
Write a python program to add three numbers by using function:
def addition(x,y,z): #function 1
add=x+y+z
return add
def get(): #function 2
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
print("The addition is:",addition(a,b,c)) #Composition function calling
get() #function calling
Output:
Enter first number:5
Enter second number:10
Enter third number:15
The addition is: 30
Scope is the portion of the program from where a namespace can be accessed directly
without any prefix. When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in namespace.
>>>a=”I am in world”
>>>outer_function()
>>>print(‘a=’,a)
Output:
a=I am in TamilNadu
a=I am in India
a=I am in World
>>>a=”I am in world”
>>>outer_function()
>>>print(‘a=’,a)
Output:
a=I am in TamilNadu
a=I am in TamilNadu
a=I am in TamilNadu
3.5 Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and
the particular function is called again and again
Syntax:
def function(parameter):
#Body of function
Example-1:
Write a python program to find factorial of a number using Recursion:
def fact(n):
if(n<=1):
return n
else:
return n*fact(n-1)
n=int(input("Enter a number:"))
print("The Factorial is", fact(n))
Output:
>>> Enter a number:5
>>> The Factorial is 120
Explanation:
First Iteration - 5*fact(4)
Second Iteration - 5*4* fact(3)
Third Iteration - 5*4*3*fact(2)
Fourth Iteration - 5*4*3*2* fact(1)
Fifth Iteration - 5*4*3*2*1
Example-2:
Write a python program to find the sum of a ‘n’ natural number using Recursion:
def nat(n):
if(n<=1):
return n
else:
return n+nat(n-1)
>>>n=int(input("Enter a number:"))
>>>print("The Sum is", nat(n))
Output:
>>> Enter a number: 5
The Sum is 15
>>>
Explanation:
First Iteration – 5+nat(4)
Second Iteration – 5+4+nat(3)
Third Iteration – 5+4+3+nat(2)
Fourth Iteration – 5+4+3+2+nat(1)
Fifth Iteration – 5+4+3+2+1
3.6 String:
A string is a combination of characters. A string can be created by enclosing the characters
within single quotes or double quotes. The character can be accessed with the bracket operator.
Example:
var1=’Hello’
var2=”Python Programming”
print(var1) # Prints Hello
print(var2) # Prints Python Programming
Traversal with a for Loop
A lot of computations involve in processing a string, one character at a time. Often they
start at the beginning, select each character in turn, do something to it, and continue until the end.
This pattern of processing is called a traversal.
Example:
>>>index = 0
>>>str="Python"
Unit III Page 3.20
GE3151 - Problem Solving And Python Programming
ILLUSTRATIVE EXAMPLES
Note- Always get an Input from the USER.
1. Program to find the square root using Newton Method.
2. Program to find the GCD of two numbers
3. Program to find the exponential of a number
4. Program to find the sum of n numbers.
5. Program to find the maximum and minimum in a list
6. Program to perform the linear search
7. Program to perform Binary search
Output:
How many terms? 10
Fibonacci sequence upto 10 :
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,
>>>
Output:
>>>
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
>>>
for r in result:
print(r)
Output:
>>>
[12, 4, 3]
[7, 5, 8]
>>>
Output:
>>> [114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
TWO MARKS
1. Define Boolean expression with example.
A boolean expression is an expression that is either true or false. The values true and false
are called Boolean values.
Eg :
>>> 5 == 6
>>> False
True and False are special values that belongs to the type bool; they are not strings.
else:
print 'x is odd'
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no
limit on the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn’t have to be one.
9. Explain while loop with example. Eg:
def countdown(n):
while n > 0:
print n
n = n-1
print 'Blastoff!'
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at the next
statement.
3. If the condition is true, execute the body and then go back to step 1
10. Explain ‘for loop’ with example.
The general form of a for statement is
Syntax:
for variable in sequence:
code block
Eg:
x=4
for i in range(0, x):
print i
11. What is a break statement?
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print'Done!'
Eg:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp) result = area(radius)
return result
14.What is recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
Eg:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)