CS306 Programming With Python
CS306 Programming With Python
CS306
CHAPTER 01 – BASIC CONCEPTS
Program:
Program is a precise set of instructions to solve a particular problem.
Interpreted languages:
Interpreted languages execute the source code directly, line by line, during
runtime.
We can use python as a calculator by typing: python + Enter(↵) on the terminal.
This opens REPL or Read Evaluate Print Loop:
Read: Python reads your input
Evaluate: It executes the code
Print: It shows the result
Loop: It waits for the next command
COMMENTS
Comments are used to write something which the programmer does not want to execute. This can be used
to mark author name, date etc.
TYPES OF COMMENTS
Single Line Comments: (#) Multiline Comments: (""" """)
# This is a Single-Line Comment """This is an amazing
example of a Multiline
comment!"""
Chapter 1 – practice set
1. Write a program to print Twinkle twinkle little star poem in python.
2. Use REPL and print the table of 5 using it.
3. Install an external module and use it to perform an operation of your interest.
4. Write a python program to print the contents of a directory using the os module.
Search online for the function which does that.
5. Label the program written in problem 4 with comments.
CHAPTER 02 – VARIABLES AND DATATYPE
Python Character Set
Letters: A to Z, a to z
Digits: 0 to 9
Special Symbols: + - * / etc.
Whitespaces: Blank Space, tab, carriage return, newline, formfeed
Other characters: Python can process all ASCII and Unicode characters as part of
data or literal
Variables
Container or memory location to store a value.
Variables: container to store a value.
Keywords: reserved words in python
Identifiers: class/function/variable name
Identifiers Variables
Names used to identify entities in a Storage locations in memory that hold
program (variables, functions, classes, data values, referenced by identifiers.
etc.).
Data Types
• str
• int, float, complex
• list, tuple, dict
• set, frozenset
• bool
• bytes, bytearray, memoryview
Integers: Whole number(+ve, -ve ,0)
String: 'Tanveer', "Tanver", '''Tanveer'''
Float: Decimal values
Boolean: True, False (always T and F should be capital)
None
Code Example:
a="Tanveer" # str
b=10 #int
c=12.5 #flaot
d=complex(2,1) # complex
print(a, type(a))
print(b, type(b))
print(c, type(c))
print(d, type(d))
Keyword or reserved words:
Its mean dictionary and we cannot use it as a name of variable
Case sensitive mean A, a are two difference meaning.
Types of Operators
An operator is a symbol that performs a certain operation between operands.
In math:
a + b: a and b are operands and + is operator
Following are some common operators in python:
1. Arithmetic operators ( + , - , * , / , % , ** )
2. Assignment operators ( = , +=, -= , *= , /= , %= , **= )
3. Relational or Comparison operators ( == , != , > , < , >= , <= )
4. Logical operators ( not , and , or )
5. Identity operators (is, is not)
6. Membership operators (in, not in)
7. Bitwise operators (&, |, ^, <<, >>)
Arithmetic operators:
1. Floor Division: //
2. Modulus: %
3. Exponentiation: **
Program:
x=13
print(f"Division operator result: {x/2}") #6.5
print(f"Modulus operator result: {x%2}") #1
print(f"Floure Division operator result: {x//2}") #6
Note:
Exponentiation operator (**): used for raise to the power.
Floor division (//): returns the largest integer less than or equal to the result of a
division.
Note:
Not is unary operator work on only one value
But and, or are binary operator work on two values.
Type() function and typecasting.
Type() function is used to find the data type of a given variable in python.
a = 31
type(a) # class <int>
b = "31"
type (b) # class <str>
Type Conversion
One data type can be converted into another data type.
There are two ways of conversion
Type Conversion (Automatically) Type Casting (Manually)
a, b = 1, 2.0 a, b = 1, "2"
sum = a + b #Float c = int(b)
sum = a + c
a, b = 1, "2"
a, b = 1, "2" c = float(b)
sum = a + b #error sum = a + c
A number can be converted into a string and vice versa (if possible)
There are many functions to convert one data type into another:
str(31) =>"31" # integer to string conversion
int("32") => 32 # string to integer conversion
float(32) => 32.0 # integer to float conversion
Type Casting:
Function Description
int(y [base]) It converts y to an integer, and Base specifies the number base.
For example: if you want to convert the string in decimal
numbers then you’ll use 10 as base.
float(y) It converts y to a floating-point number.
str = “ApnaCollege”
str[ 1 : 4 ] is “pna”
str[ : 4 ] is same as str[ 0 : 4]
str[ 1 : ] is same as str[ 1 : len(str) ]
Slicing Negative Index
Negative index is use when we don’t know the exactly length of string
A p p l e
-5 -4 -3 -2 -1
str = “Apple”
str[ -3 : -1 ] #“pl”
Slicing with skip value
We can provide a skip value as a part of our slice like this:
word = "amazing"
word[1: 6: 2] # "mzn"
Other advanced slicing techniques:
Word = "amazing"
Both have same meaning and same answer
Word = [:7] # word [0:7] – 'amazing' Word = [0:] # word [0:7] – 'amazing'
Answer: Answer:
'amazing' 'amazing'
String's Case Conversion Methods
Method Description
capitalize() Converts the first character of the string to uppercase, rest to
lowercase
casefold() Converts string to lowercase (handles ASCII & non-ASCII
characters)
lower() Converts string to lowercase
title() Converts the first character of each word to uppercase
upper() Converts string to uppercase
swapcase() Converts lowercase to uppercase and uppercase to lowercase
Program:
#
tststr="the quick BROWN fox jumped over the lazy dog"
str1=[Link]()
print(str1)
str2=[Link]()
print(str2)
str3=[Link]()
print(str3)
str4=[Link]()
print(str4)
str5=[Link]()
print(str5)
str6=[Link]()
print(str6)
String functions
Some of the commonly used functions to perform operations on or manipulate
strings are as follows.
Let us assume there is a string ‘str’ as follows:
1. len () function – This function returns the length of the strings.
str = "harry"
print(len(str)) # Output: 5
2. [Link]("rry") – This function_ tells whether the variable string ends
with the string "rry" or not. If string is "harry", it returns true for "rry" since Harry
ends with rry.
str = "harry"
print([Link]("rry")) # Output: True
3. [Link]("c") – counts the total number of occurrences of any character.
str = "harry"
count = [Link]("r")
print(count) # Output: 2
4. capitalize( ) capitalize first character of a given string.
str = "harry"
capitalized_string = [Link]()
print(capitalized_string) # Output: "Harry"
5. [Link](word) – This function finds a word and returns the index of first
occurrence of that word in the string.
str = "harry"
Harry P. 15 College lec 2 P. 5 Cs305 lec 39
6. [Link] (old word, new word ) – This function replace the old word with
new word in the entire string.
str = "harry"
replaced_string = [Link]("r", "l")
print(replaced_string) # Output: "hally"
String's Trimming Methods
Trimming leading and trailing white space:
lstrip()
Definition: Removes all leading (left-side) whitespace characters from a
string.
Details: It trims spaces, tabs, or newline characters from the beginning only.
rstrip()
strip()
Program:
# Stripping/remove white space or other character
tststr=" The quick brown fox "
print(tststr, len(tststr))
str1=[Link]()
print(str1, len(str1))
str2=[Link]()
print(str2, len(str2))
str3=[Link]()
print(str3, len(str3))
str4=[Link](" T")
print(str4, len(str4))
str5=[Link]("x ")
print(str5, len(str5))
Note:
Strip():
Not only we can remove white space we can remove a specific character
which will be given as an arguments will be removed.
Its remove characters from beginning and ending, not from middle.
String Methods – Justifications
ljust() — left justified
rjust() — right justified
center() — centered string
All require at least one argument (the total width of the string) and Optional
argument: a fill character (only one character)
Program:
#Justification of strings
tststr="The quick brown fox"
print([Link](50))
print([Link](50))
print([Link](50))
print([Link](50, "="))
print([Link](50, "="))
print([Link](50, "="))
# e.g.
print("1,234.50".rjust(20, "*"))
String Methods - Count
Returns number of times a string occurs in calling string
Arg: string containing one or more characters (required)
Empty string ⇒ all characters are counted
Program: ???
#counting the number of time a substring is found in a string.
tststr=" The quick brown fox "
for c in " abcdefghijklmnopqrstuvwxyz":
print(c, [Link](c))
print([Link](),[Link]([Link]()))
print("qu",[Link]("qu"))
CHAPTER 03 – STRINGS Part 02
String Methods
1. Find()
2. Rfind()
3. Index()
4. Rindex()
#Find()
str1=[Link]("are") #-1 mean not found
print(str1)
#2. Index
str2=[Link]("ni") #Error
print(str2)
str2=[Link]("ani") #Error
print(str2)
Program of find():
# Finde the location of substring in the string
# with the use of find()
tststr=" The quick brwon fox "
lookfor="o"
n=[Link](lookfor,0,30)
if n != -1:
print(lookfor, "occures at position",n)
else:
print(lookfor, "is not in the string")
Feature find() index()
Return Index of the Index of the substring or raises ValueError if
value substring or -1 if not not found
found
Error Returns -1 for not Raises ValueError exception for not found
handling found
Use case Safe search, when When the substring is expected to exist, and
the substring might its absence should be treated as an error
not exist
String Methods – Replace
# replace mthode
tststr="The quick brwon fox jumped over the lazy dog"
tst2=[Link]("o", "red", 1)
print(tststr, tst2)
tststr="The\tquick\tbrown fox"
print(tststr, [Link](1))
String Methods - Partition
partition(arg_string) rpartition(arg_string)
Looks for first occurrence of argstring Looks for last occurrence of argstring
Returns a 3-element tuple containing Returns a 3-element tuple containing
o The string preceding the argstring o The string preceding the argstring
o The argstring itself o The argstring itself
o The string after the argstring o The string after the argstring
If not found, returns a tuple containing If not found, returns a tuple containing
the original string and two empty two empty strings and the original
strings string
Program: Program:
# Partition () # Partition ()
tststr="The quick brow fox jumped tststr="The quick brow fox jumped
over the lazy dog." over the lazy dog."
result=[Link]("the") result=[Link]("the")
print(result) print(result)
{
String Methods – Splitlines
splitlines(keeplinebreaks) split(separator, rsplit(separator,
maxsplit) maxsplit)
Breaks string into a LIST Breaks string into a Starting from right,
where each line is a list LIST where each word breaks string into a LIST
Arg=True ⇒ keep
item is a list item Separator defines
list items (default
linebreaks. = space)
Default = False Maxsplit = no. of
splits to do.
Number of list
items = Maxsplit
+ 1 Default = all
Program:
# Split a string into a list
tststr="The quick\n brow fox\n jumped over\n the lazy dog."
#splitlines()
lstline=[Link]() #by default False
print(lstline)
lstline=[Link](True)
print(lstline)
#split( )
lstline=[Link]()
print(lstline)
lstline=[Link]("he")
print(lstline)
lstline=[Link]("he",1)
print(lstline)
#rsplit()
lstline=[Link]()
print(lstline)
lstline=[Link]("he")
print(lstline)
lstline=[Link]("he",1)
print(lstline)
Special String Methods - [Link]
[Link](iterable)
Called using a separator string.
Returns a string consisting of all elements of the iterable (elements must be
str), joined by separator.
Program:
#
# Joining lists and tuples into a string
#list into string
tstlist=["The quick", "brown fox", "jumped over", "the lazy dog"]
res_string=" ".join(tstlist)
print(res_string)
# tuple into string
tsttuple=("The quick", "brown fox", "jumped over", "the lazy dog")
res_string="**".join(tsttuple)
print(res_string)
}
Special String Methods - f string
Special String methods – f strings
“f”string with {optional formatting} placeholders”
Simple method to construct complicated strings for printing
Formatting is mainly used with numeric and date types
Very rich formatting options
Program:
#
# The power of f-string
num1=100
list1=["List element ",101, True]
tuple1=(1,2,3)
fstring=f"f-string containing a number: {num1},a list: {list1} and a tuple:
{tuple1}"
print(fstring)
Special String methods – f strings
“f”string {var} string {var}…”
Automatically transforms var to strings and concatenates
Add = to print the name of the variable and its value e.g. f“string {var=}” for
debugging
For numbers: {var:[width][.precision][type]} where type = d or f (int or
float)
Program 1 Program 2
# The power of f-string num=100
num1=100 lnum=1234
list1=["List element ",101, True] fnum=123.456
tuple1=(1,2,3) print(f"An f-string with width=10:
fstring=f"f-string containing a {num:10}")
number: {num1=},a list: {list1=} and print(f"An f-string with width=10:
a tuple: {tuple1=}" {lnum:10}")
print(fstring) print(f"An f-string with width=10 and 4
decimal places: {fnum:10.4f}")
print(f"An f-string with width=10
aligned left: {num:<10}")
print(f"An f-string with width=10
aligned right: {num:>10}")
print(f"An f-string with width=10
aligned right and padded: {num:*>10}")
print(f"An f-string with width=10
aligned left and padded: {num:*<10}")
print(f"An f-string with width=10
aligned left and rounded to 2 places:
{fnum:.2f}")
Checking Substring with Membership
tststr="The quick brown fox"
#Membership operator
print("quick" in tststr)
print("quick" not in tststr)
Syntax:
print ("yes")
print("no")
else: # otherwise
print("maybe")
Example:
a=22
if(a>9):
print("greater")
else:
print("lesser")
RELATIONAL OPERATORS
==: equals.
LOGICAL OPERATORS
ELIF CLAUSE
elif in python means [else if]. An if statements can be chained together with
a lot of
if (condition1):
#code
#code
elif(condition3):
#code
else:
#code
IMPORTANT NOTES:
2. Last else is executed only if all the conditions inside elifs fail.
if-elif-else (SYNTAX)
if(condition):
Statement1
elif(condition):
Statement2
else:
StatementN Ap
Conditional Statements
Grade students based on marks
marks >= 90, grade = “A”
90 > marks >= 80, grade = “B”
80 > marks >= 70, grade = “C”
70 > marks, grade = “D”
Practice Set of Conditional Statemnets:
1. Write a program to find the greatest of four numbers entered by the user.
2. Write a program to find out whether a student has passed or failed if it requires a
total of 40% and at least 33% in each subject to pass. Assume 3 subjects and
take marks as an input from the user.
3. A spam comment is defined as a text containing following keywords:
“Make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program
to detect these spams.
4. Write a program to find whether a given username contains less than 10
characters or not.
5. Write a program which finds out whether a given name is present in a list or not.
6. Write a program to calculate the grade of a student from his marks from the
following scheme:
90 – 100 => Ex
80 – 90 => A
70 – 80 => B
60 – 70 =>C
50 – 60 => D
<50 => F
7. Write a program to find out whether a given post is talking about “Harry” or not.
Chapter 3 – Practice Set
1. Write a python program to display a user entered name followed by Good
Afternoon using input () function.
2. Write a program to fill in a letter template given below with name and date.
letter = '''
Dear <|Name|>,
You are selected!
<|Date|>
'''
3. Write a program to detect double space in a string.
4. Replace the double space from problem 3 with single spaces.
5. Write a program to format the following letter using escape sequence characters.
letter = "Dear Harry, this python course is nice. Thanks!"
1. WAP to input user’s first name & print its length.
2. WAP to find the occurrence of ‘$’ in a String.
3. WAP to check if a number entered by the user is odd or even.
4. WAP to find the greatest of 3 numbers entered by the user.
5. WAP to check if a number is a multiple of 7 or not.
CHAPTER 04 – LISTS
Lists in Python
A built-in data type that stores set of values
It can store elements of different types (integer, float, string, etc.)
Created by using []
May also be created using list() constructor (arg=iterable)
Allow duplicate members.
List vs String
String List
Immutable (cannot be changed) Mutable (can be changed, added to, or
Stores only characters (textual data) removed from)
Sore elements of different types
List(): is a list constructor
List=[ ]
Tuple=( )
Example:
marks = [87, 64, 33, 95, 76]
#marks[0], marks[1]..
student = [”Karan”, 85, “Delhi”] #student[0], student[1]..
student[0] = “Arjun” #allowed in python
len(student) #returns length
List indexing
A list can be indexed just like a string. Its mean ordered indexed iterated (loops)
Lists are: ordered, indexed and changeable
l1 = [7,9,"harry"]
l1[0] # 7
l1[1] # 9
l1[70] # error
l1[0:2] # [7,9] #list slicing
Note:
While loop runs while the condition is true.
mylist=["House 123", "Lane 5", "Peshware Road", "Rawalpindi", 54600]
print(mylist, type(mylist), len(mylist))
Iterating with for loop Iterating with while loop
student=["Ali", "Ahmad", student=["Ali", "Ahmad",
"Kashif","Tanveer"] "Kashif","Tanveer"]
for i in student: i=0
print(i) while(i<len(student)):
print(student[i])
for i in range(len(student)): i+=1
# print(i) #Give us the index of list
print(student[i])
# list are change able
mylist=["House 123", "Lane 5", "Peshware Road", "Rawalpindi", 54600]
print(mylist, type(mylist), len(mylist))
mylist[2]=300
print(mylist)
List Slicing
Similar to String Slicing
list_name[ starting_idx : ending_idx ] #ending idx is not included
marks = [87, 64, 33, 95, 76]
marks[ 1 : 4 ] is [64, 33, 95]
marks[ : 4 ] is same as marks[ 0 : 4]
marks[ 1 : ] is same as marks[ 1 : len(marks) ]
marks[ -3 : -1 ] is [33, 95]
Example of membership operator:
mylist=["The", "quick", "brown", "fox"]
#membership operators
print("quick" in mylist)
print("quick" not in mylist)
#List slicing using index
#
sublist=mylist[1:3]
print(sublist)
restlist=mylist[2:]
print(restlist)
leftlist=mylist[:3]
print(leftlist)
#
# Indexing from the end. End not included
#
endlist=mylist[-3:-1]
print(endlist)
endlist=mylist[-3:]
print(endlist)
#
# list concatenation
#
newlist=mylist+mylist
print(newlist)
Lists - Modification
# A value can be change
fruitelist=["Apple", "banana", "cherry", "orange", "kiwi", "mango"]
print(fruitelist)
fruitelist[1]="blackcurrant"
print(fruitelist)
#
# Changing range of list values
# [1:3] is slicing operator that 3 is not include int it
fruitelist[1:3]=["blackcurrant", "watermelon"]
print(fruitelist)
# Change the second value by replacing it with two new values. The list
shrinks:
fruitelist[1:2]=["apricot", "falsa"] #Index 1 value will replace with 2 values
print(fruitelist)
#Replace the 2nd and 3rd values by a single one. The list shrinks:
fruitelist[1:3]=["kinnow"] #Index 1 values will replaced with one value.
print(fruitelist)
List methods
1. [Link](4) #adds one element at the end
2. [Link]( ) #sorts in ascending order
3. [Link]( reverse=True ) #sorts in descending order
4. [Link]( ) #reverses list
5. [Link]( idx, el ) #insert element at index
6. [Link](1) #removes first occurrence of element
7. [Link]( idx ) #removes element at idx
Note:
The datatypes which are immutable/not changeable that’s are not make changes in
the original data.
e.g. string
The datatypes which are mutable/changeable that’s are making change in the
original data.
e.g. list
Program of All method:
my_list=[1, 2, 3, 4, 6, 7, 8, 1, 3, 4]
#1. Append ()
# print(f"List befor append {my_list}")
# my_list.append(10)
# print(f"List after append {my_list}")
#4. reverse()
# print(f"List before reverse {my_list}")
# my_list.reverse()
# print(f"List after reverse {my_list}")
#6. remove(val)
# print(f"List before remove {my_list}")
# my_list.remove(1)
# print(f"List after remove {my_list}")
#7. pop(indx_value)
print(f"List before pop {my_list}")
my_list.pop(4)
print(f"List after pop {my_list}")
Lists Methods – Insertion
Adding elements and extending lists
insert(position, value)
append(value)
extend(iterable) iterable = any Python iterable
# List method
#Inserting values without replacing use of insert() method
fruitelist=["Apple", "banana", "cherry", "orange", "kiwi", "mango"]
print(fruitelist)
[Link](2, "Fox")
print(fruitelist)
#Using the append () method to append an item
[Link]("kinnow")
print(fruitelist)
# Extending a list by adding another list
dryfruits =["Almonds", "Pistachios", "Walnuts"]
[Link](dryfruits)
print(fruitelist)
#1. Can be extend using any other iterable
[Link]("This") # Using string as iterable. Insert characters
print(fruitelist)
#2. using tuple to extend. Each value become list element
[Link]((1,2,3))
print(fruitelist)
Lists Methods – Deletion
Deleting elements:
remove(value)
pop() Removing by index
No index specified. Last element removed
def myfunc(n):
return 100-abs(n)
[Link](key=myfunc)
print(f"Numerical list after sorting using a function:\n {myNums}")
Note: While sorting there must be same types of element in the list
Copying Lists
• Trimming & trailing white space:
• Simply creates a reference to the original list list1=list2
• Need to do a deep copy
• Alternatives are:
copy() method
list() constructor method based on any iterable list(name_list)
using the slice operator [:] which fools the direct copy
Way of copy Syntax
Using reference to the original list list2=list1
Using the copy method list2=[Link]()
Using the list () constructor list2=list(list1)
Using the slicing operator [:] list2=list1[:]
Program:
# List copying
fruitelist1=["Apple", "banana", "cherry", "orange", "kiwi", "mango"]
#1. reference to the original list
fruitelist2=fruitelist1
fruitelist1[0]="Watermelon"
print(f"Shallow: {fruitelist1 = }")
print( f" {fruitelist2 = }\n") # No good. shalow copy
# Using the copy method
fruitelist1=["banana", "cherry","apple", "orange", "kiwi"]
fruitelist2=[Link]()
fruitelist1[0]="Watermelon"
print(f"Copy method: {fruitelist1 =}")
print(f"Second list: {fruitelist2 =}\n")
dtuple=(1,2,1,3)
print(f"{dtuple =}")
Tuple Indexing
# Tuples are ordered, indexed and NOT changeable
With For loop With for loop with range() With while loop
mytuple = ("House mytuple = ("House 123", mytuple = ("House 123",
123", "Lane 5", "Lane 5", "Peshawar "Lane 5", "Peshawar
"Peshawar Road", Road", "Rawalpindi", Road", "Rawalpindi",
"Rawalpindi", 54600) 54600) 54600)
# i=0
# while i < len(mytuple):
# print(mytuple[i])
# i=i+1 #i+=1
lefttuple = mytuple[:3]
print(lefttuple)
# Indexing from the end. End not included
endtuple = mytuple[-3:-1]
print(endtuple)
endtuple = mytuple[-3:]
print(endtuple)
# Tuple concatenation
newtuple= mytuple + mytuple
print(newtuple)
Tuple: Changing
Convert tuple into list and vice versa.
Tuple into List List into Tuple
fruite=("Mango", "Apple", "Orange") fruite=["Mango","Apple", "Cherry",
"Orange"]
print(type(fruite)) #Tuple
print(type(fruite)) #List
fruite=list(fruite) #Conversion
print(type(fruite)) #List fruite=tuple(fruite) #Conversion
print(type(fruite)) #Tuple
# Tuples are immutable. A value cannot be changed
fruittuple = ("apple", "banana", "cherry", "orange", "kiwi", "mango")
print(fruittuple)
Note: It will reassign the tuple (first) Note: It will create a new tuple and
store combine value
Packing & Unpacking Tuples
Next time{
# Unpacking tuples
# Defining a tuple is called "packing"
# Unpacking tuples
f1, f2, f3, f4, f5, f6 = fruittuple
print(f"{f1=}, {f2=}, {f3=}, {f4=}, {f5=}, {f6=}")
# If the number of elements on the LHS are less, using * will put the remaining
into a list
# Unpacking strings
stdstr = "MyString"
print(stdstr)
# firsttuple = (1,2,3)
# secondtuple = (4, 5, 6)
# thirdtuple = firsttuple + secondtuple
# fourthtuple = 2 * firsttuple
# print(f"{firsttuple=}, \n{secondtuple=}, \n{thirdtuple=}, \n{fourthtuple=}")
mytuple = (1, 2, 3, 1, 2, 3, 1, 2)
print(f"mytuple = {mytuple}")
print(f"Count:\nThe number 1 occurs {[Link](1)} times")
print(f"The number 3 occurs {[Link](3)} times")
print(f"Index:\nThe number 2 occurs at index {[Link](2)}")
or
print(f"The index position of the first occurence of value 3 is:
{[Link](3)}")
# And being consistent, Python functions len, type and del apply:
print(f"The type of mytuple is {type(mytuple)}")
print(f"The length of mytuple is {len(mytuple)}")
fourth_dict=dict()
print(f"Empty dictionary created using dict() constructor: {fourth_dict= }\n")
#Using Standard Python Function
print(f"{len(first_dict)= },{type(first_dict) =}\n")
Following are method to create empty lists, tuples and dictionaries in python
Empty List Empty Tuple Empty Dictionary
#1. My_list=[] #1. My_tuple=() #1. My_dict={}
#2. My_list=list() #2. My_tuple=tuple() #2. My_dict=dict{}
Accessing Dictionary Items
#Accessing Dictionary Items
Items can be accessed using their key:
1. Value = dictionary[key]
Or using the get() method:
2. Value = [Link](key)
All keys obtained as special list using method:
3. [Link]()
All values obtained as special list using method:
4. [Link]()
All key:value pairs obtained using method:
5. [Link]()
Dictionary all accessing method
Name Work
Dictionary_name[“key”] Give the values of that key
Dictionary_name.get(“key”) Give the values of that key
Dictionary_name.keys() Give all keys of Dictionary
Dictionary_name.values() Give all values of keys of dictionary
Dictionary_name.items() Give all values and keys dictionary
Example of code
#Accessing Dictionary Items
first_dict={
"play": "Hamlet",
"author": "Shakespear",
"year": 1600
}
print(first_dict['play']) # return play key value
print(first_dict.get("play")) # return play key value
print(first_dict.keys()) # return all keys of dictionary
print(first_dict.values()) # return all values of keys of dictionary
print(first_dict.items()) # return all values and keys of dictionary
Program:
#Creating dictionary
first_dict={
"play":"Hamlet",
"author": "Shakespeare",
"year": 1600
}
#Access an item using key
print(f"The value of the key 'play' is {first_dict['play']}\n")
#Uisng get() method
print(f"The value of the key 'play', using the get() method is:
{first_dict.get('play')}\n")
# All keys can be obtained as a dict_keys list object using the keys() method
print(f"The keys of the dictionary are: {first_dict.keys()}\n")
# All values can be obtained as a dict_values list object using the values() method
print(f"The values of the dictionary are: {first_dict.values()}\n")
# All key:value pairs can be obtained as a list of tuples using the items() method
print(f"The key:value pairs in the dictionary are: \n{first_dict.items()}\n")
Finding Dictionary Items
- Items can be found using membership operator (works on the keys of the
dictionary)
- Be careful with keys having mixed data types!
- Preferable to have keys of the same data type (like a dictionary!)
Program:
#Creating dictionary
first_dict={
"play":"Hamlet",
"author": "Shakespeare",
"year": 1600,
1: 1000
}
# Prompt user to enter a key
find_key = input("Which key would you like to find? ")
# Check if the key exists in the dictionary
if find_key in first_dict:
print(f"\nFound! The value of the key '{find_key}' is: {first_dict[find_key]}\n")
else:
# It is preferable to have keys of the same data type otherwise extra
#programing is needed.
if find_key.isnumeric():
find_key=int(find_key)
if find_key in first_dict:
print(f"\nFound! The value of the key '{find_key}' is: {first_dict[find_key]}\
n")
else:
print(f"\nKey '{find_key}' does not exist in the dictionary\n")
Note: See it again Cs306 Lecture 80
# Finding Dictionary Items
Note: My program
first_dict={
"play": "Hamlet",
"author": "Shakespear",
"year": 1600
}
find_key = input("Which key would you like to find? ")
if find_key in first_dict:
print(f"\nFound! The value of find key {find_key} is: {first_dict[find_key]}\n")
else:
print("Not Found")
# Creating a nested dictionary, using key:value pairs where each value is itself a
dictionary
my_class = {"std1": student1, "std2": student2, "std3": student3}
print(f"Nested dictionaries: \n{my_class = }\n")
#Accessing items from nested dictionaries. Use key names for outer and inner dicts
print(f"{my_class['std1']['name']=}\n")
print(neighborhood["house1"]["address"]["mohalla"])
# Creating a new dictionary from a list of keys with the same value for every key
my_dict = [Link](key_list,"Ford")
print(f"Dictionary created from a key list with a value provided: \n{my_dict}\n")
# setdefault(key,value)
# Returns the value for the key provided
val = my_dict.setdefault("model")
print(f"The setdefault method returns the value associated with 'model': {val}")
#
# If the key exists, the existing value is returned and the provided value ignored.
No other change
#
val = my_dict.setdefault("model", "Fairlane")
print(f"The setdefault method returns the value associated with 'model', ignoring
the value in the calling statement: {val}")
# If the key does not exist, it is created and a value (if provided) is assigned
#
val=my_dict.setdefault("cartype", "saloon")
print(f"If the key does not exist, it is created and a value (if provided) is assigned:\
nThus my_dict.setdefault('cartype', 'saloon') changes the dictionary to: \
n{my_dict}\n")
print(f"and the value returned is: {val}\n")
my_car['brand'] = 'Mercedes'
my_car['model'] = 'E class'
print(f"Two values updated. The car_values is a view and shows updated values:\
n{car_values}\n")
#3. And add a new key
my_car['interior'] = "leather"
print(f"A new key added. The car_keys is a view and shows updated keys:\
n{car_keys}\n")
# And finally, car_items is a view of the dictionary items and is also updated:
print(f"The car_items is also a view and stays updated:\n{car_items}\n")
CHAPTER 07 – SETS
Sets in python
Set is the collection of the: unordered items.
- Created using set() or {} (but {} creates a dict, not an empty set)
We can store followings in the sets:
1. boolean
2. integer
3. float
4. string
5. tuple
Followings can't be store in the set:
1. List
2. Dictionary
Example:
nums = { 1, 2, 3, 4 }
set2 = { 1, 2, 2, 2 }
#repeated elements stored only once, so it resolved to {1, 2}
null_set = set( ) #empty set syntax
Note:
Unordered mean no index
Set: Mutable
Properties of sets
1. Hold mixed data types
2. Sets are unordered => Element’s order doesn’t matter
3. Sets are unindexed => Cannot access elements by index
4. There is no way to change items in sets.
5. Sets cannot contain duplicate values. Or Each element in the set must be unique
&
Example:
# Creating a set using {}
set1 = {1, 2, 3, 4}
print(f"A set created using braces: {set1 = }")
set2 = {"a", "b", 100}
print(f"A set created using braces: {set2 = }\n")
# Creating an empty set using set() constructor. Cannot use {} due to ...
set3 = set()
print(f"An empty set created using the constructor: {set3 = }\n")
# Creating a set using the set constructor on an iterateable
list1 = [1, 2, 3, "Fox"]
set4 = set(list1)
print(f"A set constructed using the constructor on a list:\n\t{list1 = }\n\t{set4 = }\
n")
Set Method:
Consider the following set: s = {1,8,2,3}
[Link]( el ) #adds an element
[Link]( el ) #removes the elem an
[Link]( ) #empties the set
[Link]( ) #removes a random value
Example of all above method:
#All Method of set
set_number={1,2,3,4,5,6}
#1. len()
print(f"Length of set is: {len(set_number)}")
#2. remove()
set_number.remove(3)
print(f"After removing elemnet 3 from the set: {set_number}")
#3. add()
set_number.add(3)
print(f"After adding element 3 in the set: {set_number} ")
#4. pop()
set_number.pop()
print(f"Use of pop method which remove random elements: {set_number}")
#5. clear()
set_number.clear()
print(f"The use of clear method make set empty: {set_number}")
Set Union and Intersection:
[Link]( set2 ) #combines both set values & returns new
[Link]( set2 ) #combines common values & returns new
Example:
#Concept of set union and intersection
set1={1,2,3,4,5,6,7,8,9,10}
set2={2,4,6,8,10}
union_set=[Link](set2)
print(f"The union of {set1= } and {set2= } is: {union_set = }")
intersection_set=[Link](set2)
print(f"The intersection of {set1 = } and {set2 = } is {intersection_set = }")
intersection_set=[Link](set1)
print(f"The intersection of {set1 = } and {set2 = } is {intersection_set = }")
Note: Below Page 74 to 89 see this part latter.
Sets: Iterating
The only way we can iterate on set with membership operator, because sets are
unordered.
# Sets are unordered and unindexed. Hence only membership works for "cat".
# Define a set with integers and strings
set1 = {1, 2, 3, "dog", "cat", "owl"}
# Iterate through each element in the set
for x in set1:
# Check if the current element is "cat"
if x == "cat":
print(f"Found the cat! {x}") # Special message when "cat" is found
else:
print(f"Not the cat: {x}") # Message for all other elements
# (1, True) treated differently from (False, 0): whichever comes first
set3 = {1, "Fox", True, "Good morning", False, 0, "dog"}
print(f"Again, either 0 or False is kept: {set3 = }\n")
if 0 in set3:
set3 = {False, 1, 'Fox', 'dog', 'Good morning'}
print("0 exists but prints as False!\n")
# Finally, the usual Python functions apply:
print(f"set3 = \n{type(set3)=}, {len(set3)=}\n")
Sets: Adding
set1 = {1, 2, 3}
print(f"set1 = {set1}\n")
# Set3 union Set1 results in nothing new since all elements are duplicates
print(f"set3 union set1 gives nothing new: {set4 =}\n") # No change so set
print(f"The union of {set1} with the tuple {tuple1} and list {list1} gives:\n{set7}\
n")
Sets: Intersection
Set methods - Intersection()
- Returns a new set with common elements
- Works with multiple arguments and other iterables
- Shorthand: & (only works with sets)
- Intersection_update()
- Changes* the calling set
The intersection_update() method updates the original set by keeping only the
elements that are common between the set and another set (or iterable).
Program:
# The intersection method returns a new set with elements that are present in both
sets
#
set1 = {1, 2, 3}
set2 = {1, 3, 5, 7}
set3 = [Link](set2)
set4 = [Link](set1)
print("The intersection method returns a new set containing common elements
only. Thus:")
print(f"\tset1 = {set1}\nintersection\n\tset2 = {set2}\ngives\n\tset3 = {set3}")
set1 = {1, 2, 3}
set2 = {1, 3, 5, 7}
set3 = [Link](set2)
set4 = [Link](set1)
print(f"The difference method returns a new set containing values present only\n in
the calling set in one [Link]: \n\t{set1= } \ndifference\n\t{set2= }\ngive\n\t{set3=
}")
print(f"And interestingly:\n\t{set2= }\ndifference\n\t{set1= }\ngives\n\t{set4= }")
set3 = set1.symmetric_difference(set2)
set1.symmetric_difference_update(set2)
Sets: Methods
Set Methods
• Copy() – returns a copy of a set (deep copy)
• Isdisjoint() – whether two sets have common elements
• Issubset() – whether one set is a subset of the other
• Issuperset() – whether one set is a superset of the other
• Frozenset() – constructor for a frozen set
Program:
# Miscellaneous set methods
set1 = {1, 2, 3, 4}
set2 = set1
[Link](100)
print(f"A shallow copy does not work:, {set1= }, {set2= }\n")
set3 = [Link]()
[Link](200)
print(f"The copy() method works and returns a new set:\n\t{set1=}\n\t{set3= }")
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {4, 5, 6}
#issubset
# issubset() returns True if the calling set is a subset of the given set
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(f"issubset() returns True if the calling set is a subset of the argument: \n\
t{set1= }\n\t{set2= }\n")
print(f"\t{[Link](set2)= }\n\t{[Link](set1)= }")
#issuperset()
# issuperset() returns True if the calling set is a superset of the given set
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
Note:
Types Of Loops
Primarily there are two types of loops in python.
• while loops
• for loops
While Loop
Syntax:
while (some condition is true): # The block keeps executing until the
condition is true
optional: break
continue
else
#use of while loop #use of while loop
# break, continue # break, continue
i=100 i=100
while(i>0): while(i>0):
print(i) print(i)
i-=7 i-=7
if(i<50): if(i<20):
break continue
print("Still in the loop")
else:
print("Loop has ended")
Note: when we use break in the loop then else is not execute.
Harry College
Syntax:
while (condition): # The block
keeps executing until the
condition is true
#Body of the loop
In while loops, the condition is checked first. If it evaluates to true,
the body of the loop is executed otherwise not!
Let‘s Practice:
College Page 02
Harry College
THE BREAK STATEMENT: Break & Continue
‘break’ is used to come out of the Break: used to terminate the
loop when encountered. It instructs loop when encountered.
the program to – exit the loop now. Continue: terminates execution
Example: in the current iteration &
for i in range (0,80): continues execution of the
print(i) loopwith the next iteration.
# this will print 0,1,2 and 3 Example:
if i==3 take search example & stop the
break search when found print all numbers
but not multiple of 3
THE CONTINUE STATEMENT:
‘continue’ is used to stop the current
iteration of the loop and continue
with the next
one. It instructs the Program to “skip
this iteration”.
Example:
for i in range(4):
print("printing")
if i == 2: # if i is 2, the iteration is
skipped
continue
print(i)
PASS STATEMENT: pass Statement:
pass is a null statement in python. pass is a null statement that does
It instructs to “do nothing”. nothing. It is used as a placeholder
Example: for future code.
l = [1,7,8] for el in range(10):
for item in l: pass
pass Let‘s Practice:
# without pass, the program will P 09
throw an error
Quick Quiz:
Example:
i=0
print("Harry")
i=i+1
Note: If the condition never become false, the loop keeps getting executed.
Quick Quiz: Write a program to print the content of a list using while loops.
??
Syntax:
range (number)
through
i in range (number)
• Useful in for-loops
Program:
#The range function and membership operator
x=range(100)
print(x, type(x))
guess =int(input("Please enter a number: "))
if(guess in x):
print("The membership operator return ", guess in x)
print("The number entered is in range ")
else:
print("The number entered is not in range")
Range Function Harry and College part:
Harry College
RANGE FUNCTION IN PYTHON: range( )
The range() function in python is Range functions returns a sequence
used to generate a sequence of of numbers, starting from 0 by
number. default, and increments by1 (by
default), and stops before a
We can also specify the start, stop specified number.
and step-size as follows: range( start?, stop, step?)
range(start, stop, step_size)
# step_size is usually not used with
range()
AN EXAMPLE DEMONSTRATING
RANGE () FUNCTION.
for i in range(0,7): # range(7) can
also be used. print(i) #
prints 0 to 6
Let‘s Practice:
College P 7
For Loop
Note:
While loop run on condition and for loop run on iteration.
Syntax:
optional: break
continue
else
Harry College
A for loop is used to iterate through Loops are used used for sequential
a sequence like list, tuple, or string traversal. For traversing list, string,
[iterables] tuples etc
Syntax: Syntax:
l = [1, 7, 8] for Loops
for item in l: for el in list:
print(item) # prints 1, 7 and 8 #some work
Example:
AN EXAMPLE DEMONSTRATING
RANGE () FUNCTION.
for i in range(0,7): # range(7) can
also be used.
print(i) # prints 0 to 6
FOR LOOP WITH ELSE for Loop with else:
An optional else can be used with a Syntax:
for loop if the code is to be executed for el in list:
when the #some work
loops exhausts. else:
Example: #work when loop ends
l= [1,7,8] Example:
for item in l:
print(item)
else:
print("done") # this is printed when
the loop exhausts! Note:
Output: else used as it doesn’t execute when
1 break is used
7
8
done
Some Notes for Loops:
In Python, for loops are used for definite iteration (when the number of
iterations is known in advance), and while loops are used for indefinite
iteration (when the loop continues as long as a certain condition is True)
In Python, the else block is used with a for loop (forming a for-else construct)
to execute a block of code only if the loop completes its iterations normally,
without encountering a break statement
Syntax:
Let‘s Practice:
College P 5
Program:
# for loop
#Computing factorial
2. Write a program to greet all the person names stored in a list ‘l’ and which
starts
with S.
5. Write a program to find the sum of first n natural numbers using while
loop.
6. Write a program to calculate the factorial of a given number using for loop.
*
***
***** for n = 3
**
*** for n = 3
***
* * for n = 3
***
order.
CHAPTER 09 – Files
Files in Python
Note:
Code with harry: Chapter 9 Page 36
Apna College Lecture 7
Cs306 Lecture 88
CHAPTER 10 – Modules
{ ((See cs306 Lecture 99)
MODULES
A module is a file containing code written by somebody else (usually) which can
be imported and used in our programs.
PIP
Pip is the package manager for python. You can use pip to install a module on your
system.
pip install flask #Installs Flask Module
TYPES OF MODULES
There are two types of modules in Python.
1. Built in Modules (Preinstalled in Python)
2. External Modules (Need to install using pip)
Some examples of built in modules are os, random etc.
Some examples of external modules are tensorflow, flask etc.
}