0% found this document useful (0 votes)
5 views53 pages

Unit 3 (Python)

The document provides an overview of boolean values, operators, and various programming constructs in Python, including arithmetic, comparison, logical, bitwise, assignment, membership, and identity operators. It also covers conditional statements, iteration techniques, and examples of Python programs for calculating areas, converting temperatures, and determining grades. Additionally, it explains input/output operations and string manipulation in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views53 pages

Unit 3 (Python)

The document provides an overview of boolean values, operators, and various programming constructs in Python, including arithmetic, comparison, logical, bitwise, assignment, membership, and identity operators. It also covers conditional statements, iteration techniques, and examples of Python programs for calculating areas, converting temperatures, and determining grades. Additionally, it explains input/output operations and string manipulation in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Boolean Values

• There are two types of boolean values – true or false.


• The boolean expression can be represented using the operator. For example
>>> 3= = 3
True
>>> 3= = 5
False
>>>
• In above example, = = operator is used for obtaining the boolean value of the expression.
• We can also check the data type of True and False with the help of type function
>>> type(True)
< class 'bool'>
>>> type(False)
< class 'bool' >
• Some of the valid boolean expressions are :
>>> True True >>> 5= =4 False >>> 3+2= =5 True >>>

Operators
• Operands are special symbols that are used in computations. For example +, - * and / are used for
performing arithmetic operations.
• The values that operator uses for performing computation are called operands. Various operators used
in Python are described as follows

1. Arithmetic Operators
• These operators are used for performing arithmetic operations.

Operator Name Example

+ Addition a + b = 30

- Subtraction a b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10**20

// Floor Division 9//2 = 4

2. Comparison Operators
The operators compare the values and establish the relationship among them.

Operator Name Example

== Equal (a == b) is not true.

!= Not equal (a != b) is true.

> Greater than (a > b) is not true.


< Less than (a < b) is true.

>= Greater than or equal to (a >= b) is not true.

<= Less than or equal to (a <= b) is true.

3. Logical Operators
There are three types of logical operators and, or, not.
Operator Name Example

and AND a and b

or OR a or b

not NOT not(a)

4. Bitwise Operators
Bitwise operators work on the bits of the given value. These bits are binary numbers i.e. 0 or 1.
For example: The number 2 is 010, 3 is 011.
Operator Name Example

& AND a&b

| OR a|b

^ XOR a^b

~ NOT ~a

<< Zero fill left shift a << 3

>> Signed right shift a >> 3

5. Assignment Operators
The assignment operator is used to assign the values to variables. Following is a list of assignment
operators.

Operator Example Same As

= a = 10 a = 10

+= a += 30 a = a + 30

-= a -= 15 a = a - 15

*= a *= 10 a = a * 10

/= a /= 5 a=a/5

%= a %= 5 a=a%5
**= a **= 4 a = a ** 4

//= a //= 5 a = a // 5

&= a &= 5 a=a&5

|= a |= 5 a=a|5

^= a ^= 5 a=a^5

>>= a >>= 5 a = a >> 5

<<= a <<= 5 a = a << 5

Example Write a program in Python to print area and perimeter of a circle.


Solution :
[Link]
print("Enter radius os a circle: ")
r = float(input())
PI = 3.14
area= PI*r*r
perimeter = 2.0*PI*r
print("Area of Circle = ", area);
print("Perimeter of Circle = ",perimeter)
Output

[Link]
Perimeter of circle - 62.800000000000004

Example Write a program to find area and perimeter of parallelogram.


Solution : Formula for finding area and perimeter of parallelogram is
Area= b*h
Perimeter = 2*b+2*w
We can write the python program using above formula
[Link]
print("Enter height(h):")
h = float(input())
print("Enter base(b): ")
b = float(input()) print("Enter width(w): ")
w = float(input())
area= b*h
perimeter = (2.0*b)+(2.0*w)
print("Area of Parallelogram = ",area);
print("Perimeter Parallelogram = ",perimeter)
Output:
Enter height(h):10
Enter base(b):20
Enter width(w):15
Area of Parallelogram = 200.0
Perimeter Parallelogram = 70.0
>>>

Example Write a program to convert Fahrenheit to Celsius.


Solution: We will use the following formula for conversion
Celsius = (Fahrenheit - 32)/1.8
[Link]
print("Enter Fahrenheit ")
f = float(input())
c = (f-32)/1.8
print("Celsius = ",c)
Output
Enter Fahrenheit
95.5
Celsius = 35.2777

6. Membership Operators
There are two types of membership operators – in and not in
These operators are used to find out whether a value is a member of a sequence such as string or list.

Operator Description Example

in Returns True if it finds a variable in the specified sequence, false otherwise. a in b

Returns True if it does not finds a variable in the specified sequence and false
not in a not in b
otherwise.

Following screenshot of Python shell shows the use of in and non in operator.
Explanation :
1) In example, we have created a list of colors.
2) The members of color list are "red","blue" and "green"
3) As “blue” is member of color list, it returns True for while testing with membership operator in
operator.
4) As "yellow" is not a member of color list, it return False for in operator and True for not in operator.

7. Identity Operators
The 'is' operator returns true if both the operand point to same memory location. Similarly 'is not operator
returns true if both the operand point to different memory location.

Operator Description Example

is Returns True if both variables are the same object and false otherwise. a is b

is not Returns True if both variables are not the same object and false otherwise. a is not b

Similarly,
>>> print(color1 is not color2)
True
Explanation : In above demonstration,
1) We have created two lists color1 and color2.
2) Although the contents of the lists are exactly the same, their memory locations are different. Hence
color1 is color2 becomes False.
3) As color3 is a new variable to which we assign color1, then they point to same memory location.
Hence color1 is color3 returns True.

8. Modulus Operator
The % operator is a modulo operator that gives the remainder from the division of first argument by
second.
For example –
>>> 10%3
1
>>> 10.10%3.3
0.20000000000000018
>>>
The operator // is used for floor division. This division returns the integral part of the quotient.
For example -
>>> 10//3.5
2.0

Example Write a program in Python to convert given time into minutes and seconds. For example - if
user inputs 260 seconds then the output should be 4 minute and 20 seconds. (Use // and % operators)
Solution :
time [Link]
print("Enter time: ")
time=float(input())
minutes = time//60
seconds = time % 60
print("Minutes are: ",minutes)
print("Seconds are: ",seconds)
Output

9. String Operators
• String is collection of characters.
• In python it is possible to perform the concatenation and repetition operations on strings using the
operators like + and *.
For example
>>> str1= "Hello"
>>> str2 = "friend"
>>> str1 + str2
'Hellofriend'
>>> "welcome"*2
'welcomewelcome!

Input and Output


• In python it is possible to input the data using keyboard.
• For that purpose, the function input() is used.
• Syntax
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.

The input method is used to get the data.


>>>a=input(“Enter some number:”)
Enter some number:10
>>>a
‘10’

Example: Write a python program to perform addition of two numbers. Accept the two numbers using
keyboard,
Solution :
[Link]
Output
For getting the output click on Run-> Module or press F5 key, following shell window will appear-

Program Explanation:
• In above program, we have used input() function to get the input through keyboard. But this input will
be accepted in the form of string.
• For performing addition of two numbers we need numerical values and not the strings. Hence we use
int() function to which the input() function is passed as parameter. Due to which whatever we accept
through keyboard will be converted to integer.
• Finally the addition of two numbers as a result will be displayed.
• The above program is run using F5 and on the shell window the messages for entering first and second
numbers will be displayed so that user can enter the numbers.

Example Write a Python program to find the square root of a given number
Solution :
[Link]
print("Enter the number:")
num = float(input())
result=num**0.5
print("The sqaure root of",num," is ",result)

Output
Enter the number:
25
The sqaure root of 25.0 is 5.0
>>>

Example Write a program in Python to obtain principle amount, rate of interest and time from user and
compute simple interest.
Solution :
[Link]
print("Enter principal amount: ")
p = float(input())
print("Enter rate of interest: ")
r = float(input())
print("Enter number of years: ")
n = float(input())
I = (p*n*r)/100
print("Simple Interest is: ",I)
Here we are reading the values through keyboard. Note we are reading the values as float
# Output will be displayed on console

Display Output on Console


Using .format the data can be displayed on the console. For that purpose { } and . format is used. For
example

Example 1
n = 10
print("There are {} numbers".format(n))
Output
There are 10 numbers
We can also display the data along with some space. For that purpose, we have to use {:n}. For example

Example 2 :
n=10
print("There are {:10d} numbers".format(n))
Output
There are 10 numbers

Example 3 :
a = 10
b = 20
c = 30
print("There are three numbers and those are {} {} {} numbers".format(a,b,c))
Output
There are three numbers and those are 10 20 30 numbers

Example Write a program to swap two numbers.


Solution :
a = input('Enter value of a: ').
b = input('Enter value of b: ')
temp = a
a=b
b = temp
print('After swapping a: {}'.format(a))
print('After swapping b: {}'.format(b))
Output
Conditional Statements
There are various types of conditional statements -
i) if statements
ii) if-else or alternate statements
iii) nested if
iv) chained conditionals

1. if statement
The if statement is used to test particular condition. If the condition is true then it executes the block of
statements which is called as if block.

The if statement is the simplest form of the conditional statement.


Syntax :
if condition:
statement
Example
if a < 10:
print("The number is less than 10")

Example Write a Python program to check whether given number is even or odd.
Solution :
Print (“Enter value of n”)
n=int(input())
if n%2= =0:
print(“Even Number”)
if n%2= =1:
print(“Odd Number”)
2. Alternative Statements
• The if-else statement provides an else block combined with the if statement which is executed in the
false case of the condition. The flowchart for if-else is

Syntax
if condition :
else :
statement
statement
• If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
[Link]
print("Enter value of n")
n = int(input())
if n % 2 == 0:
print("Even Number")
else:
print("Odd Number")

3. Nested if Statements
When one if condition is present inside another if then it is called nested if conditions. Any number of
these statements can be nested inside one another. Indentation is the only way to figure out the level of
nesting.

Example Write a python program to compare two numbers using nested conditionals,
Solution :
[Link]
print("Enter value of a")
a = int(input())
print("Enter value of b")
b = int(input())

if a == b:
print("Both the numbers are equal")
else:
if a < b:
print("a is less than b")
else:
# Nested if-else
if a > b:
print("a is greater than b")
Output
Enter value of a
20
Enter value of b
10
a is greater than b
>>>

4. Chained Conditionals
Sometimes there are more than two possibilities. These possibilities can be expressed using chained
conditions. The syntax for this is as follows
if condition:
Statement
elif condition:
Statement

else:
Statement
• The chained conditional execution will be such that each condition is checked in order.
• The elif is basically abbreviation of else if.
• There is no limit on the number of elif statements.
• If there is else clause then it should be at the end.

• In chained execution, each condition is checked in order and if one of the condition is true then
corresponding branch runs and then the statement ends. In this case if there are any remaining conditions
then those condition won't be tested.
Example Write a python program to display the result such as distinction, first class, second class, pass or
fail based on the marks entered by the user.
Solution :
print("Enter your marks")
m = int(input())
if m >= 75:
print("Grade : Distinction")
elif m >= 60:
print("Grade : First Class")
elif m >= 50:
print("Grade : Second Class")
elif m >= 40:
print("Grade : Pass Class")
else:
print("Grade : Fail")

Output
Enter your marks
45
Grade : Pass Class

Example Write a python program to find the largest among the three numbers.
Solution :
print("Enter value of a")
a = int(input())
print("Enter value of b")
b = int(input())
print("Enter value of c")
c = int(input())
if (a>b) and (a>c):
printf(“First Number is largest”)
elif (b>a) and (b>c):
printf(“Second Number is largest”)
if (a>b) and (a>c):
printf(“First Number is largest”)
else:
printf(“Third Number is largest”)

Output

Iteration
• Iteration is a technique that allows to execute a block of statements repeatedly.
Definition : Repeated execution of a set of statements is called iteration.
• The programming constructs used for iteration are while, for, break, continue and so on.
• Let us discuss the iteration techniques with the help of illustrative examples.

1. State
• The simple form of statement is assignment Statement. The statement is specified using = operator.
• The reassignment statement is specified as

• Reassigning variables is often useful, but you should use it with caution. If the values of variables
change frequently, it can make the code difficult to read and debug.
• Similarly we can update the values by using operators. For example :

2. while
The while statement is popularly used for representing iteration.
Syntax
while test_condition:
body of while
Flowchart for while statement is as given below

The flow of execution is specified as follows –


1. Using the condition determine if the given expression is true or false.
2. If the expression is false then exit the while statement
3. If the expression is true then execute the body of the while and goback to step 1 in which again the
condition is checked.
For example
while i< = 10:
i=i+1
• The body of a while contains the statement which will change the value of the variable used in the test
condition. Hence finally after performing definite number of iterations, the test condition gets false and
the control exits the while loop.
• If the condition never gets false, then the while body executes for infinite times. Then in this case, such
while loop is called infinite loop.
• There is another version of while statement in which else is used.
Syntax
while test_condition:
body of while
else:
statement
Example
while i < =10:
i=i+1
else:
print("Invalid value of i")
Programming Examples on while

Example Write a python program for computing the sum of n natural numbers and finding out the
average of it.
Solution : The python script is as given

This program can be run by pressing F5 key and following output can be obtained.
Output

Example Write a python program to display square of a numbers using while loop
Solution :
print(“Enter the value of n”)
n=int(input())
i=1
print(“The square table in as given below..”)
while i<=n:
print(i,i*1)
i=i+1

Output:

Example Write a python program for displaying even or odd numbers between 1 to n.
Solution :
n=int(print(“Enter the value of n”))
i=1
j=1
while j<=n:
if i%2= = 0:
print(i, “is even”)
else:
print(i, “is odd”)
j=j+1
i=j;

Example Write a python program to display Fibonacci numbers for the sequence of length.
Solution :
print("Enter the value of n")
n = int(input())
a=0
b=1
i=0
print("Fibonacci Sequence is...")
while i < n:
print(a)
c=a+b
a=b
b=c
i = i + 1Output
Enter the value of n
10
Fibonacci Sequence is...
0
1
1
2
3
5
8
12
21
34

3. for

The for loop is another popular way of using iteration. The syntax of for loop is
Syntax
for variable in sequence:
Body of for loop
The variable takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the
rest of the code using indentation.
Example
for val in numbers:
val = val + 1
Similarly, we can have for loop with else statement

Programming examples based on For Loop


Example Write a python program to find the sum of 1 to 10 numbers.
Solution:
print(“Enter the value of n”)
n=int(input())
num=0
for i in range (1,n+1):
sum=sum+i
print(“The sum of”, n,”number is”,sum);
Output:

Example Write a python program to display the multiplication table.


Solution :
print("Enter number for its multiplication table")
n = int(input())
for i in range(1,11):
print(n,"X",i,i*n)
Output

Example Write a program to print 1+1/2+1/3+1/4+…….+1/N series.


Solution:
print("Enter value of N")
n = int(input())
sum = 0
for i in range(1, n + 1):
sum = sum + 1/i
print("The Sum is", sum)Output

Example Write a Python program to check whether given number is prime or not.
Solution :
print("Enter the number")
num = int(input())

if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output

Example Write a Python Program to find the prime numbers between given interval.
Solution :
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
Output

Example Write a python program to display the star pattern as


*
**
***
****
*****
...
...
user should enter the value of N
Solution :
print("Enter value of n")
n = int(input())

for i in range(n):
for j in range(i + 1):
print('* ', end="")
print()
Output
Example Write a python program to display the number pattern as follows
12345
2345
345
45
5
Solution :
for i in range(1, 6):
for k in range(1, i):
print(end="")
for j in range(1, 6):
print(" ", j, end="")
print()
Output

Example Write a python program to print the pattern as given below


A
AB
ABC
ABCD
ABCDE
Solution :
for i in range(1, 6):
for j in range(65, 65 + i):
a = chr(j)
print(a, " ", end="")
print()
Output
Example Write a python program to print the pattern for alphabets
AAAAA
ВВВВ
CCC
DD
E
Solution :
num = 65 # ASCII value for A

for i in range(0, 5):


for j in range(1, 5):
ch = chr(num + i) # Convert ASCII to character
print(ch, " ", end='')
print()
Output

4. break
• The break statement is used to transfer the control to the end of the loop.
• When break statement is applied then loop gets terminates and the control goes to the next line pointing
after loop body.

Syntax
break
For example
for i in range(1,11):
if i = =5:
print("Element {} Found!!!".format(i))
break
print(i)
Output
5. continue
• The continue statement is used to skip some statements inside the loop. The continue statement is used
with decision making statement such as if...else.
• The continue statement forces to execute the next iteration of the loop to execute.

Syntax
continue
Example
In while loop the continue passes the program control to conditional test. Following example illustrates
the idea of continue
i=0
while i < 10:
i=i+1
if i%2 = = 0:
continue
print(i)
Output

6. pass
The pass statement is used when we do not want to execute any statement. Thus the desired statements
can be bypassed.
Syntax
Pass
Example
for i in range(1,5):
if i= =3:
pass
print("Reached at pass statement")
print("The current number is ",i)
Output

Example Write a Python program to print sum of cubes of the values of n variables,
Solution :
sum = 0
n = int(input("Enter some number: "))

for i in range(1, n + 1):


sum = sum + (i * i * i)

print("Sum of cubes of first", n, "numbers is =", sum)

Output
Enter some number: 5
Sum of cubes of first 5 numbers is = 225
>>>

Example Find the syntax error in the code given while True print('Hello world')
Solution : There must be colon after True and the print statement must be indented. The correct code is as
follows –
while True :
print('Hello world')
Fruitful Functions
There are two types of functions.
1) The functions that return some value
2) The functions that does not return the value. The fruitful functions are the functions that return values.

1. Return Values
The value can be returned from a function using the keyword return. For example
Syntax
return (expression_list]

Example Write a function that returns area of circle


Solution :
Step 1 : Write a function for finding out area of circle in Script mode as
[Link]
def area(r):
result = 3.14*r**2
print("The area of Circle ")
return(result)
Step 2 : Now press the key F5 to get the output of the above program. Give the function call by passing
some value of radius to it.
The output will be displayed on the shell window as follows:

2. Parameters
We can pass different number of parameters to the function. Following example illustrates the parameter
passing to the function
Example Write a Python program for creating simple calculator,
Solution :
def add(x, y):
return x + y

def sub(x, y):


return x - y

def mult(x, y):


return x * y

def div(x, y):


return x / y

print("Main Menu")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

print("Enter your choice")


choice = int(input())
print("Enter first number")
num1 = int(input())

print("Enter second number")


num2 = int(input())

if choice == 1:
print(num1, "+", num2, "=", add(num1, num2))
elif choice == 2:
print(num1, "-", num2, "=", sub(num1, num2))
elif choice == 3:
print(num1, "*", num2, "=", mult(num1, num2))
elif choice == 4:
print(num1, "/", num2, "=", div(num1, num2))
else:
print("Invalid Choice")

Output
Main Menu
[Link]
[Link]
[Link]
[Link]
Enter your choice
1
Enter first number
10
Enter second number:
20
10 + 20 = 30
>>>

Example Write a python program to find the largest among the three numbers.
Solution :
def largest(x, y, z):
if (x > y) and (x > z):
print("First Number is largest")
elif (y > x) and (y > z):
print("Second Number is largest")
else:
print("Third Number is largest")

print("Enter first number")


num1 = int(input())

print("Enter second number: ")


num2 = int(input())

print("Enter third number: ")


num3 = int(input())

largest(num1, num2, num3)


Example Write a Python program using function to find the sum of first 'n' even numbers and print the
result.
Solution :
# first n even numbers
# function to find sum of
# first n even numbers

def evensum(n):
step = 2
total = 0
i=1
while i <= n:
total += step
step += 2
i += 1
return total

print("Enter value of n")


n = int(input())
print("Sum of first", n, "even numbers is:", evensum(n))

Output
Enter value of n
3
sum of first 3 even number is: 12

Example Write a Python program using function to find the factors of a given number.
Solution :
# Define a function
def Find_factors(n):
# This function takes a number and prints its factors
print("The factors of", n, "are:")
for i in range(1, n + 1):
if n % i == 0:
print(i)

# Input from user


num = int(input("Enter a number: "))
Find_factors(num)

Output
Enter a number :
12
The factors of 12 are:
1
2
3
4
5
6
12
Example Write a Python program using function to find the GCD of two numbers
Solution :
# Define gcd function
def gcd(a, b):
if a < 1 or b < 1:
return None # Invalid input
while a != b:
if a > b:
a=a-b
else:
b=b-a
return a

# Input from user


num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))

result = gcd(num1, num2)

if result is None:
print("Invalid input: numbers must be positive")
else:
print("GCD =", result)

Output
Enter first number: 12
Enter second number: 15
The G.C.D of 12 and 15 is 3

3. Local and Global Scope


• The global variables are those variables that are declared and defined outside the function and can be
used inside the function.
• The local variables are those variables that are declared and defined inside a function.
• A global variable is one that can be accessed anywhere. A local variable is the opposite, it can only be
accessed within its frame.
• The difference between the global and local is that global variables can be accessed locally, but not
modified locally inherently.
• For example : In the following program, variable a is global variable.
def fun():
print(a)
#global scope
a = 10 fun()
Output
10
Now consider following program, in which we try to change the value declared outside the function
def f():
print(a)
a = 100 #Due to this statement the error is raised
# Global scope
a = 10
f()
print(a)
To make the above program work, we need to use global keyword. We only need to use global keyword
in a function if we want to do change that variable.
The corrected version of above program is as follows:
def f():
global a
print(a)
a = 100
# Global scope
a = 10
f()
print(a)
Output
10
100

4. Function Composition
• Function composition is a way of combining functions such that the result of each function is passed as
the argument of the next function.
• For example, the composition of two functions f and g is denoted f(g(x)). Here x is the argument of g,
the result of g is passed as the argument of f and the result of the composition is the result of f.
For example
Step 1: Create a simple function for addition of two numbers.
def add(a,b):
return a+b
Step 2: Create a simple function for multiplication of two numbers
def mul(c,num):
return c*num
Step 3: Create a main function in which the two functions used in above two steps are called.
def mainFun(x,y):
z = add(x,y)
result = mul(z, 10)
return result
The complete program will now look like this

Step 4: Now execute the above program by pressing F5 key. The output can be obtained as follows -
Recursion
Definition : Recursion is a property in which one function calls itself repeatedly in which the values of
function parameter get changed on each call.
Properties of Recursion
There are three important laws of recursion –
1. A recursive function must have a base case.
2. A recursive function must change its state and move toward the base case.
3. A recursive function must call itself, recursively.

Example 3.7.1 Display the numbers from 10 to 1 (ie, numbers in reverse order) using recursion in
python. Also draw the stack diagram representing the execution of the program.
Solution :
def display(n):
if n <= 0:
return
else:
print(n)
display(n - 1)

# Example usage
num = int(input("Enter a number: "))
display(num)

Output
The execution of above program can be diagrammatically shown as follows:

Example 3.7.2 Write a python program for recursive factorial function,


Solution :
def factorial(n):
if n == 0:
return 1
else:
result = n * factorial(n - 1)
return result

print(factorial(5))
Output
120

Example 3.7.3 Write a python program to display the Fibonacci series upto n numbers using recursion
Note The Fibonacci numbers are 0,1,1,2,3,5,8,13,21,34,.., where each number is a sum of the preceding
two numbers.
AU : Jan.-18, Marks 8
Solution :
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)

print("Enter number of terms ")


n = int(input())
print("Fibonacci sequence is as follows...")

for i in range(n):
print(fibonacci(i))

Output
Example 3.7.4 Implement a recursive function in python for sieve of Eratosthenes. The Sieve of
Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer.

Solution :
# Recursive function to check if a number is prime
def is_prime(i, num):
if i == num:
return True
if num % i == 0:
return False
return is_prime(i + 1, num)

n = int(input("Enter last number: "))


print("Prime numbers between 1 to", n, "are:")

for i in range(2, n + 1):


if is_prime(2, i):
print(i, end=" ")

Output
Enter last Number:50
Prime Number Between 1 to n are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
>>>

1. Advantages and Disadvantages


Advantages
1) It reduces the length of code.
2) It is very useful while applying the same pattern of solution.
3) It reduces unnecessary calling of function.
4) Big and complex iterative solutions are easy and simple with Python recursion.
Disadvantages
1) Recursive functions are slower than iterative solutions.
2) It is hard to analyse or understand the code.
3) It may require a lot of memory space to hold intermediate results on the system stack.
4) The computer memory may run out of memory if the recursive calls are not properly checked.
2. Comparison of Recursions with Iteration
Recursion
1. The function is called itself repeatedly.
2. The intemal stack is used to store the set of local variables
3. Recursion is always applied to function
4. Slow in execution.
5. Recursion reduces the size of the code.
Iteration
1. The set of instructions is executed repeatedly
2. It does not use stack.
3. Iteration is applied to control statements such as for loops, while and do while statements.
4. Fast in execution.
5. Iteration makes the code lengthy

String Function

String is basically the sequence of characters.


Any desired character can be accessed using the index.
For example >>> country ="India"
>>> country[1] → Here using index the particular character is accessed
'n'
>>> country[2]
'd'
>>>
The index is an integer value if it is a decimal value, then it will raise an error. For example
>>> country(1.5)
TypeError: string indices must be integers
>>> The string can be created using double quote or single quotes. For example
>>> msg="Hello"
>>> print(msg)
Hello
>>> msg ='Goodbye'
>>> print(msg)
Goodbye
Finding length of a String
There is an in-built function to find length of the string. This is len function. For example
>>> msg="Goodbye'
>>> print(msg)
Goodbye
>>> len(msg)
7

Traversing the String


We can traverse the string using the for loop or using while loop.
Example 1 - Traversing a string using while string
Example 2 - The string can be traversed using for loop
Python Program
msg = 'GoodBye'
for index in range(len(msg)):
letter = msg[index]
print(letter)

Output
G
o
o
d
B
y
e
>>>

Example 3.8.1 Write a program to display a set of strings using range() function.
Solution :
handsets = ['Samsung', 'OPPO', 'OnePlus', 'Apple']

print("The mobile handsets are...")


for i in range(len(handsets)):
print(handsets[i], end=" ")
Output
The mobile handsets are...
Samsung OPPO OnePlus Apple
>>>

1. String Slices
String slice is an extracted chunk of characters from the original string. In python we can obtain the string
slice with the help of string indices. For example - We can obtain
>>> msg = "Good Morning"
>>> msg[0:4]
'Good'
>>> msg(5:12]
'Morning'
Here the string from 0 to less than 4 index will be displayed. In the next command the string from 5th
index to 11th index is displayed.

We can omit the beginning index. In that case, the beginning index is considered as 0. For example
>>> msg[:4] ←Here the starting index will be 0
'Good'
Similarly we can omit ending index. In that case, the string will be displayed upto its ending character.
For example -
>>> msg[5:] ← Here the last character of the string is the ending index
Morning
>>>
If we do not specify any starting index or ending index then the string from starting index 0 to ending
index as last character position will be considered and the entire string will be displayed. For example
>>> msg[:]
Good Morning
>>>

2. Immutability
Strings are immutable i.e we cannot change the existing strings. For example
>>> msg = "Good Morning"
>>> msg[0]='g'
Output
TypeError: 'str' object does not support item assignment
To make the desired changes we need to take new string and manipulate it as per our requirement. Here is
an illustration
Python Program
msg = 'Good Morning'
new_msg = 'g'+ msg[1:]
print(new_msg)
Program Explanation :
In above example the new_msg string is created to display "good morning" instead of “Good Morning"
The string slice from character 1 to end of string is concatenated with the character'g'. The concatenation
is performed using the operator +.

3. String Functions and Methods


In this section we will discuss various string functions and methods.
1. String Concatenation
Joining of two or more strings is called concatenation.
In python we use + operator for concatenation of two strings.
For example –

2. String Comparison
The string comparison can be done using the relational operators like <,>,= = . For example
>>> msg1="aaa"
>>> msg2="aaa"
>>> msg1= =msg2
True
>>> msg1="aaa"
>>> msg2="bbb"
>>>print(msg1<msg2)
True
Note that, the string comparison is made based on alphabetical ordering. All the upper case letters appear
before all the lower case letters.

3. String Repetition
We can repeat the string using * operator. For example
>>> msg="Welcome!"
>>> print(msg*3)
Welcome!Welcome!Welcome!

4. Membership Test
The membership of particular character is determined using the keyword in. For example -
>>> msg ="Welcome"
>>> 'm' in msg
True
>>> 't' in msg
False
>>>
Methods in String Manipulation
Some commonly used methods are enlisted in the following table.
Method : count ()
Purpose : This methods searches the substring and returns how many times the substring is present in it.
Method : capitalize()
Purpose : This function returns a string with first letter capitalized. It doesn't modify the old string
Method : find()
Purpose : The find() method returns the lowest index of the substring (if found). If not found, it returns -
1.
Method : index
Purpose : This method returns the index of a substring inside the string (if found). If the substring is not
found, it raises an exception.
Method : isalnum().
Purpose : The isalnum() method returns True if all characters in the string are alphanumeric
Method : isdigit()
Purpose : The isdigit() method returns True it all characters in a string are digits. If not, it returns False
Method : islower()
Purpose : The islower() method returns True if all alphabets in a string are lowercase alphabets. If the
string contains at least one uppercase alphabet, it returns False
Let us illustrate these methods with the help of python code.

4. String Module
The string module contains number of constants and functions to process the strings. To use the string
module in the python program we need to import it at the beginning.
Functions
We will discuss, some useful function used in string module.
1. The capwords function to display first letter capital
The capwords is a function that converts first letter of the string into capital letter.
Syntax
[Link](string)
Example program : Following is a simple python program in which the first character of each word in
the string is converted to capital letter.
[Link]
import string
str = 'i love python programming'
print(str)
print([Link](str))
Output

2. The upper function and lower case


For converting the given string into upper case letter. We have to use [Link]() function instead of
[Link]. Similarly [Link]() function is for converting the string into lower case. Following program
illustrates this.
[Link]
import string
text1 = 'i love programming'
text2 = 'PROGRAMMING IN PYTHON IS REALLY INTERESTING'
print("Original String: ", text1)
print("String in Upper Case: ", [Link](text1))
print("Original String: ", text2)
print("String in Lower Case: ", [Link](text2))

Output
Original String: i love programming
String in Upper Case: I LOVE PROGRAMMING
Original String: PROGRAMMING IN PYTHON IS REALLY INTERESTING
String in Lower Case: programming in python is really interesting
>>>

3. Translation of character to other form.


The maketrans() returns the translation table for passing to translate(), that will map each character in
from_ch into the character at the same position in to_ch. The from_ch and to_ch must have the same
length.
Syntax
[Link](from_ch, to_ch)
Programming Example
[Link]
from_ch = "aeo"
to_ch = "012"
new_str = [Link](from_ch,to_ch)
str = "I love programming in python"
print(str) print ([Link](new_str))

Output
I love programming in python
I 12v1 pr2gromming in pyth2n

Program explanation : In above program,


1) We have generated a translation table for the characters a, e and o characters. These characters will be
mapped to 0, 1 and 2 respectively using the function maketrans.
2) The actual conversion of the given string will take place using the function translate.
3) According the above programming example, the string “I Love Programming in Python” is taken.
From this string we locate the letters a, e and o, these letters will be replaced by 0, 1 and 2 respectively.
4) The resultant string will then be displayed on the console.
Constants
Various constants defined in string module are -

We can display the values of these string constants in python program. For example -
[Link]
5. Programming Examples Based on String
Example 3.8.2 Write a Python program to find the length of a string
Solution :
def str_length(s):
length = 0
for ch in s:
length += 1
return length

print("Program to find the length of a string")


print("Enter some string:")
s = input()
print("Length of the string is:", str_length(s))
Output
Program to find the length of a string
Enter some string:
Python
Length of a string is : 6
>>>

Example 3.8.2 Write a Python program to count occurrence of each word in given sentence.
Solution :

def count_occur(s):
data = dict()
words = [Link]()
for word in words:
if word in data:
data[word] += 1
else:
data[word] = 1
return data

print("Enter some string:")


s = input()
print(count_occur(s))

Output
Enter some string :
A big black bear sat on a big black rug
{'A': 1, 'big': 2, 'black': 2, 'bear': 1, 'sat': 1, 'on': 1, 'a': 1, 'rug': 1}
>>>

Example 3.8.4 Write a Python program to copy one string to another.


Solution :
print("Enter some string:")
str1=input()
str2=""
for i in range (len(str1)):
str2=str2+str1[i]
print("The copied string is: ",str2)

Output
Enter some string:
Technical
moitulo The copied string is: Technical
>>>

Example 3.8.5 Write a Python program to check if a substring is present in the given string or not.
Solution :
print("Enter some string: ")
str1 = input()

print("Enter a word: ")


str2 = input()

if [Link](str2) == -1:
print("The substring", str2, "is not present in", str1)
else:
print("The substring", str2, "is present in", str1)

Output
Enter some string:
sky blue
Enter a word:
blue The substring blue is present in sky blue
>>>
Example 3.8.6 Write a Python program to count number of digits and letters in a string,
Solution :
print("Enter some string: ")
s = input() # Avoid using 'str' as it is a built-in name

digit_count = 0
letter_count = 0

for i in s:
if [Link]():
digit_count += 1
elif [Link](): # Count only letters
letter_count += 1

print("Total number of digits in", s, "are", digit_count)


print("Total number of letters in", s, "are", letter_count)

Output
Enter some string :
Python123Program
Total number of digits in Python123Program are 3
Total number of letters in Python123Program are 13
>>>

Example 3.8.7 Write a Python program to count number of vowels in a string,


Solution :
print("Enter some string: ")
s = input() # Avoid using 'str' as it is a built-in type

vowel_count = 0
for i in s:
if (i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or
i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'):
vowel_count += 1

print("Total number of vowels in", s, "are", vowel_count)

Output
Enter some string:
India
Total number of vowels in India are 3
>>>

Example 3.8.8 Write a Python program to check if the string is palindrome or not.
Solution :
print("Enter some string:")
s = input() # Avoid using 'str' as a variable name

rev_s = list(reversed(s))

if list(s) == rev_s:
print("The string", s, "is a palindrome")
else:
print("The string", s, "is not a palindrome")

Output
Enter some string :
madam
The string madam is palindrome
>>>

Example 3.8.9 Write a Python program to sort the word in a sentence in an alphabetic order.
Solution :
print("Enter some string: ")
s = input() # Avoid using 'str' as a variable name

words_list = [Link]()
words_list.sort()

print("The words in sorted order are...")


for word in words_list:
print(word)

Output
Enter some string :
I like python program very much
The words in sorted order are...
I
Like
much
program
python
very
>>>
Lists as arrays
The arrays is a data structure in which the elements are of same data type.
A list in Python is just an ordered collection of items which can be of any type. By comparison
an array is an ordered collection of items of a single type.
The elements in the array are separated by comma and are enclosed within the square bracket. For
example
arr = [10,20,30,40,50]
The arr can be represented by following figure

Fig. 3.9.1 Array representation


Here the values are arranged sequentially as follows –
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

1. Creation of Arrays
We can create an array using the array name and list of elements. For example
arr = [10,20,30,40]
will create an array containing the elements 10,20,...,40. These elements can be represented using for
loop. Following program represents the array creation and display of elements.
[Link]
arr = [10,20,30,40] print("The elements is array are ...")
for i in range(len(arr)):
print(arr[i])
Output

Another method of creation of Array


We can also create an array using following method
a = [i for i in range(10)]

2. Operations on Arrays
1. Appending a value
Using append() function we can add the element in the array at the end. For example
[Link]
arr = [10, 20, 30, 40]
print("The elements in array are...")

for i in range(len(arr)):
print(arr[i])

# Add an element
[Link](50)

print("Now the elements in array are...")


for i in range(len(arr)):
print(arr[i])

Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
30
40
50
>>>
Thus we can see that value 50 is appended in the array.

2. Inserting the element in the list


autemele ed We can insert the value at any desired location using insert() function. The syntax is
insert(index,value)
For example
[Link]
arr = [10, 20, 30, 40]
print("The elements in array are...")

for i in range(len(arr)):
print(arr[i])

# Insert 25 at index 2
[Link](2, 25)

print("Now the elements in array are...")


for i in range(len(arr)):
print(arr[i])

Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
25
30
40
>>>

3. Extending the array


We can extend one array by joining another array to it. For that purpose the extend() function is used. The
syntax is
extend(new_array)
For example
[Link]
arr = [10, 20, 30, 40]
print("The elements in array are...")

for i in range(len(arr)):
print(arr[i])

# Extend the array with another list


new_arr = [50, 60, 70]
[Link](new_arr)

print("After extending, the elements in array are...")


for i in range(len(arr)):
print(arr[i])

Output
The elements is array are ...
10
20
30
40
50
60
70
>>>
4. Removing the element from the array
Any desired element can be deleted from the array using remove() method. The syntax is
remove(index_of_element)
For example
[Link]
arr = [10, 20, 30, 40]
print("The elements in array are...")

for i in range(len(arr)):
print(arr[i])
# Remove element 30
[Link](30)

print("Now the elements in array are...")


for i in range(len(arr)):
print(arr[i])

Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
40
>>>

5. Removing last element from array


For removing the last element from the array then pop() function is used.
Syntax
pop()
For example
[Link]
arr = [10, 20, 30, 40]
print("The elements in array are...")

for i in range(len(arr)):
print(arr[i])

# Remove the last element


[Link]()

print("Now the elements in array are...")


for i in range(len(arr)):
print(arr[i])

Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
30
>>>
6. Reversing the elements of array
We can reverse the contents of the array using reverse() function
For example
[Link]
arr = [10, 20, 30, 40]
print("The elements in array are...")

for i in range(len(arr)):
print(arr[i])

# Reverse the array


[Link]()

print("Now the elements in array are...")


for i in range(len(arr)):
print(arr[i])

Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
40
30
20
10
>>>
7. Counting the occurrence of element in array
We can count the number of times the particular element appears in the array using the count method.
For example
[Link]
arr = [10, 20, 30, 40, 50, 20, 30, 20]
print("The elements in array are...")

for i in range(len(arr)):
print(arr[i])

print("The element 20 appears", [Link](20), "times in array")

Output
The elements is array are ...
10
20
30
40
50
20
30
20
The element 20 appears for 3 times in array
Illustrative Programs

1. square Root
Following is a Python program that is used for obtaining the square root of a given number
Python Program
print("Enter the number: ")
num = float(input())
sqrt_num = num ** 0.5
print("The square root of ",num," is ",sqrt_num)
Output

2. GCD
The GCD is a largest integer that can exactly divide both numbers without a remainder.
The easiest and fastest process consists in decomposing each one of the numbers in products of prime
factors, this is, and we successively divide each one of the numbers by prime numbers till we reach a
quotient that equals 1.
For example -
96 = 2 × 2 × 2 × 2 × 2 × 3
36 = 2 × 2 3 × 3
GCD = 2 × 2 × 3
= 12
Hence GCD of 96 and 36 is 12.
Iterative Python Program
print("Enter first number: ")
a = int(input())

print("Enter second number: ")


b = int(input())

rem = a % b

while rem != 0:
a=b
b = rem
rem = a % b

print("GCD of given numbers is:", b)

Output
Recursive Python Program
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)

print(gcd(96, 36))

Output
12
>>>
Cano

3. Exponentiation
Python Program
def expo(base, degree):
result = 1
i=1
while i <= degree:
result = base * result
i += 1
print("Result is", result)

expo(2, 3)

Output
Result is 8
>>>

4. Sum of Numbers
For sum of numbers we have to store the numbers in an array. And by traversing the elements of array,
each number is added with each other. The resultant sum is then printed.
For example
Consider 5 numbers stored in an array as follows -

Sum = (10 + 20 + 30 + 40 + 50) = 150


Python Program
print("Enter total number of elements in array")
n = int(input())

a = [0] * n # Create an array of size n


total = 0

for i in range(n):
print("Enter the element:")
a[i] = int(input())

print("The elements in array are...")


for i in range(n):
print(a[i])

for i in range(n):
total += a[i]

print("The sum of all elements in array is", total)

Output

5. Linear Search
In linear search method, the key element is compared against every element of the array. If the key
element matches with the array element then we declare element is found otherwise the element is
declared as not found.
Python Program
print("Enter total number of elements in array")
n = int(input())

a = [0] * n # Creation of array

for i in range(n):
print("Enter the element: ")
a[i] = int(input())
print("The elements in array are...")
for i in range(n):
print(a[i])

print("Enter the key element to be searched ")


key = int(input())

found = False
for i in range(n):
if a[i] == key:
found = True
break

if found:
print("The element is found")
else:
print("The element is not found")

Output

6. Binary Search
The binary search is an efficient searching technique.
Python Program
def binary_search(a, n, key):
low = 0
high = n - 1 # indices go from 0 to n-1

while low <= high:


mid = (low + high) // 2
if key == a[mid]:
return mid
elif key < a[mid]:
high = mid - 1
else:
low = mid + 1
return -1

n = int(input("Enter the size of the list: "))


a = [0] * n # Creation of array

for i in range(n):
print("Enter the element: ")
a[i] = int(input())

k = int(input("Enter the element to be searched: "))


position = binary_search(a, n, k)

if position != -1:
print("Entered number {} is present at position: {}".format(k

Output(Run1)
Enter the size of the list: 5
Enter the element:
10
Enter the element:
20
Enter the element:
30
Enter the element:
40
Enter the element:
50
Enter the element to be searched:
40
Entered number 40 is present at position: 3
>>>
Output(Run2)
Enter the size of the list: 5
Enter the element:
10
Enter the element:
20
Enter the element:
30
Enter the element:
40
Enter the element:
50
Enter the element to be searched:
90
Enter the number 90 is not present in the list
>>>
Explanation on Binary search method
The prerequisite for this searching technique is that the arry should be sorted.
Example :
Aa mentioned earlier the necessity of this method is that all the elements should be sorted. So let us take
an arry of sorted elements.

Step 1: Now the key element which is to be searched is = 99 key = 99.


Step 2: Find the middle element of the array. Compare it with the key
if middle < key
i.e. if 42 < 99

if 42 < 99 search the sublist 2.

Here middle element is 99 and key is also 99. Hence we declare that the element is found and it is at
index 6.

You might also like