Lec 7-8 Basics of Python
Lec 7-8 Basics of Python
1. What is Python?
2. Download & Install Anaconda for Python
3. Learn Basics of Python
4. Conditional Statements in Python
5. Loops of Python
6. Libraries in Python
WHAT’S PYTHON ?
General purpose programming language
Named after Monty Python-British comedy
group
Used to do things from testing microchips at
Intel
Used to powering Instagram
building video games ,popular in IoT, Data
Science ,Big Data, AI and so on….
Followed by millions of users worldwide
Why Python?
Image source:
IEEE
Spectrum Jul
2020
Why Python?
Fast, lower learning-curve, user-friendly
Plays well with others
Runs everywhere
Known for rich-ecosystem & utilities
Major advantage is its breadth
Has thousands of third-party modules and libraries
Libraries/frameworks are mature and tested for 10+
years
PYTHON TOOLS FOR
SCIENTIFIC COMMUNITY
WHO USES PYTHON?
Google makes extensive use of Python in its web search
system
Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and
IBM use Python for hardware testing
YouTube video sharing service is largely written in
Python
NASA uses Python for hardware testing and satellite
launching
...the list goes on...
Download Python
Download and Install Python
raju3131.pal@gmail.
com
BRIEF HISTORY OF PYTHON
24
WHAT’S PYTHON BUZZ?
25
WHY PROGRAM?
Pre Packaged software available to analyse a model for
your data
Limits the types of analysis
Deviate your research agenda
Can do anything that you want
Limit is your imagination
26
WHY PYTHON?
Fast, lower learning-curve, user-friendly
Plays well with others
Runs everywhere
Known for rich-ecosystem & utilities
Major advantage is its breadth
Has thousands of third-party modules and libraries
Libraries/frameworks are mature and tested for 10+ years
27
WHY PYTHON?
28
PYTHON V/S OTHER
LANGUAGES
On an average Python code is smaller than JAVA/C++
codes by 3.5 times owing to Pythons built in datatyeps
and dynamic typing.
Dynamically declare and use variables
Python is interpreted while C/C++, etc. are compiled.
Compiler : spends a lot of time analyzing and processing the program, faster
program execution
Interpreter : relatively little time is spent analyzing and processing the
program, slower program execution
29
PYTHON TOOLS FOR
SCIENTIFIC COMMUNITY
30
WHO USES PYTHON?
31
Python Basics
START WORKING WITH
PYTHON
Open the Python IDLE and execute the following
commands. Observe the output.
10 + 15
print("Hello World")
45 - 34
8 * 2
print("Rahul's age is", 45)
print("I have", 10, "mangoes and", 12, "bananas")
33
START WORKING WITH
PYTHON
Writing
Python
v e St
t i Program an
r a c e M da
e
t o d od rd
n
I M e
34
START WORKING WITH
PYTHON
Standard Mode
Interactive Mode
Running your program from
Test One Line at a time
start to finish
35
START WORKING WITH
PYTHON
Python Distribution
Core Python
Several Packages
36
VARIABLES IN PYTHON
Variable is a container for data.
e. g. a=10
Open Python IDLE and execute the following commands.
Observe the output.
emp_number = 1233
print("Employee Number:", emp_number)
emp_salary = 16745.50
emp_name = "Jerry Squaris"
print("Employee Salary and Name:", emp_salary, emp_name)
emp_salary = 23450.34
print("Updated Employee Salary:", emp_salary)
37
VARIABLES IN PYTHON
38
VARIABLE DECLARATION
Typing 39
VARIABLES AND ITS
DIMENSIONS
40
DATA TYPES IN PYTHON
41
DATA STRUCTURE IN PYTHON
42
VARIABLE NAMING
CONVENTIONS
• Try 1_rollnumber=10
What is result?
• Variable name must start with an underscore (_) or an
alphabet(upper/lower) followed by any number of
occurrences of alphabets, digits or underscores (_).
• Variable names are case-sensitive.
• Variable name cannot match any of Python's reserved
words(keywords)
43
TEST YOURSELF
1. _age
2. b: _1234
3. c: in
4. d: length (white spaces appended before the
word length)
5. e: 100_emp
6. abc$
44
BUILT-IN FUNCTION type()
var1 = 10
print(“Type of var1:”,type(var1))
var2 = “10”
print(“Type of var2:”,type(var2))
var3 = 10.5
print(“Type of var3:”,type(var3))
45
COMPLEX EXAMPLE
complex1 = 10 + 45.6j
Temp = complex1.img +10
print(“Output_1:”,complex1.real)
print(“Output_2:”,Temp)
Output:
Output_1:?
Output_2:?
46
OBJECTS
Object contains either data, functions or both. Called attribute; Data and method
The id() function returns identity of the object (an integer value) which is unique for given object and
remains constant during its lifetime.
id(5)
6406896
Python variables are references to objects.
In Python, multiple assignments can be made in a single
statement as follows:
a, b, c = 5, 3.2, "Hello"
47
MEMORY MANAGEMENT
Code and data are always present in RAM for execution
Main memory is partitioned into; code, stack, heap
All objects are in heap and reference variables are in stack
a = 10
b = 20
a 10
c = 10
b
c 20
48
TRY IT
a = 10
b = a
print( “ Value of a and b before
increment”)
print(“id of a: “, id(a))
print(“id of b: “, id(b))
b = a + 1
print( “ Value of a and b after increment”)
print(“id of a: “, id(a))
print(“id of b: “, id(b))
49
VARIABLES IN PYTHON
Mutable: Mutable object can be changed after it is created.
When you alter the item, the id will be still the same.
Dictionary, List
b = []
id(b) = 140675605442000
b.append(3)
b = [3]
id(b)= 140675605442000 #SAME!
Immutable: Immutable object can not be changed after it is
created. String, Integer, float, Tuple
a=4
id(a) = -6406896
a=a+1
id(a) = -6406872 # DIFFERENT!
50
PRINT IN PYTHON
Print method prints the given text message or expression value on
the console, and moves the cursor down to the next line. syntax
o print('Write any message')
Prints several messages and/or expressions on the same line.
o print (Item1, Item2, ..., ItemN)
Output formatting
o print('The value of x is {} and y is
{}'.format(5,10))
Here the curly braces fg are used as placeholders. We can specify the
order in which it is printed by using numbers(tupleindex).
C-like syntax can also be used.
o print("%s %s" %('hello', 'world'))
51
EXERCISE 1
WAP to print your name two times
WAP to add three numbers and print result
WAP to print the following string in a specific format
Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up
above the world so high, Liek a diamond in the sky. Twinkle, twinkle, little star,
How I wonder what you are"
Output :
52
COMMENTS IN PYTHON
53
INDENTATION IN PYTHON
Try it:
print(“Python uses indentation”)
print(“will it work?”)
Python uses indentation instead of braces to determine the
scope of expressions.
All lines must be indented the same amount to be part of
the scope (or indented more if part of an inner scope).
This forces the programmer to use proper indentation since
the indenting is part of the program.
54
USER INPUT IN PYTHON
55
USER INPUT IN PYTHON
Example:
Output:
56
EXERCISE 2
Find and print the sum of new values of num1 and num2
57
PYTHON BASIC OPERATORS
Arithmetic Operators +, -, /, *, %, //
Output:
10 Python True
Syntax Error
59
TEST YOURSELF
Which of the following will give the output as 23?
(Choose all applicable)
1. int("20") + 3
2. "20" + str(3)
3. int(20) + int("3")
4. str(20 + 3)
60
TEST YOURSELF
What will be the output?
x = 2+3/4%5-2**3**2/5+10//2
print(x)
1. x == 1 and y <= 4
2. True and (x * 4 == y)
3. not(y > x)
4. x <= 1 and y - 2 > x or True
5. not(x - y > 0) or (1 != 1)
6. False or True and False
61
EXERCISE 3
Jack and his three friends have decided to go for a trip by sharing the expenses of the fuel
equally.
Write a Python program to calculate the amount (in Rs) each of them need to put in for the
complete (both to and fro) journey.
The program should also display True, if the amount to be paid by each person is divisible
by 5, otherwise it should display False.
Assume that mileage of the vehicle, amount per litre of fuel and distance for one way are
given.
62
_ OPERATOR
Returns last accessed object
Works in interactive mode
63
PYTHON MODULE AND
METHODS
Module is set of library functions
Can include entire module or a single function if required
64
PYTHON MODULE AND
METHODS
65
help() AND dir()
66
Basic Data Types
BASIC DATA TYPES
Integers (default for numbers).
z=5
Range of int in python is equivalent of a C long
Long Integer an unbounded integer value.
Floats
z=5.2
Strings - strings are enclosed within either single quotes or (‘ ') or double
quotes (\ ").
z='python'
z="python"
Use triple double quotes for multi line strings or strings than
contain both ' and " inside of them:
“””python is ' open source
" language"
"""
68
SEQUENCES
Collection of elements
Perform common operation (in addition some specific)
Sequences are:
String
List
Tuple
Dictionaries
Sets
69
REPRESENTATION OF
SEQUENCES
70
SLICING IN SEQUENCES
To extract a chunk of elements from a sequence
General Syntax:
Sequence[start : stop]
Returns elements from sequence[start] to sequence[stop-
1]
e. g. Shapes[2:4]
[Triangle
Square]
71
STRING
72
STRING-SLICING
Which of the following will give an output as "Python"
(Multiple options can be correct):
text ="I love Python“
1. text[7:13]
2. text[8:13]
3. text[7:]
4. text[-6:-1]
5. text[-6:]
73
STRING ESCAPING
74
STRING-CHANGE OR DELETE
Try it:
S = “Sample”
S[1] = ‘i’
print(S)
75
STRING-CHANGE OR DELETE
Try it:
S = “Sample”
S + “Collected”
print(S)
76
STRING-OPERATORS
+ and * can be applied on String objects
Try It:
s1=“Hello”
s2=“Learners”
print(s1+s2) s1=“Hello”
print(s1*3)
77
STRING-METHODS
78
EXERCISE 3
Accept a string as an input from the user. Check if the
accepted string is palindrome or not.
If the string is palindrome, print "String is palindrome",
otherwise print "String is not palindrome".
Also print the actual and the reversed strings.
Note – Ignore the case of characters.
Hint – A palindrome string remains the same if the
characters of the string are reversed
79
PYTHON LIST
80
LIST-ACCESSING
# list with mixed datatypes
mylist = [1, "Hello", 3.4]
mylist[0] will return 1
# nested list
mylist = ["mouse", [8, 4, 6], ['a']]
mylist [0][0] return m
mylist [0] return mouse
81
LIST-SLICING
82
LIST-OPERATORS
+ and * can be applied on List objects
Try It:
L1=[1,2,3,4,5]
L2=[6,7]
print(L1+L2)
print(L2*3)
83
LIST-UPDATE
Lists are mutable i.e. we can change/modify their content
after it is created.
General Syntax:
List[index] = new Value
L=[6,7,8,9]
L[3]= 10
print(L)
84
LIST-INSERT
List.append(item)
List.insert(index,item)
List.extend[list]
L1=[6,7,8,9]
L2=[1,2]
L1.insert(2,L2)
print(L1)
L1.append(L2)
print(L1)
L1.extend(L2)
print(L1)
85
LIST-DELETE
86
LIST-METHODS
List.index(item)
List.sort()
List.reverse()
List.count(item)
L1=[1,2,3,4,5,6,7,8,9,1]
print(L1.index(1))
L1.sort()
print(L1)
L1.reverse()
print(L1)
print(L1.count(8))
87
PYTHON TUPLE
88
CREATING A TUPLE
89
CREATING A TUPLE-WITH
ONE ELEMENT
T=(“Python”)
print(type(T))
T=(“Python”,)
print(type(T))
90
TUPLE-OPERATORS
+ and * can be applied on Tuple objects
Try It:
T1=(1,2,3,4,5)
T2=(6,7)
print(T1+T2)
print(T2*3)
91
TUPLE-ACCESSING ELEMENT
92
TUPLE-CHANGE, INSERT AND
DELETE
93
TUPLE-FUNCTIONS
94
SET IN PYTHON
A set is an unordered collection of items. Every element
is unique (no duplicates) and must be immutable (which
cannot be changed).
However, the set itself is mutable. We can add or remove
items from it.
Sets can be used to perform mathematical set operations
like union, intersection, symmetric deference etc.
95
SET-CREATING SET
96
SET-CREATING EMPTY SET
• Try it:
T={}
print(type(T))
97
SET-ADDING ELEMENT
98
SET-REMOVE ELEMENT
A particular item can be removed from set using
methods, discard() and remove().
The only difference between the two is that, while using
discard() if the item does not exist in the set, it remains
unchanged. But remove() will raise an error in such
condition.
99
SET-REMOVE ELEMENT
100
SET-OPERATION
101
PYTHON DICTIONARY
Dictionary is an unordered collection of key-value pairs. It is generally
used when we have a huge amount of data. Dictionaries are optimized
for retrieving data.
Creating a dictionary
102
PYTHON DICTIONARY
103
DICTIONARY-DELETE OR
REMOVE ELEMENT
104
DICTIONARY-NESTING
105
TRY IT
dic={“name”:”xyz”,”Roll_No”:123456,”age”:18}
print(dic.keys())
print(dic.values())
print(dic.items())
Output?
106
RANGES
Immutable sequence of integers
General Syntax:
range(start,stop,interval)
print(list(range(10))
print(list(range(5,10))
print(list(range(1,10,2))
107
Control Flow
Statements
STATEMENTS
Use to compute and assign values
109
USE OF INDENTATION
Uses indentation for block (Compound statements)
Delimiter for blocks in Python is a colon (:) followed by
indented spaces or tabs
110
CONTROL FLOW IN
PYTHON- SELECTION
The if else statement is used in Python for decision making
if test expression:
statement(s)
else:
statement(s)
To test more than one condition following syntax is used
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
111
CONTROL FLOW IN
PYTHON- SELECTION
Observe the following Python code. Find the value of num3 if the
output of the program is 6.
Num1=2
Num2=5
Num3=?
if(Num2!=5 or abs(Num1-Num3)==6)):
Num2 += 1
elif(Num2-Num3*Num1 == -11):
Num2 +=22
else:
Num2 *= 2
print(Num2)
112
TRUE AND FALSE IN PYTHON
Things that are False
The boolean value False
The numbers 0 (integer), 0.0 (oat) and 0j (complex).
The empty string "".
The empty list [], empty dictionary and empty set().
Things that are True
The boolean value True
All non-zero numbers.
Any string containing at least one character.
A non-empty data structure.
113
CONTROL FLOW IN PYTHON-
ITERATION/LOOPING
1. while loop
2. for loop
114
CONTROL FLOW IN
PYTHON- WHILE LOOP
115
CONTROL FLOW IN
PYTHON- FOR LOOP
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.
General Syntax
116
CONTROL FLOW IN
PYTHON- FOR LOOP
117
NESTED LOOPING
118
BREAK STATEMENT
The break statement terminates the loop containing it. Control of the
program follows to the statement immediately after the body of the
loop.
If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.
119
CONTINUE STATEMENT
The continue statement is used to skip the rest of the code
inside a loop for the current iteration only. Loop does not
terminate but continues on with the next iteration.
120
LOOP WITH ELSE CLAUSE
121
TEST YOURSELF
What is the value of "a", if the output of the program is 0 0 1?
a = ?
i = 0
while i < a:
print(i)
i += 1
if i == 2:
break
else:
print(0)
Answer- 4, 3, 2 or 1
122
EXERCISE 4
user.
Python Program to Find the Second Largest Number in a
List
Python Program to check number is prime or not.
numbers = range(10)
l=[]
for i in numbers:
l.append(i**2)
print(l)
124
LIST COMPREHENSIONS
numbers = range(10)
print(l)
Output?
125
EXERCISE 5
126
Functions
FUNCTIONS
128
FUNCTIONS IN PYTHON
To use a function you always write its name, followed by
some arguments in parentheses ().
The word argument basically means an input to the function. Then,
the function does some action depending on its arguments.
When there are multiple arguments to a function, you separate them
with commas (,).
x=3
print(x, x + x , x * x)
129
FUNCTIONS IN PYTHON
A function may also give back a value (like an output).
For example the function max() (short for maximum)
gives back the largest out of all of its arguments, which
must be numbers.
print(max(42, 17))
print(max(128,281,812))
130
FUNCTIONS IN PYTHON
In-built functions
x = min(max(13, 7), 9)
print(x)
131
There is a single road between the two cities. The road has three bridges
with weight limits a, b, c, as shown in the picture below:
In order to drive along the route, your truck needs to drive first over the
bridge with weight limit a, then the one with weight limit b, then the one
with weight limit c. Your truck will crash if you overload any of the three
weight limits. Write a program that prints out the maximum weight that
can be transported along this road. Your code should assume that the
variables a, b, and c already contain the bridge weight limits.
132
Now we will tell you the whole story. There is also a second
route consisting of two bridges, the first with weight limit d, and the
second with weight limit e, as illustrated below.
Your truck can take either route. Write a program that prints out the
maximum weight that can be transported between the two cities.
Assume that the variables a, b, c, d, and e contain the bridge weight
limits.
133
FUNCTIONS IN PYTHON
General Syntax:
def functionname(parameters):
statement(s)
134
DEFINING FUNCTIONS
135
FUNCTIONS-EXAMPLE
136
EXERCISE 6
137
TYPES OF FUNCTION
ARGUMENTS
139
FUNCTION-REQUIRED ARGUMENTS
def printinfo(name,age):
print (“Name:”,name)
print(“Age:”,age)
printinfo(29,“Kushagra”)
printinfo(“Kushgra”,29)
140
FUNCTION-KEYWORD ARGUMENTS
def printinfo(name,age):
print (“Name:”,name)
print(“Age:”,age)
printinfo(29,“Kushagra”)
printinfo(age=29,name=“Kushgra”)
141
FUNCTION-DEFAULT ARGUMENTS
142
FUNCTION-VARIABLE LENGTH
ARGUMENTS
143
SCOPE OF VARIABLE
144
SCOPE OF VARIABLE
145
SCOPE OF VARIABLE
146
SCOPE OF VARIABLE
Which of the following code snippets gives the output as:
2
3
147
RECURSION IN PYTHON
Recursion is the process of defining something in terms
of itself.
148
LAMBDA FUNCTION
To create an anonymous function in the form of an expression, use the
lambda statement:
Syntax
lambda args : expression
args is a comma-separated list of arguments, and expression is an
expression involving those arguments. For example:
a = lambda x, y : x+y
print a(2,3) # produces 5
149
PYTHON MODULE
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for e.g.: example.py, is called a module
and its module name would be example.
First create a module example.py
150
MODULE-IMPORT
Use import module to import the definition of module
import example
example.add(4,5.5)
151
MODULE-IMPORT STATEMENT
152
MODULE-IMPORT STATEMENT
153
EXERCISE 6
Write a Python function that takes two lists and returns
True if they have at least one common member.
Write a Python program to print a specified list after
removing the 0th, 4th and 5th elements.
Python Program to sum all the Items in a Dictionary.
154
FILE HANDLING IN PYTHON
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
File operations
- Open a file
- Read or write (perform operation)
- Close the file
155
FILE HANDLING IN PYTHON
156
FILE OPERATION
157
FILE OPERATIONS
Unlike other languages, the character 'a' does not imply the number
97 until it is encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it
is 'cp1252' but 'utf-8' in Linux.
Hence, when working with files in text mode, it is highly
recommended to specify the encoding type.
f = open("test.txt", mode = 'r', encoding = 'utf-8')
In case any exception occurs use a try...finally block.
try:
f = open("test.txt",encoding = 'utf-8')
# perform le operations
finally:
f.close()
158
FILE ATTRIBUTES
159
FILE ATTRIBUTES
160
FILE ATTRIBUTES
161
WRITE TO AND READ FROM
A FILE
162
WRITE TO AND READ FROM
A FILE
163
Writing
164
165
EXERCISE 7
Python Program to Count the Number of Words in a Text File.
Python Program to Read a String from the User and Append it into a
File.
166