Unit 1
Unit 1
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
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
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
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)
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.
(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)
20
Representing Binary, Octal and Hexadecimal Numbers
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
23
int(string,base)
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)
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
Ex:
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
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.
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
41
Sets
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}
43
Set datatype Cont.
print(s[0]) # indexing will give error
print(s[0:2]) #slicing will give error
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("abcdefg")
print(fs) # may display frozenset( {'e', 'g', 'f', 'd', 'a', 'c', ' b'})
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.
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.
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".
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.
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
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
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)
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
74
Input : ['yellow', 'blue', 'red' , 'blue', 'white']
Expected output: {'yellow': 1, 'blue': 2, 'red': 1, 'white': 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 ')
• 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
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?
81
#print(object)
lst = [10, "Hai", 20.5]
print(lst) [10, 'Hai', 20.5]
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
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
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)
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.
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.
90
eval() function – Used in two different ways
a, b = 5, 10
result = eval("a + b -4")
print(result)
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']
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")
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")
98
Write a program to display even numbers between m and n using while loop.
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])
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.
*
**
***
****
*****
******
*******
********
*********
**********
102
Write a program to display stars in right angled triangular form using a single loop.
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 ********
*********
**********
105
Write a program using nested loops to display numbers in the following two formats.
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
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)
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])
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)
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)
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())
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)
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
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)
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.
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)
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)
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
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
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)
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
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
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
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
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
x,y = calculate(lst)
print('Total: ', x)
print('Average: ',y)
164