Python Unit 3
Python Unit 3
Boolean Operators are those that result in the Boolean values of True and
False. These include and, or and not. While and & or require 2 operands, not is
a unary operator. Boolean operators are most commonly used in arithmetic
computations and logical comparisons.
BOOLEAN OPERATOR
Types of Boolean Operators in Python
There are two types of operators in Python that return boolean values, i.e.,
Logical operators and Comparison operators.
Since both these operators have return types as boolean, they are also
termed, Boolean operators.
1. Comparison operators
2. Logical Operators
The logical operators and, or and not are also referred to as Boolean
operators. and and or require 2 operands and are thus called binary
operators. On the other hand, not is a unary operator which works on one
operand.
Case 1:
Condition 1: Mom is back.
Condition 2: She doesn’t permit me to leave.
Result: I will not come to the party.
Case 2:
Condition 1: Mom is back.
Condition 2: She permits me to leave.
Result: I will come to the party.
Example:
x=5
y = 10
z = 11
print((x > y) and (y > z))
print((x > y) and (y < z))
print((x < y) and (y > z))
print((x < y) and (y < z))
Output:
False
False
False
True
The statement implies that I will rest if both conditions are satisfied and not if
none of them is.
Thus, let’s consider 2 example cases and the results based on the or operator.
Case 1:
Condition 1: Mohan disconnects the call sooner
Condition 2: There is no extra class
Result: I will rest.
Case 2:
Condition 1: Mohan does not disconnect the call sooner
Condition 2: There is no extra class.
Result: I will not rest.
Example:
x=5
y = 10
z = 11
print((x > y) or (y > z))
print((x > y) or (y < z))
print((x < y) or (y > z))
print((x < y) or (y < z))
Output:
False
True
True
True
not It is a unary operator that is used to negate the expression after
succeeding the operator. According to this, every True expression
becomes False, and vice versa.
Example:
x = True
y = False
print(not x)
print(not y)
Output:
False
True
X Y X and Y
X Y X or Y
X not X
True False
False True
CONDITIONALS
Conditional if
Alternative if… else
Chained if…elif…else
Nested if….else
Conditional (if):
syntax:
if(condition 1):
Statement 1
Flowchart:
Example:
purchase=purchase-500
print(“amount to pay”,purchase)
output
amount
2500
amount to pay
2000
if(c==”S”):
m=m+5
print(“mark is”,m)
output
mark is 90
alternative (if-else)
In the alternative the condition must be true or false. In this else statement
can be combined with if statement. The else statement contains the block of
code that executes when the condition is false. If the condition is true
statements inside the if get executed otherwise else part gets executed. The
alternatives are called branches, because they are branches in the flow of
execution.
syntax:
Flowchart:
Examples:
n=eval(input("enter a number"))
if(n%2==0):
print("even number")
else:
print("odd number")
Output
enter a number4
even number
n=eval(input("enter a number"))
if(n>=0):
print("positive number")
else:
print("negative number")
Output
enter a number8
positive number
y=eval(input("enter a yaer"))
if(y%4==0):
print("leap year")
else:
Output
enter a yaer2000
leap year
b=eval(input("enter b value:"))
if(a>b):
print("greatest:",a)
else:
print("greatest:",b)
Output
enter a value:4
enter b value:7
greatest: 7
age=eval(input("enter ur age:"))
if(age>=18):
else:
Output
enter ur age:78
Chained conditionals(if-elif-else)
If the condition1 is False, it checks the condition2 of the elif block. If all
the conditions are False, then the else part is executed.
Among the several if...elif...else part, only one part is executed according
to the condition.
• The if block can have only one else block. But it can have multiple elif blocks.
syntax:
Flowchart:
Example:
mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Output
enter ur mark:78
grade:B
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
Output
GO
x=eval(input("enter x value:"))
y=eval(input("enter y value:"))
if(x == y):
else:
enter x value:5
enter y value:7
x is less than y
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
c=eval(input("enter c value:"))
d=(b*b-4*a*c)
if(d==0):
elif(d>0):
else:
print("imaginagry roots")
output
enter a value:1
enter b value:0
enter c value:0
Nested conditionals
If both the conditions are true statement1 get executed otherwise statement2
get execute.
Syntax:
Flowchart:
Exampe:
if(a>b):
if(a>c):
else:
if(b>c):
else:
output
the greatest no is 9
if(n==0):
else:
if(n>0):
output
ITERATION/CONTROL STATEMENTS:
state
while
for
break
continue
pass
State:
While loop:
While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true.
In while loop, test expression is checked first. The body of the loop
isentered only if the test_expression is True. After one iteration, the test
expression is checked again. This process continues until the test_expression
evaluates to False.
Syntax:
Flowchart
Examples:
Sum of n numbers:
n=eval(input("enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)
output
enter n
10
55
Factorial of a numbers:
n=eval(input("enter n"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(fact)
output
enter n
120
n=eval(input("enter a number"))
sum=0
while(n>0):
a=n%10
sum=sum+a
n=n//10
print(sum)
output
enter a number
123
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
print(sum)
output
enter a number
123
321
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
else:
Armstrong number")
output
enter a number153
Palindrome or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
output
enter a number121
For loop:
for in range:
v
We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
v
In range function have to define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not provided.
Syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.
n=eval(input("enter a"))
for i in range(1,n,1):
print(i)
output
enter a:30
15
25
Fibonacci series
a=0
b=1
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
output
Fibonacci Series:
01
n=eval(input("enter a number:"))
for i in range(1,n+1,1):
if(n%i==0):
print(i)
Output
enter a number:10
10
n=eval(input("enter a number"))
for i in range(2,n):
if(n%i==0):
break
else:
output
enter a no:7
n=eval(input("enter a number:"))
sum=0
for i in range(1,n,1):
if(n%i==0):
sum=sum+i
if(sum==n):
else:
Output
enter a number:6
numbers to be displayed:"))
count=1
n=2
while(count<=number):
for i in range(2,n):
if(n%i==0):
break
else:
print(n)
count=count+1
n=n+1
Output
displayed:5
5
7
11
if n > 1:
for i in range(2,n):
if (n % i) == 0:
break
else:
print(n)
output:
53
59
61
67
71
73
79
83
89
97
----------------------------------------------------------------------------------------------------------
BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of
the loop completely.
Syntax:
Break
Flowchart
example
for i in "welcome":
if(i=="c"):
break
print(i)
Output
CONTINUE
It terminates the current iteration and transfer the control to the next
iteration in the loop.
Syntax:
Continue
Flowchart
Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
PASS
It is used when a statement is required syntactically but you don’t want any
code to execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pass
break
Example
for i in “welcome”:
if (i == “c”):
pass
print(i)
Output
Fruitful function
Void function
Return values
Parameters
Function composition
Recursion
Fruitful function:
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the function.
example:
PARAMETERS / ARGUMENTS:
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
The number of parameter in the function definition should match exactly with
number of arguments in the function call.
Example
print(name,roll)
student(“George”,98)
Output:
George 98
Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword
parameter, the order of the arguments can be changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")
Output:
90 102 bala
Default parameter:
Example
student( “kumar”):
student( “ajay”):
Output:
Kumar 17
Ajay 17
In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.
Example
print(name,mark)
student (“bala”,102,90)
Output:
Global Scope
The scope of a variable refers to the places that you can see or access a
variable.
Local Scope
A variable with local scope can be used only within the function .
Function Composition:
In other words the output of one function is given as the input of another
function is known as function composition.
Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Output:
900
def sum(a,b):
sum=a+b
return sum
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
output
enter a:4
enter b:8
Recursion
A function calling itself till it reaches the base value - stop point of function
call. Example: factorial of a given number using recursion
Factorial of n
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
fact:"))
fact=fact(n)
print("Fact is",fact)
Output
Fact is 120
Explanation
Examples:
def sum(n):
if(n==1):
return 1
else:
return n*sum(n-1)
sum:"))
sum=sum(n)
print("Fact is",sum)
Output
Fact is 55
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. Member ship
String slices:
v
A part of a string is called string slices.
v
The process of extracting a sub string from a string is called slicing.
Immutability:
v
Python strings are “immutable” as they cannot be changed after they are
created.
v
Therefore [ ] operator cannot be used on the left side of an assignment.
Stringname.method()
a=”happy birthday”
Syntax:
import module_name
Example
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happ
y birthday"))
print(string.hexdigits)
print(string.octdigits)
output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567
List as array:
Array:
Syntax :
import array
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
i- integer datatype
Example
import array
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Output
10
Convert list into array:
fromlist() function is used to append list to array. Here the list is act like a
array.
Syntax:
arrayname.fromlist(list_name)
Example
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Output
35
Methods in array
a=[2,3,4,5]