Unit 3 (Python)
Unit 3 (Python)
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.
+ Addition a + b = 30
- Subtraction a b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0
2. Comparison Operators
The operators compare the values and establish the relationship among them.
3. Logical Operators
There are three types of logical operators and, or, not.
Operator Name Example
or OR a or b
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
| OR a|b
^ XOR a^b
~ NOT ~a
5. Assignment Operators
The assignment operator is used to assign the values to variables. Following is a list of assignment
operators.
= 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
[Link]
Perimeter of circle - 62.800000000000004
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.
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.
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!
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
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
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.
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
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
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: "))
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
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: "))
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]
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
print("Main Menu")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
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")
def evensum(n):
step = 2
total = 0
i=1
while i <= n:
total += step
step += 2
i += 1
return total
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)
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
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
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:
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)
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)
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
>>>
String Function
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']
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 +.
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
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
>>>
Output
I love programming in python
I 12v1 pr2gromming in pyth2n
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
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
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}
>>>
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()
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
Output
Enter some string :
Python123Program
Total number of digits in Python123Program are 3
Total number of letters in Python123Program are 13
>>>
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
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()
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
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
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)
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.
for i in range(len(arr)):
print(arr[i])
# Insert 25 at index 2
[Link](2, 25)
Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
25
30
40
>>>
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)
Output
The elements is array are ...
10
20
30
40
Now The elements is array are ...
10
20
40
>>>
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])
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])
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())
rem = a % b
while rem != 0:
a=b
b = rem
rem = a % 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 -
for i in range(n):
print("Enter the element:")
a[i] = int(input())
for i in range(n):
total += a[i]
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())
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])
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
for i in range(n):
print("Enter the element: ")
a[i] = int(input())
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.
Here middle element is 99 and key is also 99. Hence we declare that the element is found and it is at
index 6.