0% found this document useful (0 votes)
52 views164 pages

Unit 1

Uploaded by

Chinnu Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views164 pages

Unit 1

Uploaded by

Chinnu Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 164

Introduction

1
Features of Python
• Easy to read code
• Open Source
• Non-mandatory delimiters
• Dynamic typing
• Dynamic memory usage
• Interpreted language
• Platform independent(Byte Code, PVM)
• Procedure and Object Oriented
• Multi paradigm language(Extensible and Embeddable)
• Database Connectivity
• Batteries
• Scripting Language
Large ecosystem of scientific libraries and its high and vibrant community

2
“The only way to learn a new programming language is writing programs in it”
– Dennis Ritchie

“First, solve the problem. Then, write the code” – John Johnson

3
JAVA //Java Program to add two numbers
Class ADD //create a class
{ Non-mandatory delimiters
public static void main(String arg[]) Dynamic typing
{
int a, b; //take two variables
a = b = 10; //store 10 in a and b
System.out.println("Sum = " + (a+b)); //display their sum
}
}
C /* C Program to add two numbers */
#include<stdio.h>
void main()
{
int a, b; /* take two variables */
a = b = 10; /*store 10 in to a, b */
printf("Sum = %d ",(a + b)); /*display their sum */
}
PYTHON #Python program to add two numbers
a = b =10 #Take two variables and store 10 in to them
print("Sum= ", (a+b)) #display their sum
4
Installing Python
 Python 3.12.2
 Two variations(32 bit version and 64 bit version)
 https://www.python.org/
 Select Downloads

5
Popular Toolboxes

• NumPy
• Pandas
• Matplotlib
• SciPy
• Scikit-Learn

6
Installation of Additional Packages

To download and install numpy


C:\>pip install numpy
pip -> Python installation package

pandas is a package used in data analysis(Python Data Analysis Library)


To download and install pandas
C:\>pip install pandas

7
Installation of Additional Packages

• openpyxl is a package that is useful to retrieve data from Microsoft Excel spreadsheet
files.
• To download and install openpyxl
• C:\>pip install openpyxl

• matplotlib is a package that is useful to produce good quality 2D graphics


• To download and install matplotlib
• C:\>pip install matplotlib

8
Numeric and Scientific Computation: NumPy and SciPy
• Numpy:
• Support for multidimensional array
• Linear algebra functions

• Scipy:
• Signal processing
• Optimization
• Statistics
• Matplotlib: Data Visualization

9
SCIKIT-Learn: Machine Learning in Python

• Machine learning library built from NumPy, SciPy, and Matplotlib


• Classification
• Regression
• Clustering
• Dimensionality reduction
• Model selection
• Preprocessing

10
PANDAS: Python Data Analysis Library

• Dataframe
• Functions
• Reshaping
• Aggregation
• Merge
• Joining
• Data Import and Export: CSV, Textfile, Excel, SQL and HDF5(Hierarchical
Data Format) format
• Missing value handling

11
How Python sees variable
Variables are seen as tags(name) tied to some value.

Example 1:
a=1
Python considers the values as ‘objects’. If we change the value of a to a new value
a 1
If we change the value a = 2
a 2 1
1 becomes unreferenced object, it is removed by garbage collector

Example 2:
b=a
a
2
b

12
Built-in data types
• The built-in data types are of five types
• None Type
• Numeric types
• Sequences
• Sets
• Mappings

13
None Type
• None datatype represents an object that does not contain any value.
• Used inside a function as a default value of the arguments.
• When calling the function, if no value is passed, then the default value
will be taken as ‘None’.
• None datatype represents false.

14
Examples : None data type
Example 1:
x = None
print(x)

Output
None

Example 2:
x = None
if x:
print("Do you think None is True")
else:
print("None is not True...")

Output
None is not True...
15
largest number of size 2 bytes :
16
11111111 11111111 = 2 – 1 = 65536–1 = 65535(0 to 65535)

3 Bits =23 = 8(0 to 7)


Binary Decimal Binary Decimal
0000 0 1000 8
4 Bits = 24 = 16 (0 to 15)
0001 1 1001 9
0010 2 1010 10 5 Bits=25 = 32 (0 to 31)
0011 3 1011 11
0100 4 1100 12 6
6 Bits=2 = 64 (0 to 63)
0101 5 1101 13
0110 6 1110 14
0111 7 1111 15 16
=> 16 Bits = 2 = 65536 (0 to 65535)

16
Numeric data type
• The numeric type represents numbers. There are three sub types.

• int
• Ex: a = -98 (No limit for the size)

• float
• Ex1: num = 45.67
• Ex2:num1 = 34.65e4

• complex
• Ex1: c1 = 4 ̶ 5.6j
• Ex2: c2 = -5+7j

17
Program to display the sum of two complex numbers
#python program to add two complex numbers
c1= 2.5+2.5j
c2 = 3.0-0.5j
c3=c1+c2
print("Sum= ",c3)

Output
Sum = (5.5+2j)

18
Write a program to add, subtract, multiply and division of two complex numbers.

print("Addition of two complex numbers : ",(4+3j)+(3-7j))


print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",(4+3j)*(3-7j))
print("Division of two complex numbers : ",(4+3j)/(3-7j))

(a+bj)+(c+dj)=(a+c)+(b+d)j
(a+bj)-(c+dj)=(a-c)+(b-d)j
(a+bj)(c+dj)=(ac-bd)+(ad+bc)j
(a+bj)/(c+dj)=((ac+bd)+(bc-ad)j)/(c2+d2)

19
Addition of complex numbers
#Program with generic input 3+8j
x=complex(input()) 2+3j
y=complex(input()) The sum is: (5+11j)
z=x+y
print("The sum is: ",z)

#Improved input() Enter the first complex number:4+6j


x=complex(input("Enter the first complex number:")) Enter the first complex number:2+8j
print(x) The sum is: (6+14j)
y=complex(input("Enter the first complex number:"))
print(y)
z=x+y
print("The sum is: ",z)

20
Representing Binary, Octal and Hexadecimal Numbers

• Binary Number: 0b or 0B(prefix)


• Example: 0b1010111
• Hexadecimal Number: 0x or 0X(prefix)
• Example:0XAB87
• Octal Number: 0o or 0O(prefix)
• Example:0o775

21
Converting the datatypes explicitly
Type conversion or coercion - Examples
x=15.56
int(x) # will display 15

num =15
float(num) # will display 15.0

n=10
complex(n) # will display (10+0j)

a= 10
b=-6
complex(a,b) # will display (10-6j)

22
Program to convert numbers from octal, binary and hexadecimal to decimal

#Program to convert into decimal number system


n1 = 0O17
n2 = 0B1110010
n3 = 0x1c2 Output
Octal 17 = 15
Binary 1110010 = 114
n = int(n1) Hexadecimal 1c2 =450
print('Octal 17 = ',n)
n = int(n2)
print('Binary 1110010 = ',n)
n = int(n3)
print('Hexadecimal 1c2 = ',n)

23
int(string,base)

str = "1c2" # string str contains a hexadecimal number


n = int(str, 16) # hence base is 16. Convert str to int
print(n) # this will display 450

24
Rewrite the Program to convert numbers from octal, binary and hexadecimal to decimal
using int(string,base) function
#Program to convert into decimal number system – v2.0
s1 = "0O17"
s2 = "0B1110010" Output
Octal 17 = 15
s3 = "0x1c2"
Binary 1110010 = 114
Hexadecimal 1c2 =450
n = int(s1,8)
print('Octal 17 = ',n)
n = int(s2,2)
print('Binary 1110010 = ',n)
n = int(s3,16)
print('Hexadecimal 1c2 = ',n)
25
Conversion to Decimal
s1=input()
n = int(s1,8) 45
print('Octal to decimal= ',n) Octal to decimal= 37
10110
s2=input() Binary to decimal= 22
n = int(s2,2) A14
print('Binary to decimal= ',n) Hexadecimal to decimal = 2580

s3=input()
n = int(s3,16)
print('Hexadecimal to decimal = ',n)

#Try the code given below


s4=input()
n=int(s4,10)
print("Decimal",n) 26
Program to convert numbers to octal, binary and hexadecimal

a = 15 a = int(input('Enter a decimal number\n'))


b = bin(a) b = bin(a)
print(b) print('The Binary equivalent is: ',b)
b=oct(a) b=oct(a)
print(b) print('The Octal equivalent is: ',b)
b=hex(a)
b=hex(a)
print('The Hexadecimal equivalent is: ',b)
print(b)
#Try print('The Hexadecimal equivalent is: ',b.upper())
0b1111
0o17
0xf

27
bool Datatype
• Boolean values (True or False represented as 1 or 0)
• A blank string "" is represented as False
• Conditions will be evaluated internally to True or False

Example1:
a = 10
b = 20
if(a<b):
print("Hello") # displays hello

Example2:
a = 10>5 # here 'a' is treated as bool type vairable
print(a) # displays True

28
Write the output of the following code
a = 5 > 10
print(a)
print(True + True)
print(True – False)

Output
False
2
1

29
Sequences
• Sequence represents a group of elements or items.
• Types of Sequences
• str
• bytes
• bytearray
• list
• tuple
• range

30
str datatype

• String is a group of characters


• Strings are enclosed in single or double quotes
• Strings can also be written inside triple double quotes(""") or triple single quotes(''') to span a group of
lines including spaces.
• The triple double quotes or triple single quotes are useful to embed a string inside another string.

Ex:
str = """This is 'Core Python' string example"""
print(str) # will display This is 'Core Python' string example

str = '''This is "Core Python" string example'''


print(str) # will display This is "Core Python" string example

31
Slice Operator([ and])
Example:
s = 'Welcome to Core Python' # this is the original string
print(s)
Welcome to Core Python

print(s[0]) # display 0th character from s


W

print(s[3:7]) # display from 3rd to 6th character from s


come

print(s[11:]) # display 11th characters onwards till end


Core Python

print(s[-1]) # display first character from the end


n

Repetition Operator(*) - Example:


print(s*2)
Welcome to Core PythonWelcome to Core Python 32
str datatype Cont.
Example:
s = " Welcome to Python" n
print(s[-1]) yth
print(s[-5:-2]) WELCOME TO PYTHON
print(s.upper()) welcome to python
print(s.lower()) Welcome to Python
print(s.strip())#to remove any leading or trailing white spaces
Thanks to Python
print(s.replace("Welcome","Thanks"))
gs ="Hai,How are you" ['Hai,How', 'are', 'you']
print(gs.split()) ['Hai', 'How are you']
print(gs.split(",")) ecm oPto
print(s[::2])
nohtyP ot emocleW
#Try the following
print(s[::-1])
33
String Concatenation

s1 = "Hai,"
s2 = "How are you" Output
s3 = s1 + s2 Hai,How are you
print(s3)

s1 = "Hai"
Output
s2 = "How are you"
Hai How are you
s3 = s1 +" "+s2
print(s3)

34
bytes datatype
 The bytes datatype represents a group of byte numbers
 A bytenumber is any positive integer from 0 to 255(inclusive)
 bytes array can store numbers in the range 0 to 255 and it cannot even store negative numbers
 We can not modify or edit any element in the bytes type array

Example:
elements = [10, 20, 0, 40, 15] # this is a list of byte numbers
x = bytes(elements) # convert the list into byte array
print(x[0]) # display 0th element, i.e 10

Example:
elements = [10, 20, 0, 40, 15] #this is a list of byte numbers
elements[0]=30
Output
print(elements[0])
30
x = bytes(elements) #convert the list into byte array 30
print(x[0]) #display 0th element, i.e 10 x[0] = 23
x[0] = 23 TypeError: 'bytes' object does not support item assignment
print(x[0])
35
Write a program to create a byte type array, read and display the elements
of the array
Output
#create a list of byte numbers 10
20
elements = [10, 20, 0, 40, 15]
0
#convert the list into bytes type array 40
x = bytes(elements) 15
#retrieve elements from x using for loop and display
for i in x:
print(i)
Traceback (most recent call last):
File "C:/Users/admin/Downloads/series1.py", line 4, in <module>
#create a list of byte numbers x = bytes(elements)
elements = [10, 320, 0, 40, 15] ValueError: bytes must be in range(0, 256)
#convert the list into bytes type array
x = bytes(elements)
#retrieve elements from x using for loop and display
for i in x:
print(i) 36
bytearray datatype
• The bytearray datatype is similar to bytes datatype.
• The difference is that the bytes type array can not be modified but the bytearray can be modified.

Creation of bytearray - Example


elements = [10, 20, 0, 40,15] #this is a list of byte numbers Output
88
x = bytearray(elements) #convert the list into bytearray type array
99
print(x[0]) #display 0th element, i.e 10 0
x[0] = 88 #replace 0th element by 88 40
15
x[1] = 99 #replace 1st element by 99
#retrieve elements from x using for loop and display
for i in x:
print(i)

37
What is the output of the following program?
elements = [10, 20, 0, 40,15]
x = bytearray(elements)
print(x[0]) #display 0th element, i.e 10
x[0] = 88
x[1] = 299
for i in x:
print(i)

10
Traceback (most recent call last):
File "C:/Users/admin/Desktop/Pythonprograms/bytearray datatype.py", line 5, in
<module>
x[1] = 299 #replace 1st element by 299
ValueError: byte must be in range(0, 256)
38
list datatype
• A list represents a group of elements
• List can store different types of elements
• Lists can grow dynamically in memory
Examples
list = [10, -20, 15.5, 'Vijay',"Vishal"] Output
[10, -20, 15.5, 'Vijay',"Vishal"]
print(list)
10
print(list[0]) [-20,15.5]
Vijay
print(list[1:3])
[10, -20, 15.5, 'Vijay',"Vishal“, 10, -20, 15.5, 'Vijay',"Vishal"]
print(list[-2]) [-20, 15.5, 'Vijay',"Vishal“]
print(list * 2)
print(list[1:])

39
tuple Datatype
• Similar to list
• Contains group of elements which can be of different types
• The elements are separated by commas and enclosed in parentheses ()
• It is not possible to modify the tuple elements
• Can be treated as a read-only list
Example
tpl = (10, -20, 15.5, 'Vijay',"Vishal")
tpl[0] = 99 =>This will result in error

The slicing operations which can be done on list are also valid in tuples.

40
range Datatype
• Represents a sequence of numbers
Output
• The numbers in the range are not modifiable
range(0, 10)
• Range is used for repeating a for loop for a specific number of times 0
Example 1
r = range(10) # To create a range of numbers 2
print(r) 3
# range object is created with numbers starting from 0 to 9 4
for i in r: 5
print(i) # will display numbers from 0 to 9 6
7
8
r = range(30,40,2) # starting number is 30 and ending number is 39 9
for i in r:
print(i) # will display 30,32,34,36,38

lst = list(range(10)) # Convert to list


print(list) # will display [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

41
Sets

• An unordered collection of elements


• The order of elements is not maintained in the sets
• The elements may not appear in the same order as they are entered into
the set
• A set does not accept duplicate elements
• Sub types:
• set datatype
• frozenset datatype

42
set Datatype
Creation of set
s = {10,20,30,20,50}
print(s) #may display {50, 10, 30, 20}

ch=set("Hello")
print(ch) #may display{'H', 'e' , 'l', 'o‘}

lst =[1, 2, 5, 4, 3]
s = set(lst)
print(s) #may display {1, 2, 3, 4, 5}

fruitset = {"apple", "orange", "grapes"} Output


print("banana" in fruitset) False
print("grapes" in fruitset) True

43
Set datatype Cont.
print(s[0]) # indexing will give error
print(s[0:2]) #slicing will give error

The update() method


Output
s = {10,20,30,20,50}
{0, 1, 2, 3, 4, 5, 6, 8}
s.update([50,60]) {2, 4}
print(s) #may display {10, 20, 30,50,60} {0,1,3,5}

s.remove(50)
print(s) #may display {10, 20, 30, 60}

a = {0, 1, 2, 3, 4, 5}
b ={2, 4, 6, 8}
print (a.union(b))
print (a.intersection(b))
print(a.difference(b))
44
frozenset Datatype
• Similar to set datatype
• But the elements can not be modified in frozenset
Example:
s = {50, 60, 70, 80, 90}
print(s) #may display {80, 90, 50, 60, 70}

fs = frozenset(s) #create frozenset fs


print(fs) # may display frozenset( {80, 90, 50, 60, 70} )

fs = frozenset("abcdefg")
print(fs) # may display frozenset( {'e', 'g', 'f', 'd', 'a', 'c', ' b'})

NOTE: update() and remove() will not work on frozenset

45
Mapping Types
• Represents a group of elements in the form of key value pairs so that
when the key is given, the value associated with it can be retrieved.
• dict datatype(Dictionary) is a Mapping Type

Example 1 :
d = {10:'a' , 11:'b', 12: 'c'}
print(d) # will print {10:'a' , 11:'b', 12: 'c'}
print(d[11]) # will print b

46
dict datatype

Example 2 :
Output
d = {} dict_keys([4, 3])
d[4] ='example' dict_values(['example', 'string'])
d[3]='string' {4: 'example', 3: 'string'}
print(d.keys())
print(d.values())
print(d)

47
Literals in Python
• Literal is a constant value stored into an object in a program.

48
Determining the datatype of the variable

a= 15
print(type(a))

<class 'int'>

49
Write a Python program to display the first and last colors from the following list.

color_list = ["Red","Green","White" ,"Black"]

Solution
color_list = ["Red","Green","White" ,"Black"]
print( color_list[0])
Print(color_list[-1])

50
a. Create a list "lst" containing integers: 1, 2, 3, 4, 5
b. Use list indexing to select the second item in the list.
c. Use list indexing to select the third to last item in the list.
d. Use list slicing to select the first to the third item in the list.

lst = [1, 2, 3, 4, 5]
print (lst[1])
print (lst[-3])
print(lst[1:4])

51
a. Create a list "one_to_ten" with values from 1 to 10
b. Replace the first item in the list with the value 10.
c. Append the number 11 to the list.
d. Add another list ([12, 13, 14]) to the list using the "extend" method.

one_to_ten =list(range(1, 11))


one_to_ten[0] = 10
one_to_ten.append(11)
one_to_ten.extend([12, 13, 14])
print (one_to_ten)

52
a. Create a tuple named "t" containing one integer 1.
b. Use indexing to print the last value of the tuple.
c. Create a tuple containing all values from 100 to 200.
d. Print the first and the last items in the tuple.

t = (1)
print (t[-1])
l = range(100, 201)
tup = tuple(l)
print( tup[0], tup[-1])

53
a. Create a string "s" with the value "I love to write code".
b. Loop through "s" displaying each value.
c. Print the 5th element of "s".
d. Print the last element of "s".
e. Print the length of "s".

s = "I love to write code"


for i in s:
print (i)
print (s[5])
print (s[-1])
print (len(s))

54
a. Create a list called "a" containing values: [0, 1, 2, 3, 4, 5]
b. Create a list called "b" containing values: [2, 4, 6, 8]
c. Print the unique elements of the two lists.
d. Print the common elements of the two lists.

a = set([0, 1, 2, 3, 4, 5]) Output


b = set([2, 4, 6, 8]) c: {0, 1, 2, 3, 4, 5, 6, 8}
c=a.union(b) common elements: {2, 4}
print("c: ",c) unique elements: {0, 1, 3, 5, 6, 8}
d=a.intersection(b)
print("common elements: ",d)
print ("unique elements: ",c.difference(d))

55
Write a Python program to check whether an element exists within a tuple.

tuplex = ("x", 4, "r", "e", "s", "o", "u", "r", "c", "e")
print("r" in tuplex)
print(5 in tuplex)

True
False

56
a. Create a list "band" with the members: ["mel", "geri", "victoria“,"mel", "emma"]
b. Create an empty dictionary called "counts".
c. Loop through each member of "band".
d. Inside the loop: when a name is seen for the first time add an item to the dictionary with the name as
the key and 1 as the value.
e. Inside the loop: if a name has already been seen then add 1 to the dictionary item to indicate that it has
been spotted again.
f. Loop through the dictionary printing the key and value of each item.
g. Display the dictionary

band = ["mel", "geri", "victoria", "mel", "emma"] Output


counts = {} mel 2
for name in band: geri 1
if name not in counts: victoria 1
counts[name] = 1 emma 1
else: {'mel': 2, 'geri': 1, 'victoria': 1, 'emma': 1}
counts[name] += 1
for name in counts:
print(name, counts[name])
print(counts)
57
Operators
• Arithmetic operators
• Assignment operators
• Unary minus operators
• Relational operators
• Logical operators
• Boolean operators
• Bitwise operators
• Membership operators
• Identity operators

58
Arithmetic Operators
Operator Meaning Result with
a = 12
b=5
+ Addition 17
- Subtraction 7
* Multiplication 60
/ Division 2.4
% Modulus 2
** Exponent 248832
// Integer division(Also called floor division) 2
Performs division and gives only integer quotient

59
Using Python Interpreter as Calculator
>>> 13+5
18
>>>13//5
2
>>>d =(1+2)*3**2//2+3
>>>print(d)
16

60
Assignment Operators Unary Minus Operator

Operators n = 10
Assignment = print(-n)
(Shorthand +=
assignment) -= num = -10
*= num = -num
/= print(num)
%=
**= -10
//= 10

61
Relational Operators

Operators
> Examples
print(1<2<3<4) True
>= print(1<2>3<4) False
< print(4>2>=2>1) True
<=
==
!=

62
Logical Operators
Operator Example Meaning Result for x=1, y=2
and x and y If x is false, it returns x, otherwise it returns y 2
or x or y If x is false, it returns y, otherwise it returns x 1
not not x If x is false, it returns True, otherwise False False

x = 100
y= 200 Output
print(x and y) 200
print(x or y) 100
print(not x) False
Yes
x=1 ; y=2; z=3
if(x<y and y<z):
print('Yes')
else:
print('No') 63
Boolean Operators

Operator Example Meaning Result for


x=True and y=False
and x and y Boolean and operator False
or x or y Boolean or operator True
not not x Boolean not operator False

64
Bitwise Operators
• Bitwise Complement operator(~)
• Bitwise AND operator(&)
• Bitwise OR operator(|)
• Bitwise XOR operator(^)
• Bitwise Left shift operator(<<)
• Bitwise Right shift operator(>>)

65
Bitwise Operator Examples
x=10 , y=11
x = 0000 1010
y = 0000 1011
Operator Result for x=10 , y=11
x&y => 0000 1010
~x -11 (1111 0101) 0000 1011
x&y 10 (0000 1010) 0000 1010
x|y 11 (0000 1011) x^y => 0000 1010
x^y 0000 1011
1 (0000 0001) 0000 0001
x << 2 40 (0010 1000)
x >> 2 2 (0000 0010) x 0000 1010
x << 2 0010 1000

66
Membership Operators
• Useful to test for membership in a sequence such as strings, lists, tuples or dictionaries.
• Operators : in, not in
Example Vijay
names = ["Vijay", "Raj", "Sunitha"] Raj
for name in names: Sunitha
print(name)

67
Identity Operators
• is
• is not
• Memory location of an object can be seen using the id() function

Example
a = 25
b = 25 Output
if(a is b): a and b have same identity
print("a and b have same identity/Location") 1671955954
else: 1671955954
print("a and b do not have same identity/location")
print(id(a))
print(id(b))

68
Identity Operator
one = [1, 2, 3, 4]
two = [1, 2, 3, 4]
three =two
if(one is two):
print("one and two are same")
else:
print("one and two are not same")
print("Location of One",id(one))
print("Location of Two",id(two))
print("Location of Three",id(three))

Output
one and two are not same
Location of One 2551344500096
Location of Two 2551304355456
Location of Three 2551304355456
69
Determining the datatype of the variable
a= 15
print(type(a))

Output
<class 'int'>

70
Operator Precedence
Operator Name
() Parenthesis
** Exponentiation
-, ~ Unary minus, Bitwise Complement
*, / , //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise left shift, Bitwise right shift
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
>, >=, <, <=, ==, != Relational(Comparison) operators
=, %=, /=, //=, -=, +=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not Logical not
or Logical or
and Logical and 71
Mathematical Functions

import math
x= math.sqrt(16)

import math as m
x=m.sqrt(16)

from math import sqrt

from math import factorial, sqrt

Note: import cmath to handle complex numbers

72
Important Math Functions
Function Input value Result
ceil(x) 30.34 31 1 radian =57.2957795 degrees
floor(x) 30.34 30
1 degree =0.01745329 radians
degrees(x) 0.0174532925239283986 1.0000000002283296
radians(x) 57.29577951308232 1
sin(x) 0 0.0
cos(x) 0 1.0
tan(x) 0 0.0
trunc(x) 30.34 30
factorial(x) 4 24
fmod(x,y) 8,3 2.0
fsum(values) [2.3,4,5.6] 11.899999999999999
pow(x,y) 2,3 8
gcd(x,y) 21,7 7
73
Constants in math module

Example : math.pi(3.141592…) , math.e(2.718281…)

74
Input : ['yellow', 'blue', 'red' , 'blue', 'white']
Expected output: {'yellow': 1, 'blue': 2, 'red': 1, 'white': 1}

colours= ['yellow', 'blue', 'red' , 'blue', 'white']


Output
counts = {} {'yellow': 1, 'blue': 2, 'red': 1, 'white': 1}
for name in colours:
if name not in counts:
counts[name] = 1
else:
counts[name] += 1

print(counts)

75
Write a program to check whether the given string in symmetric

st=input()
l=len(st)
if (l%2 ==0):
if ( st[:(l//2)]==st[(l//2):]):
print("String is symmetric")
else:
print("String is not symmetric")
else:
print("String is not symmetric")

76
Write a program to check whether the given string in symmetric

st=input()
if (st[::]==st[::-1]):
print("Palindrome")
else:
print("Not a
Palindrome")

77
('x', 4, 's', 'o', 'u', 'r', 'c', 'e ')

Write a Python program to remove an item from a tuple.


#create a tuple
tuplex = ("x", 4, "r", "s", "o", "u", "r", "c", "e ")
print(tuplex)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it will create a new tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)

('x', 4, 'r', 's', 'o', 'u', 'r', 'c', 'e')


('x', 4, 's', 'o', 'u', 'r', 'c', 'e')
#converting the tuple to list
tuplex = ("x", 4, "r", "s", "o", "u", "r", "c", "e ")
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("r") ('x', 4, 's', 'o', 'u', 'r', 'e')
#converting the list to tuple
tuplex = tuple(listx)
print(tuplex)
78
Output Statements

• print()
• A blank line will be displayed
• print("string")
• The string is displayed as it is

79
print(variables list)
a, b = 2, 4
print(a) # will print 2
print(a, b) # will print 2 4

print(a,b,sep=",") # will print 2,4


print(a,b,sep=":") # will print 2:4
pri nt(a,b,sep="---- ") # will print 2---- 4

80
print(variables) - Cont.
print("Hai", end='')
print("Hello", end='')
print("How are you?", end='')
Output
HaiHelloHow are you?

print("Hai", end='\t')
print(“Hello", end='\t')
print("How are you?", end='\t')

Output
Hai Hello How are you?

Note : \n is default end attribute

81
#print(object)
lst = [10, "Hai", 20.5]
print(lst) [10, 'Hai', 20.5]

#print(string, variable list) 10 is a even number


a=10
print(a, "is a even number") You typed 10 as input
print('You typed' ,a, 'as input')
Value of x = 10
Value of x = %d 10
#print(formatted string) x = 10 y=315.55
print(" Formatted String " % (variable list))

x = 10
print('Value of x = %i' % x)
print('Value of x = %d',x)
y=315.545
print('x = %i y=%0.2f' %(x,y))
82
name = 'Anusha'
print('Hai %s ' % name)
print('Hai (%20s) ' % name) # for right alignment print with parenthesis; Try with numbers
print('Hai (%-20s) ' % name) # for left alignment print with parenthesis

print('Hai %c, %c ' % (name[0], name[1]))

print('Hai %s' % (name[0:2]) Output


Hai Anusha
Hai ( Anusha)
num = 123.456789 Hai (Anusha )
print('The value is %f ' % num) Hai A, n
Hai An
print('The value is %.2f ' % num)
The value is 123.456789
print('The value is %8.2f ' % num) The value is 123.46
The value is 123.46

83
print('format string with replacement fields'.format(values))

n1, n2, n3 = 1, 2, 3
print('number1={0}, number2={1}, number3={2} '.format(n1,n2,n3))
O/P : number1=1, number2=2, number3=3

print('number1={1}, number2={0}, number3={2} '.format(n1,n2,n3))


O/P : number1=2, number2=1, number3=3

print('number1={two}, number2={one}, number3={three} '.format(one=n1,two=n2,three=n3))


O/P : number1=2, number2=1, number3=3

print('number1={}, number2={}, number3={} '.format(n1,n2,n3))


O/P : number1=1, number2=2, number3=3

84
name, salary = 'Anusha', 15500.75
print('Hello {0}, your salary is {1}'.format(name, salary))
print('Hello {n}, your salary is {s}'.format(n=name, s=salary))
print('Hello {:s}, your salary is {:.2f}'.format(name, salary))
print('Hello %s, your salary is %f' % (name, salary))

Output
Hello Anusha, your salary is 15500.75
Hello Anusha, your salary is 15500.75
Hello Anusha, your salary is 15500.75
Hello Anusha, your salary is 15500.750000

85
Input Statements
input() function takes a value from the keyboard and returns it as a string
str = input()
print(str)

str=input('Enter your Name: ')


Enter your Name:

str=input('Enter a Number: ')


Enter a Number : 10
x=int(str)
print(x)

x=int(input('Enter a Number: '))


Enter a Number : 10
print(x)

x=float(input('Enter a Number: '))


Enter a Number : 10.7
print(x)
86
Write a program to accept two numbers and find their sum and product.

# find sum and product of two numbers


x = int(input('Enter first number: '))
y = int(input('Enter first number: '))
# display sum
print('The sum of {0} and {1} is {2} '.format(x, y, x+y))
# display product
print('The product of {0} and {1} is {2} '.format(x, y, x*y))
# display both sum and product
print('The sum of {0} and {1} is {2} and product of {0} and {1} is {3} '.format(x, y, x+y, x*y) )

Sample Output
Enter first number: 50
Enter second number: 40
The sum of 50 and 40 is 90
The product of 50 and 40 is 2000
The sum of 50 and 40 is 90 and product of 50 and 40 is 2000
87
Write a program to convert numbers from other systems into decimal number system.

# input from other number systems


str = input('Enter hexadecimal number: ')
n = int(str,16)
print('Hexadecimal to Decimal= ',n)

str = input('Enter octal number: ')


n = int(str,8)
print('Hexadecimal to Decimal= ',n)

str = input('Enter binary number: ')


n = int(str,2)
print('Hexadecimal to Decimal= ',n)

88
Example 1:
input_str = input("Enter elements of the tuple separated by comma: ")
print(type(input_str))
my_seq= tuple(input_str.split(',')) #splits a string into a tuple
print(my_seq)
Enter elements of the tuple separated by comma:
print(type(my_seq))
45,67,88,40
<class 'str'>
('45', '67', '88', '40')
<class 'tuple'>

Example 2:
# Taking input as a string using input function
input_str = input("Enter elements of list separated by space: ")
a=input_str.split()
print(a)
print([int(x) for x in a])#List comprehension Enter elements of list separated by space: 45 56 67
['45', '56', '67']
print(list(map(int,a))) #tuple(map(int,a)) [45, 56, 67]
[45, 56, 67]

89
To accept more than one input in the same line, we can use a for loop along with the input() function in the
following format.

a, b = [int(x) for x in input("Enter two numbers:" ).split()]

# Accepting 3 numbers separated by space


var1, var2, var3 = [int(x) for x in input("Enter three numbers: ").split()]
print(' Sum = ' , var1 + var2 + var3)

# Accepting 3 numbers separated by comma


var1, var2, var3 = [int(x) for x in input("Enter three numbers: ").split(', ')]
print(' Sum = ' , var1 + var2 + var3)

# Accepting a group of strings separated by comma


lst= [x for x in input("Enter strings: ").split(', ')]
print(' You entered = \n ' , lst) # lst will be printed as a list

my_list1 = tuple(map(int, input("Enter elements of the list separated by space: ").split()))


# Printing the list
print("Tuple:", my_list1)

90
eval() function – Used in two different ways
a, b = 5, 10
result = eval("a + b -4")
print(result)

Write a Program to evaluate an expression entered from keyboard


# using eval() along with input() function
x = eval(input("Enter an expression: "))
print("Result = %d" %x)

Output(Sample)
Enter an expression: 2*(3**2)/3
Result = 6

91
# accepting a list from keyboard
lst = eval(input("Enter a list: "))
print("List = ",lst)
Output
Enter a list: [ 10, 20, 'Akshay']
List = [ 10, 20, 'Akshay']

# accepting a tuple from keyboard


tpl = eval(input("Enter a tuple: ")) #default input type is tuple when more than one
value is provided
print("Tuple = ",tpl)

Output
Enter a tuple: (1, 2, 3)
Tuple = (1, 2, 3)
92
d = eval(input("Enter a dictionary: ")) d = eval(input("Enter a set: "))
print("Dictionary = ",d) print("set = ",d)
print(type(d)) print(type(d))
print(d.keys())
print(d.values())

Sample Output:
Enter a set: {4,'t',8}
Enter a dictionary: {'a':'apple',1:'one'}
set = {8, 't', 4}
Dictionary = {'a': 'apple', 1: 'one'}
<class 'set'>
<class 'dict'>
dict_keys(['a', 1])
dict_values(['apple', 'one'])

93
Control Statements
if condition:
statement

Ex:
num =1
if num==1:
print("One")

Ex:
str= "Yes"
if str == "Yes" :
print("Yes")
print("This is what you said")
print("Your response is good")
94
Ex:
if x==1:
print('a') x=1, y=0 x=1, y=2 x=0, y=2
print('b')
if y == 2:
print('c')
print('d')
print('end')

Effect of Indentation
Output when x=1, y=0 Output when x=1, y=2 Output when x=0, y=2
a a end
b b
end c
d
end

95
Ex:
# To accept a number from keyboard and test whether it is is even or odd
x= int(input("Enter a number: "))
if x%2 == 0:
print(x, "is even number")
else:
print(x, " is not an even number")

Write a program to test whether a given number is in between 1 and 10

# program to test whether a given number is in between 1 and 10


x= int(input("Enter a number: "))
if x>=1 and x<=10:
print("You typed", x, "which is between 1 and 10")
else:
print("You typed", x, "which is below 1 or above 10")

96
Ex:
# To know if a given number is zero, positive or negative
num = -10
if num == 0:
print(x, "is zero")
elif num>0:
print(x, " is positive")
else:
print(x, " is negative") # else part not compulsory

97
# Program to display numbers from 1 to 10 using while loop
x=1
while x<=10:
print(x)
x+=1
print("End")

What will be the output of the following program?

# Program to display numbers from 1 to 10 using while loop


x=1
while x<=10:
print(x)
x+=1
print("End")

98
Write a program to display even numbers between m and n using while loop.

# To display even numbers between m and n


m, n =[int(i) for i in input("Enter minimum and maximum range: ").split(',' )]
x= m
if x%2 !=0 :
x=x+1
while x>=m and x<=n:
print(x)
x+=2

99
Example – For loop
#To display each character from a string using sequence index
str='Hello'
n=len(str)
for i in range(n):
print(str[i])

Write a program to display odd numbers from 1 to 10 using range object


#To display odd numbers from 1 to 10 using range object
for i in range(1,10,2):
print(i)

Write a program to display odd numbers from 10 to 1 in descending order

#To display odd numbers from 10 to 1


for x in range(10,0,-1):
print(x)
100
Nested Loop

for i in range(3):
for j in range(4):
print('i=',i, '\t', 'j=', j)

Output
i= 0 j= 0
i= 0 j= 1
i= 0 j= 2
i= 0 j= 3
i= 1 j= 0
i= 1 j= 1
i= 1 j= 2
i= 1 j= 3
i= 2 j= 0
i= 2 j= 1
i= 2 j= 2
i= 2 j= 3
101
Write a program to display the following output.

*
**
***
****
*****
******
*******
********
*********
**********

# To display stars in right angled triangular form


for i in range(1, 11):
for j in range(1, i+1):
print('* ', end=' ')
print( )

102
Write a program to display stars in right angled triangular form using a single loop.

# To display stars in right angled triangular form


for i in range(1, 11):
print('* ' *(i))

103
Write a program to display the stars in the following form using single loop

*
**
***
****
*****
******
*******
********
*********
**********

104
# to display stars in equilateral triangular form
*
n=20 **
for i in range(1, 11): ***
****
print(' '*n, end='') # repeat space for n times *****
******
print('* '*(i)) # repeat stars for i times *******
n-=1 ********
*********
**********

# to display stars in equilateral triangular form


n=20
for i in range(1, 11):
print(' '*(n-i) + '* '*(i))

105
Write a program using nested loops to display numbers in the following two formats.

# to display numbers in rows and columns


for x in range(1,11):
for y in range(1,11):
print(x*y,end=' ' )
print()

106
The else Suite
Example : for with else
for i in range(5):
print('Yes')
else:
print('No')

Output
Yes
Yes
Yes
Yes
Yes
No
107
# A Program to search for an element in the list of elements
group1 = [1, 2, 3, 4, 5]
search = int(input("Enter element to search:"))
for element in group1:
if search == element:
print("Element found in group1")
break
else:
print("Element not found in group1")

108
Write a program to display only negative numbers of a list
# Retrieving only negative numbers from a list
num = [10, 20, -40, 80, 90, -100]
for i in num:
if (i>0):
pass #we are not interested
else:
print(i) # this is what we need

Output
-40
-100

109
#Using pass statement to do nothing
x=0
while x <10:
x+=1
if x>5:
pass
print('x = ',x)
print("Out of loop")

Output
x= 1
x= 2
x= 3
x= 4
x= 5
x= 6
x= 7
x= 8
x= 9
x = 10
Out of loop
110
The assert statement

• To check if a particular condition is fulfilled or not


• Syntax
assert expression, message #message is optional

111
# Program to assert that the user enters a number greater than zero
x = int(input("Enter a number greater than 0: "))
assert x>0, "Wrong input entered"
print("You entered: ",x)

Enter a number greater than 0: 10


You entered: 10

Enter a number greater than 0: -45


Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/assertstatement.py", line 3, in
<module>
assert x>0, "Wrong input entered"
AssertionError: Wrong input entered

112
# To handle Assertion Error raised by assert
x = int(input("Enter age (greater than 0):"))
try:
assert(x>0)
print('You entered: ',x)
except AssertionError:
print("Wrong input entered")

Output
Enter a number greater than 0:-20
Wrong input entered

113
Arrays
• An object that stores a group of elements of same data type.
• Can increase or decrease their size dynamically.
• We need not declare the size of the array.
• Array is the standard module to support array

114
Creating an Array
arrayname = array(type code, [elements])

Typecode C Type Minimum size in bytes


'b' signed integer 1
'B' unsigned integer 1
'i' signed integer 2
'I' unsigned integer 2
'l' signed integer 4
'L' unsigned integer 4
'f' floating point 4
'd' double precision floating point 8
'u' unicode character 2

115
Creating Integer type Array # Creating a character type array
# Creating an array from array import *
import array a = array('u', ['a', 'e', 'i', 'o', 'u'])
ar=eval(input("Enter the elements of integer array as a list: ")) print('The array elements are: ')
a = array.array('i', ar) for element in a:
print("type of a",type(a)) print(element)
print('The array elements are: ')
for element in a:
print(element)

Enter the elements of integer array as a list: [4,5,6,9,3]


type of a <class 'array.array'>
The array elements are:
4
5
6
9
3

116
# Creating an array
from array import *
a = array('d', [1.5, 3.5,10.11,10])
b = array(a.typecode,(elt for elt in a)) # All elements of a will be stored in b
c = array(a.typecode,(elt*3 for elt in a)) # Elements of c are 4.5, 10.5,30.33,30.0
print('The array elements are: ')
for element in a:
print(element)
for ele in b: The array elements are:
print(ele) 1.5
for elt in c: 3.5
print(elt) 10.11
10.0
1.5
3.5
10.11
10.0
4.5
10.5
30.33
30.0

117
# Accessing Array elements using index
from array import *
a = array('i', [10, 15,18,50, 90,120, 13, 55])
n = len(a)

print('The array elements are: ')


for i in range(n):
print(f'a[{i}]={a[i]}') #formatted string literals

The array elements are:


a[0]=10
a[1]=15
a[2]=18
a[3]=50
a[4]=90
a[5]=120
a[6]=13
a[7]=55
118
a = array('i', [10, 15, 18, 50, 90, 120, 13,30])
1. Create array b with elements from 1st to 3rd from a
2. Create array b with elements from 0th to last element in a
3. Create array b with elements from 0th to 3rd from a
4. Create array b with last 4 elements from a
5. Create array b with elements from 0th to 7th element extracting only alternate elements
from array import *
a = array('i', [10, 15, 18, 50, 90, 120, 13,30])
b = a[1:4]
print(b) # will print array('i', [15, 18, 50])
b = a[0:]
print(b)
b=a[:4]
print(b)
b=a[-4:]
print(b)
b=a[0::2]
print(b) 119
Processing in Arrays

Methods
a.append(x) a.pop(x)
a.count(x) a.pop()
a.extend(x) a.remove(x)
a.fromlist(lst) a.reverse()
a.fromstring(s) a.tolist()
a.index(x) a.tostring()
a.insert(i,x)
Variables
a.typecode a.itemsize

120
#Program to sort the array elements using bubble sort
from array import *
x = array('i',[])
print('How many elements', end='') Output
n = int(input()) How many elements 7
for i in range(n): Enter element: 5
print('Enter element: ',end='') Enter element: -4
x.append(int(input())) Enter element: 3
print('Original Array:', x) Enter element: 2
flag = False Enter element: 6
for i in range(n-1): Enter element: 11
for j in range(n-1-i): Enter element: -3
if x[j] > x[j+1]: Original Array: array('i', [5, -4, 3, 2, 6, 11, -3])
t = x[j] Sorted Array= array('i', [-4, -3, 2, 3, 5, 6, 11])
x[j] = x[j+1]
x[j+1] = t
flag = True
if flag == False:
break
else:
flag = False 121
print('Sorted Array= ',x)
#sequential search
from array import *
x=array('i',[])
print('Enter the number of elements:', end='')
n=int(input())
for i in range(n):
print('Enter element: ',end='')
x.append(int(input()))
print('Original array: ',x)
print('Enter element to search: ',end='')
s=int(input())
flag=False
for i in range(len(x)):
if s==x[i]:
print('Found at position:',i)
flag=True
if flag==False:
print('Not found in the array') 122
#sequential search using index()method
from array import *
x=array('i',[])
print('Enter the number of elements:', end='')
n=int(input())
for i in range(n):
print('Enter element: ',end='')
x.append(int(input()))
print('Original array: ',x)
print('Enter element to search: ',end='')
s=int(input())
try:
pos = x.index(s)
print('Found at position: ',pos)
except ValueError:
print('Not found in the array')
123
Write a program to accept the array elements from the user(note: without using eval())

from array import *


x = array('i',[])
print('How many elements', end='')
n = int(input())
for i in range(n):
print('Enter element: ',end='')
x.append(int(input()))
print(x)

124
Working with Arrays using numpy
# creating single dimensional array
import numpy
a = numpy.array([12,34,56]) or numpy.array([12,34,56], int)
print(a)

# creating single dimensional array


import numpy as np
a = np.array([12,34,56]) or np.array([12,34,56], int)
print(a)

# creating single dimensional array


from numpy import *
a = array([12,34.5,56]) or array([12,34.5,56], float)
print(a) # [12. , 34.5,56.]

s=array(['xyz', 'abc', 'xxx'], dtype=str) or array(['xyz', 'abc', 'xxx‘])


strg=s or strg=array(s) # creating another array, same id for strg and s
125
# creating array using arrange Output
from numpy import *
a = arange(10) [0 1 2 3 4 5 6 7 8 9]
b=arange(5,10) [5 6 7 8 9]
[1 4 7]
c=arange(1,10,3) [10 9 8 7 6 5 4 3 2]
d=arange (10,1,-1) [0. 1.5 3. 4.5 6. 7.5 9. ]
e=arange(0,10,1.5)
print(a)
print(b) a=range(1,10,1)
print(c) print(a)
print(d)
print(e) range(1, 10)

126
from numpy import *
a= array([12.4,5,7])
b=array([3,4,5])
print(a+b)
print(a-b)
print(a*b)
print(a/b)

127
from numpy import *
a= array([12.4,5,7])
b=array([3,5,1]) [False True False]
c = a==b [ True False True]
[False True False]
print(c)
<class 'numpy.ndarray'>
c= a>b <class 'numpy.ndarray'>
print(c) <class 'numpy.ndarray'>
c= a<= b
print(c)
print(type(a))
print(type(b))
print(type(c))

128
# reshape function
Output
from numpy import * [1 2 3 5 6 2]
[[1 2 3]
a=array([1,2,3, 5,6,2]) [5 6 2]]
b=reshape(a,(2,3)) [[1 2]
[3 5]
c=reshape(a,(3,2))
[6 2]]
print(a)
print(b)
print(c)

129
Output
[ 0 1 2 3 4 5 6 7 8 9 10 11]
from numpy import * [[[ 0 1]
[ 2 3]
a=arrage(12) [ 4 5]]
b=reshape(a,(2,3,2))
[[ 6 7]
c=reshape(a,(3,2,2))
[ 8 9]
[10 11]]]

[[[ 0 1]
[ 2 3]]

[[ 4 5]
[ 6 7]]

[[ 8 9]
[10 11]]]
130
# Retrieving the elements from a 2D array using indexing
from numpy import *
Output
[1, 2, 3]
#create a 2D array [5, 6, 2]
[9, 5, 3]
a=[[1,2,3], [5,6,2],[9,5,3]] #a=eval(input())
123562953

#display only rows


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

#display element by element


for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j],end=' ')

131
Write the output of the following program
from numpy import *
a= arange(10,20)
print(a)
a = a[1:10:2] [10 11 12 13 14 15 16 17 18 19]
[11 13 15 17 19]
print(a) 11
13
15
i=0 17
while (i<len(a)): 19

print(a[i])
i+=1

132
create a 3D array with size 2×2×3
from numpy import *
Output
a= array([[[1,2,3],
2
[5,6,2]], 2
[[9,5,3], 3
[10,34,12]]]) 123
2
3
#display element by element
562
for i in range(len(a)):
print(len(a)) 2
for j in range(len(a[i])): 2
print(len(a[i])) 3
953
print(len(a[i][j])) 2
for k in range(len(a[i][j])): 3
print(a[i][j][k],end=' ') 10 34 12
print()
print()
133
from numpy import * Output
arr1 = array([1,2,3,4]) 1
print(arr1.ndim) # 1 (4,)
print(arr1.shape) # (4,) 2
(2, 3)
arr2=array([[1,2,3], [4,5,6]]) [[1 2]
print(arr2.ndim) [3 4]
print(arr2.shape) # r,c=arr2.shape [5 6]]
arr2.shape = (3,2) 4
print(arr2) 6
print(arr2.itemsize) int32
print(arr2.size) 24
print(arr2.dtype)
print(arr2.nbytes)

134
Strings and Characters
#program to check whether sub string is in main string or not
str = input('Enter main string: ')
sub=input('Enter sub string: ')
if sub in str:
print(sub+' is found in main string')
else:
print(sub+' is not found in main string')

135
#removing spaces from the string
name = " Sample string "
print(name)
print(name.rstrip()) #remove spaces at right
print(name)
print(name.lstrip()) #remove spaces at left
print(name)
print(name.strip()) #remove spaces from both sides
print(name)

136
# To find the position of sub string in a main string
str=input('Enter main string: ')
sub=input('Enter main string: ')
n=str.find(sub,0,len(str)) #str.find(sub)
if n == -1:
print('Sub string not found')
else:
print('Sub string found at position', n+1)

# To find the position of sub string in a main string


str=input('Enter main string: ')
sub=input('Enter main string: ')
try:
n=str.index(sub,0,len(str))
except ValueError:
print('Sub string not found')
else:
print('Sub string found at position', n+1)
137
str=input('Enter main string: ')
sub=input('Enter substring: ')
Enter main string: malayalam
i=0 Enter substring: la
flag=False la found at position:3
n=len(str) la found at position:7
while i<n:
pos=str.find(sub,i,n)
Enter main string: malayalam
if pos != -1:
Enter substring: laa
print(f'{sub} found at position:{pos+1}') laa not found
i=pos+1
flag = True
else:
i=i+1
if flag == False:
print(f'{sub} not found') 138
# string operations
str=input('Enter main string: ')
sub=input('Enter main string: ')
print(f"Number of occurences of '{sub}' in '{str}':",str.count(sub))
a=['This','is','an','example']
ajoined=' '.join(a)
print(ajoined)
print(str.lower()) Enter main string: All flowers are beautiful.Rose is beautiful
print(str.upper()) Enter main string: beautiful
print(str.title()) Number of occurences of 'beautiful' in 'All flowers are beautiful.Rose is beautiful': 2
print(str.swapcase()) This is an example
print(str.startswith(sub)) all flowers are beautiful.rose is beautiful
print(str.endswith(sub)) ALL FLOWERS ARE BEAUTIFUL.ROSE IS BEAUTIFUL
All Flowers Are Beautiful.Rose Is Beautiful
aLL FLOWERS ARE BEAUTIFUL.rOSE IS BEAUTIFUL
False
True

139
String Operations
• Finding length
• indexing
• slicing
• Repeating string
• Concatenation
• checking membership
• comparing strings
• removing spaces
• Finding sub strings
• Counting substrings in a string
• replacing a string with another string
• splitting and joining strings [separator.join(str)]
• changing case of string (str.upper(), str.lower(),str.swapcase(),str.title())
• checking starting and ending of string
• Formatting the string
• Sorting strings
• Searching in the string
• Inserting a sub string to a string

140
Write a Python program to compute the distance between the points (x1, y1) and (x2, y2)

import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)

141
Write a program to find the number of items in a list which are not characters.

# Python program to illustrate the use of 'is not' identity operator


list=[5.4,4,5,6,'c','v',10]
count=0
for item in list:
if (type(item) is not str):
count=count+1
print('Number of items which are not characters:',count)

Number of items which are not characters: 5

142
List of programs to practice in Lab (Week2)
1. Write a program that asks the user for a number and then prints
out a list of all the divisors of that number
2. Ask the user for a string and print out whether this string is a
palindrome or not.
3. Write a program that takes a list a and makes a new list that has
only the odd elements of this list in it.
4. Ask the user for a number and determine whether the number is
prime or not.
5. Write a Python program to sort three integers without using
conditional statements and loops.

143
Functions
def functionname(para 1, para 2, …):
""" function docstring """
function statements

Example:
def prod(x,y):
""" This function finds the product of two numbers """
c=a*b
print(c)

#call the function


prod(10,20)
prod(10.5,2.5)

Example:
def prod(x,y):
""" This function finds the product of two numbers """
c=a*b
return c
#call the function
x = prod(10,20)
y = prod(10.5,2.5) 144
Write a program to calculate factorial value of first 10 numbers (Using a user defined function)

# Function to calculate factorial value


def fact(n): Output
'''To find factorial value ''' Factorial of 1 is 1
prod = 1 Factorial of 2 is 2
while n > 1: Factorial of 3 is 6
prod*=n Factorial of 4 is 24
n-=1 Factorial of 5 is 120
return prod Factorial of 6 is 720
Factorial of 7 is 5040
#display factorials of first 10 numbers Factorial of 8 is 40320
for i in range(1,11): Factorial of 9 is 362880
print("Factorial of {} is {}". format(i, fact(i))) Factorial of 10 is 3628800

145
Returning multiple values from a function

def mul_div(a,b):
c=a*b
d = a // b
Output
return c, d Result of multiplication 50
Result of division 2
x, y = mul_div(10, 5)
print("Result of multiplication ", x)
print("Result of division ", y)

146
Returning multiple values from a function
def add_sub_mul_div(a,b):
e=a+b
f=a-b
Output
c=a*b The results are:
d = a // b 15 5 50 2
return e, f, c, d

t = add_sub_mul_div(10,5) #t is of type tuple


print('The results are: ')
for i in t :
print(i,end=' ')

147
Nested Function

# Nested function
Output
def display(str): Enter the name Raj
def message(): How are you Raj
return 'How are you '
result = message()+str
return result

name=input("Enter the name ")


print(display(name))

148
# Passing a function as parameter
def display(fun):
return 'Hai, ' + fun Output
Enter a name Ajit
Hai, Welcome Ajit
def message(inpst):
return ('Welcome '+inpst)

inputstring=input("Enter a name ")


print(display(message(inputstring)))

149
# passing an integer to a function
def modify(x):
x =15 Output
print(x,id(x)) 15 1683941520
10 1683941440

x = 10
modify(x)
print(x,id(x))

150
# passing a list to a function
def modify(lst):
lst.append(10)
print(lst,id(lst)) Output
[1, 2, 3, 4, 10] 60069096
[1, 2, 3, 4, 10] 60069096
lst = [1, 2, 3, 4]
modify(lst)
print(lst,id(lst))

151
# passing a list to a function
def modify(lst):
Output
lst = [10, 20, 30] [10, 20, 30] 56676488
print(lst,id(lst)) [1, 2, 3, 4] 66819432

lst = [1, 2, 3, 4]
modify(lst)
print(lst,id(lst))

152
Formal and Actual Argument

• The actual arguments used in a function call are of 4 types


• Positional Arguments
• Keyword Arguments
• Default Arguments
• Variable Length Arguments

153
#keyword arguments Output
Item = Pen
def pricedetail(item,price):
Price = 155.75
print('Item = %s'% item) Item = Pencil
print('Price = %.2f' % price) Price = 24.00
Item = Eraser
Price = 5.00
pricedetail(item='Pen', price =155.75)
pricedetail(price=24.00, item ='Pencil')
pricedetail('Eraser',5) # positional argument

pricedetail('Eraser',price =5) Item = Eraser


Price = 5.00

pricedetail(item='Eraser',5) #Syntax Error: Positional argument


follows keyword argument
154
#default arguments Output
def pricedetail(item , price =100): Item = Pen
print('Item = %s'% item) Price = 100.00
Item = pencil
print('Price = %.2f' % price)
Price = 340.00
Item = Pencil
pricedetail('Pen' ) Price = 100.00
pricedetail(price =340, item ='pencil')
pricedetail(item= 'Pencil')

pricedetail(price=340) TypeError: pricedetail() missing 1


required positional argument: 'item'

pricedetail(340) Item = 340


Price = 100.00 155
Variable Length Argument
# variable length argument
def add(*a): #args can take zero or more values
""" This function adds the given numbers """ Output
sum = 0 Sum of all numbers= 30
Sum of all numbers= 130
for i in a:
Sum of all numbers= 10
sum+=i Sum of all numbers= 0
print('Sum of all numbers= ',(sum))

#call add() and pass arguments


add(10, 20)
add(20,10,50,30,10,10)
add(10)
add()
156
Keyword variable length argument
#Keyword variable argument
def display(**kwargs): #kargs can take zero or more values --- dictionary
""" To display the given values """
for x, y in kwargs.items(): # items() will give pairs of items Output
print('key={}, value={} '.format(x,y)) key=rno, value=20

key=rno, value=10
display(rno =20) key=name, value=Prakash
print()
display(rno=10, name = 'Prakash') key=x, value=10
key=name, value=Prakash
print()
key=ab, value=5.5
display(x=10, name = 'Prakash', ab = 5.5)

157
#Keyword variable argument Output
key=rno, value=20
def display(**kwargs): #kargs can take zero or more values --- dictionary rno
""" To display the given values """ 20
for x, y in kwargs.items(): # items() will give pairs of items
key=rno, value=10
print('key={}, value={} '.format(x,y)) key=name, value=Prakash
for x in kwargs.keys(): rno
name
print(x) 10
for y in kwargs.values(): Prakash
print(y)
key=x, value=10
print() key=name, value=Prakash
key=ab, value=5.5
x
display(rno =20)
name
display(rno=10, name = 'Prakash') ab
display(x=10, name = 'Prakash', ab = 5.5) 10
Prakash
5.5
158
Local and global variables

# Accessing the local variable in a function


def myfunc():
a =10
a+=1
print(a)

myfunc()
print(a) NameError: name 'a' is not defined

159
Local and global variables
# Global variable example
1
a=1 10
def myfunc(): 1
b =10 ERROR!
Traceback (most recent call last):
print(a)
File "<main.py>", line 10, in <module>
print(b) NameError: name 'b' is not defined

myfunc()
print(a)
print(b)

160
Local and global variables

# Global variable example


a=1 Output
def myfunc(): 10
a =10 1
print(a)

myfunc()
print(a)

161
Local and global variables
Output
# Accessing the global variable inside a function
Global a = 10
a = 10 Modified a= 2
def myfunc(): Global a = 2
global a
print('Global a = ',a)
a=2
print('Modified a= ' ,a)

myfunc()
print('Global a = ',a)

162
# same name for local and global variable
a = 10
def myfunc():
a = 20 # a is a local variable Output
x = globals()['a'] 10
Global a = 10
print(globals()['a'])
Local a= 20
print('Global a = ',x)
Global a = 10
print('Local a= ' ,a) 10
45
myfunc()
print('Global a = ',a)
print(globals()['a'])
globals()['a']=45
print(a)

163
# A function to calculate total and average
# Passing group of elements to a function
def calculate(lst):
n = len(lst)
sum = 0
for i in lst:
sum+= i
avg = sum/n
return sum, avg

print('Enter the numbers separated by space: ')


lst = [int(x) for x in input().split()]

x,y = calculate(lst)
print('Total: ', x)
print('Average: ',y)

164

You might also like