Ge3151 Python Unit3
Ge3151 Python Unit3
3.1 CONDITIONALS
3.1.1 Boolean Values
Boolean data types have two values. They are 0 and 1.
0 represents False and 1 represents True. True and False are keywords.
Relational operators such as ==, !=,>,<,>=,<= and the logical operators such as and, or, not
are the Boolean operators
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
>>> x=True
>>> y=False
>>> x and y
False
>>> x or y
True
>>> not x
False
>>> not y
True
1
1 Conditional (if):
Conditional (if) is used to test a condition, if the condition is true the statements inside if will
be executed.
syntax:
Flowchart:
Example:
Program to provide flat rs.500, if the purchase amount is greater than 2000.
Program to provide bonus mark if the category is sports.
2 Alternative (if-else)
In the alternative if-else, the condition must be true or false.
In this, else statement can be combined with if statement.
If the condition is true, statements inside the if get executed otherwise else part gets
executed.
syntax: Flowchart:
2
Examples
1. odd or even number
2. positive or negative number
3. leap year or not
4. Greatest of 2 numbers
5. Eligibility for voting
Flowchart:
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
4
2. Traffic light system
Output
colour=input("enter colour of light:") enter colour of light: green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
Output
3 Compare two numbers
4Nested conditionals
One conditional can also be nested within another. Any number of conditions can be nested
inside one another.
In this, if the condition is true it checks another if condition1.
If both the conditions are true, statement1 gets executed otherwise statement2 gets
executed.
If condition is false statement3 gets executed
Syntax
5
Flowchart:
Example
6
3.2 ITERATION
3.2.1 Iteration statements
1. while
2. for
State: Transition from one process to another process under specified condition with in a time
is called state. The state variable or the variable in the loop undergoes change for each iteration.
1. While: 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 is entered 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.
In Python, the body of the while loop is determined through indentation.
Syntax:
Flowchart
Program Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number is greater than 5") the number is greater than 5
7
Nested while
While inside another while is called nested while
Syntax
8
3 Sum of digits of a number Output
n=int(input("enter the number")) enter a number
sum=0 123
while (n>0): 6
a=n%10
sum=sum+a
n=n//10
print(sum1)
4 Reverse of the given number Output
9
For Loop
For loop statement in Python is used to repeatedly execute set of statement as long as the given
condition is true. For statement iterate over a range of values or sequence (String, List, Tuple)
Syntax :
for variable in range() :
body of for loop
The different methods of using for loop in Python are given below:
i) for in range
We can generate a sequence of numbers using range () function. Range function have to
define the start, stop and step size as range (start, stop, step size).
The default value of step size is 1 if not provided. The default value of start is 0.
Range (10) will generate numbers from 0 to 9 (10 numbers).
The body of for loop is separated from the rest of the code using indentation.
syntax
Example
For loop with Sequence Output
for i in "RANI": R
For loop in string print(i) A
N
I
For loop in list for i in [2,3,5,6,9]: 2
3
print(i)
5
6
9
For loop in tuple
for i in (2,3,1): 2
print(i) 3
1
10
iii) else in for loop
The else statement can be used in for loop. The else statement is executed when the loop has
reached the limit. The statements inside for loop and statements inside else will also execute.
Example Output
for i in range(1,5): 1
print(i) 2
else: 3
print("the number is greater than 4”) 4
the number is greater than 4
Example :
Examples:
1. print numbers divisible by 5 not by 10:
2. Program to print Fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
i) break
Break statement can alter the flow of a loop.
It terminates the current loop and executes the statements outside loop.
If the loop has else statement, that will also get terminated and come out of the
loop completely.
Syntax
Flowchart
13
ii) continue
This terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
Flowchart
3. 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
Examples
3.3 FUNCTIONS
14
Example 2:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
b. Void function: A function that performs action but don’t return any value is called void
function
Example 1:
print( “Hello” )
Example 2:
def add():
a=10
b=20
c=a+b
print(c)
add()
c. Return values: Return keyword is used to return the value from the function.
Examples description
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
Example :
def area(s):
c=s*s
return (c)
a = int (input(“Give the value of side”))
ar=area(a)
print(“Area of square=”,ar)
d. Parameter / Arguments
Parameters are the variables/values which are used in the
function definition.
Parameters are inputs to functions.
Parameter receives the input from the function call.
It is possible to define more than one parameter in the function definition.
Types of parameters:
i) Required/Positional parameters
ii) Keyword parameters
iii) Default parameters
iv) Variable length parameters
15
i) 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 ): Output: George 98
print(name,roll)
student(“ George” ,98)
ii) 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 ): Output: 90 102 bala
print(name,roll,mark) bala 102 90
student( 90,102,”bala”)
student( roll=102,mark=90,name =,”bala”)
iii) Default parameter: Python allows function parameter to have default values; if the function
is called without that argument, the argument gets its default value in function definition.
Example
def student( name, age=17): Output Kumar 17
print(name,age) Ajay 17
student(“ kumar”)
student(“ ajay”)
iv) 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( name, *mark): Output bala (102,90)
print(name,mark)
student(“bala",102,90)
e. Local and global scope of variables in functions
The SCOPE of a variable refers to the places where you can see or access a variable.
Global scope : A variable with global scope can be used anywhere in the program.
It can be created by defining a variable outside the function.
Example
f. 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.
Example 1: Output:
def add(a,b): 900
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
The above statement is also function composition where, “input” is a built-in function.
The value got through input function is passed as argument to “int” function and gets
converted to integer value
g. 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 Output
def fact(n): enter no. to find factorial: 5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find factorial:"))
f=fact(n)
print("Fact is ",f)
Explanation
Example
sum of n numbers using recursion
def sum(n):
if(n==1):
return 1
else:
return n+sum(n-1)
n=eval(input("enter no. to find sum:"))
sum=sum(n)
print("Sum is",sum)
Syntax:
var = lambda arguments : expression
Example :
3.4 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 an index. The index should always be an
integer (positive or negative). The 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 is enclosed within:
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes (“”” “””)
String Traversal : Accessing the elements of string using its index value in for/while loop
Example:
name=”jai” j
for i in name: a
print(i) i
Operations on string
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
String A H E L L O
Positive Index 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
20
3.4.3. String built in functions and methods:
21
Escape Sequences:
An escape sequence contains a backslash (\) symbol followed by a character. In Python, backslash ( \ )
is known as escape character because it causes an escape from the normal interpretation of the character.
When used inside a character or string, does not represent itself but is converted into another character or
series of characters like newline (\n), tab (\t), and so on.
22
Exampe for list as array
a=[]
for i in range(0,10):
car=input("Give the car name")
a.append(car)
for i in range(0,10):
print(a[i])
ILLUSTRATIVE PROGRAMS
1. Square root using newtons method
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
Output
enter number to find Sqrt: 9
3.0
Method 2 :
n=int(input("Give the number"))
sqrt=n**0.5
print("Square root of",n,"is",sqrt)
Output
Give the number 9
Square root of 9 is 3.0
23
2. GCD of two numbers - Method 1
n1=int(input('Enter a number1:'))
n2=int(input('Enter a number2:'))
for i in range(1,n1+1):
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Output
Enter a number1: 8
Enter a number2: 24
8
3. Exponent of number
base = int(input("Give the base : "))
exponent = int(input("Give the Exponent : "))
result = 1
for i in range(exponent):
result = result* base
print("Answer = ",result)
Output :
Give the base: 2
Give the Exponent: 3
Answer = 8
24
4. 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
5. Linear Search
a=[20,30,40,50,60,70,80]
print(a)
search=eval(input("enter a element to search:"))
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
Output
[20, 30, 40, 50, 60, 70, 80]
enter a element to search:40
element found at 3
6 Binary Search
Output
[20, 30, 40, 50, 60, 70, 80]
enter a element to search:50
element found at 4
25