Chapter 1
Chapter 1
Chapter 1
➢ Easy to learn
➢ Easy to set up
➢ Simple syntax
➢ Interpreted language which means that the code is executed as soon as it is typed.
➢ Can be considered as procedural, object oriented and even functional programming language.
➢ Large ecosystem - support of python developers in the form of libraries and features
➢ Flexible when it comes to syntax, data types, etc so molds itself as per the requirement
➢ Current version - 3
Scope of Python
❖ Multi functional :
➢ Machine learning - TensorFlow, Keras, PyTorch
➢ Data science - NumPy, Pandas, Matplotlib, SciPy, etc
➢ Web development - Django, Flask, Tornado, etc
➢ Automation - Libraries to automate DevOps tasks, scripts for automated backups, clean ups, automating tasks
while working on excel sheets or other tasks, etc
➢ Artificial Intelligence - Face recognition, Voice recognition
➢ Web scraping
Set up & Configuration
import sys
print(sys.version)
What is sys?
1. Based on the inputs given in the previous slide, execute the above lines of code on the command line.
Indentation, white spaces
❖ Both the above play an important role in defining scopes of loops, functions and classes in Python. In other
if 8>9:
if 8<9 :
if 8<9 :
1. #This is a comment
print("Python programming comment demo")
3. #This is a comment
#on multiple lines
#This is a comment
print("Python programming multi line comment demo")
Activity 1.3
Consider the below code. Copy it and execute it. Discuss the output.
"""
This is a comment sample
how does it work??
"""
print("Only this line is executed")
Why does the above code work? Is the multiline string a style of commenting in Python?
Variables
❖ They have some datatype based on the value which they are holding.
variable_name = variableValue
Observe that there is no datatype defined at the time of defining the variable. This means that the variables are
DYNAMICALLY TYPED and NOT STATIC TYPED as is the case with languages such as Java, C, C++,etc
❖ If the variable name has multiple words then the convention says to separate those words using _ (underscore)
student_roll_number
Variables - Naming rules
Can only contain alpha-numeric characters and Can not have reserved words
underscores
Declared within a function. Scope is limited to the function Declared outside the function but used/ modified within a
function. Variables that are only referenced inside a function
are implicitly global.
#understanding the scope of the variables in Python num1, num2 = 30.50, 40.25
def addition():
#we are defining addition() using def keyword print("Inside addition")
def addition(): global num1,num2
num1,num2=30.50,40.25 print("Num1 is ", num1)
sumAdd = num1+num2 print("Num2 is", num2)
print("Num1 is ", num1) num1, num2 = 50.75, 120.25
print("Num2 is", num2) sumAdd = num1+num2
print("Addition result is:",sumAdd) print("Addition result is:",sumAdd)
#we are invoking addition() #we are invoking addition()
addition() addition()
print("Num1 is ",num1) #what will be the output of this print("Num1 is ",num1) #what will be the output of this line?
line? print("Num2 is", num2) #what will be the output of this line?
print("Num2 is", num2) #what will be the output of this print("Addition result is:",sumAdd) #what will be the
line? output of this line?
print("Addition result is:",sumAdd) #what will be the
output of this line?
Activity 1.4
1. Copy the code given below and observe the output
num1 = 20
num2 = 30
st1 = 'Hello'
st2 = 'World'
#guess the output of the following
print(num1)
print(num1)
print(num1+num2)
print(st1)
print(st2)
print(st1+st2)
print(st1,st2)
print(num1,st1)
print(num1+st1) #will this line execute?
Data types
Name of the data type Type of Syntax
data
stored
str (These are immutable) Text str = “Hello world” (or) str = ‘Hello World’ (or) str = ‘’’ Hello
world’’’
True / False (Any integer, floating-point Boolean st_task_done = True (or) st_task_done = False
number, or complex number having zero
as a value is considered as False, while if
they are having value as any positive or
negative number then it is considered as
True.)
Activity 1.5
1. You are making a housie game app to generate random numbers. Write a Python program to help you generate
these numbers 6 times for a given housie ticket.
Operators
This topic will be covered as a part of Students’ Presentation
Object Types - List
❖ There are four collection data types in the Python programming language: List, Tuple, Set, Dictionary.
constructor here.
❖ Items in the list are ordered i.e they will retain the sequence in which they are inserted into the list.
❖ Individual item in the list is identified using the index number of that element. Index numbers begin with 0
b. print(len(myDictionary))
c. studentRecord = {'name':'ABC',
'age':20,
'contactNumbers':[123456,987653]
}
print(studentRecord)
print(studentRecord['name'])
print(studentRecord['contactNumbers'])
print(type(studentRecord))
Activity 1.7
studentRecord = {'name':'ABC',
'age':20,
'contactNumbers':[123456,987653]
}
oneMoreStudentRecord = studentRecord
print('The new dictionary looks like:',oneMoreStudentRecord)
Activity 1.7
3. Add the following lines to the above code snippet. Execute the modified code and observe the results:
studentRecord = {'name':'ABC',
'age':20,
'contactNumbers':[123456,987653]
}
oneMoreStudentRecord = studentRecord
print('The new dictionary looks like:',oneMoreStudentRecord)
studentRecord.update({'address':'Mumbai'})
print('Modified studentRecord dictionary looks like:',studentRecord)
print('The new dictionary looks like:',oneMoreStudentRecord)
Object Types - Tuples
❖ There are four collection data types in the Python programming language: List, Tuple, Set, Dictionary.
myTuple=(element1,element2,..,elementN) (OR)
❖ Elements are accessed using their index values. Index starts from 0.
Activity 1.8
Execute the below given code and observe the output
print('Fifth tuple',fifthTuple)
firstTuple=() # this is an empty tuple
print(type(fifthTuple))
print('First tuple',firstTuple)
myList=[10,20,30]
print(type(firstTuple))
sixthTuple=tuple(myList)
secondTuple=("mon","tue","wed","thu")
print('Sixth tuple',sixthTuple)
print('Second tuple',secondTuple)
seventhTuple=(40,)
print(type(secondTuple))
print('Seventh tuple',seventhTuple)
thirdTuple=(1,2,3)
print(type(seventhTuple))
print('Third tuple',thirdTuple)
eightTuple=(90)
print(type(thirdTuple))
print('Eighth tuple',eightTuple)
fourthTuple=tuple(("fri","sat","sun"))
print(type(eightTuple))
print('Fourth tuple',fourthTuple)
ninthTuple=tuple(range(1,11))
print(type(fourthTuple))
print('Ninth tuple',ninthTuple)
fifthTuple=(secondTuple,fourthTuple) #NESTEDtuple
Object Types - Unpacking Tuples
❖ A was used to assign or extract the tuple values on the right to the variables on the left is called UNPACKING of a
tuple.
❖ If the number of variables on the left do not match the number of values in the tuple then we can use ASTERISK with
any one of the variable on the left. This special variable will hold all the remaining values within the tuple.
❖ Block defines the scope of the variable and control the flow of execution of the program.
❖ Examples of blocks:
➢ Functions
➢ Conditional statements
➢ Class
Python Flow Control - if,elif,else
❖ The if, elif, else conditions are used in isolation or combination to compare operands and determine the flow of
❖ Ternary operators can also be used to with if,elif and else conditions to reduce the length of code and get the
Using if,elif,else
elif(age == 18):
print('Just 18!')
else:
print('Legally adult')
Activity 1.9
2. Execute the below given code and observe the output
3. Execute the following code and observe the output. Understand the use of pass statement
match valueToBeMatched:
case option1:
case option2:
case _:
❖ for loop - To execute the given set of statements ‘n’ number of times / iterations. It iterates over list, tuple, dictionary,
while (True):
num = int(input("Enter a number: "))
if(num % 2 == 0):
print('Even number')
continue
else:
print('Odd number')
break
Activity 1.11
2. Using for loop write a program in Python to print all the prime till the nth number. Take the nth number from the
user.
val = int(#missingKeyword('Enter the number till which you want to find prime numbers'))
primeSt = False
for i in #missingKeyword(2,#missingvariable):
if val % i == #missingvalue:
#missingKeyword #terminate the loop here
else:
primeSt = True
if(primeSt):
print(f'{val} is a prime number')
else:
print(f'{val} is not a prime number')
Activity 1.11
3.Execute the code snippets given below and observe the output
for i in message:
print(i)
for i in myList:
print(i)
c. for i in range(1,15,2):
print(i)
d. myTelephoneDiary = {"ABC":1234,"PQR":5678,"XYZ":2345,"QWE":7834}
for ky in myTelephoneDiary:
import sys
#missingKeyword True:
status = input('Enter Y to continue or N to exit')
if status == #missingValue:
num = int(input('Enter a number to determine if it is odd or even'))
if #missingCondition == 0:
print(num,'is even number.')
else:
print(num,'is odd number.')
elif status == 'N':
print('Thank you! See you again')
sys.exit()
File Handling basics
❖ File handling allows us to perform a wide range of operations such as creating,opening, reading, writing on to file.
❖ Python allows a file to be operated in text or binary format.
❖ When any file has to be handled it has to be loaded into the primary memory first.
❖ Each file is given a FILE HANDLER using which it can be operated upon.
❖ Syntax for opening a file:
fileObject = open(r”filename”,”accessmode”)
The letter r before the filename prevents the characters in the file name to be treated as special characters by Python
interpreter. If the file is in the same directory as the file handling program then the r can be omitted.
fileObject.close()
This command closes the file and frees the memory from the primary memory space which was occupied by the said
file.
File Handling Modes
❖ File handling allows us to perform a wide range of operations such as creating,opening, reading, writing on to file.
r Read operation
w Write mode. Create the file if it does not exist. Overwrite the file if it exists.
w+ Write and read to a file. Overwrites existing file. Reduces the file size if there is no
data in the file. Creates a new file if previous does not exist.
❖ To perform any operation on a given file, one first has to open it using the open().
Read Description
methods
readline() Read the file line by line. Useful in conserving memory especially in case of large
files. Refer fileReadLineEx.py
❖ To perform any operation on a given file, one first has to open it using the open() and set the mode to w or a .
Write Description
methods
write() Writes the content in the file without adding any extra characters not even new line,
\n. Refer writeFileEx.py
wrtielines() Writes list of strings to a file in one go. Each string is separated using \n. Refer
writeLinesEx.py
Thank you