0% found this document useful (0 votes)
4 views104 pages

CS306 Programming With Python

The document provides an introduction to programming in Python, covering basic concepts such as programs, interpreted languages, comments, variables, data types, and operators. It includes practical exercises for readers to apply their knowledge, as well as detailed explanations of string manipulation, including methods for string slicing, case conversion, and trimming. The content is structured into chapters, with each chapter focusing on specific programming concepts and practices in Python.

Uploaded by

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

CS306 Programming With Python

The document provides an introduction to programming in Python, covering basic concepts such as programs, interpreted languages, comments, variables, data types, and operators. It includes practical exercises for readers to apply their knowledge, as well as detailed explanations of string manipulation, including methods for string slicing, case conversion, and trimming. The content is structured into chapters, with each chapter focusing on specific programming concepts and practices in Python.

Uploaded by

Tanveer Abbas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programming Using 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

For exit, type: exit()

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.).

Variable Naming Conventions Rules for choosing an identifier


 Must start with letters or  A variable name can contain
underscore character alphabets, digits, and
 Cannot start with a number underscores.
 Contain only alphanumeric  A variable name can only start
characters and underscores with an alphabet and
 Case-sensitive underscores.
 The type of a variable can be  A variable name can’t start with
forced by casting the RHS a digit.
 No while space is allowed to be
used inside a variable name.

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.

complex(real It creates a complex number.


[imag])
str(y) It converts y to a string.

tuple(y) It converts y to a tuple.


list(y) It converts y to a list.
set(y) It converts y to a set.
dict(y) It creates a dictionary and y should be a sequence of (key, value)
tuples.
ord(y) It converts a character into an integer.
hex(y) It converts an integer to a hexadecimal string.
oct(y) It converts an integer to an octal string.
Chapter 2 – Practice Set
1. Write a python program to add two numbers.
2. WAP to input side of a square & print its area.
3. WAP to input 2 floating point numbers & print their average
4. WAP to input 2 int numbers, a and b. Print True if a is greater than or equal
to b. If not print False
5. Write a python program to find remainder when a number is divided by z.
6. Check the type of variable assigned using input () function.
7. Use comparison operator to find out whether ‘a’ given variable a is greater
than
8. ‘b’ or not. Take a = 34 and b = 80
9. Write a python program to find an average of two numbers entered by the
user.
[Link] a python program to calculate the square of a number entered by the
user.
CHAPTER 03 – STRINGS Part 01
String
String is data type that stores a sequence of characters and enclosed in quotes.
Strings are immutable/can’t be modify.
We can primarily write a string in these three ways:
a ='harry' # Single quoted string
b = "harry" # Double quoted string
c = '''harry''' # Triple quoted string
String as Array
A string can be treated as array using indexing.
Program 01:

Str1="Tanveer" #<<<<<<< String >>>>>>>


str="Tanveer"
strlen=len(str1) strlen=len(str)
print(str1, strlen) print(f"{str= }\n{len(str)= }")
for i in range(strlen): # use of index for i in range(7):
print(str1[i]) print(str[i])
#Using membership operator
Str1="Tanveer"
for c in str1:
# ignor all vowles and white space
if c not in "aiou ": # remove all vowles and spaces
print(c)
# extract the sub string
str="Tanveer"
substr=str1[1:5] # (anve) last index is not included
print(substr)
Program 02:
# A string can be treated as array using indexing
str1="This is a test:"
str2=str1[0:4]+ 'z'+ str1[4:len(str1)] # to geting sub string
print(str2)
Escape Sequences
Sequence of characters after backslash "\" → Escape Sequence characters.
Escape Sequence characters comprise of more than one character but represent one
character when used within the strings.
\n New line
\t Tab
\r Carriage return
It moves the cursor to the beginning of the current line without moving to a new
line.
\f Form feed
It is used to move the printer or display to the next page (historically used in
printers).
\' Single quote
\" Double quote
\\ Backslash
\nnn Octal value
\xnn Hexadecimal value
Program 01
str1="This is string with \n a newline embedded."
print(str1)
str2="This is string with \t a tab embedded."
print(str2)
str3="A string with cariage \r return embedded."
print(str3)
str4="A string with formfeed \f embedded."
print(str4)
str5="This is string in a double with a \"quotes\" word embedded inside"
print(str5)
str6="What if we need to ambed a \"\\\" "
print(str6)
str7="A string with a octal value: \150"
print(str7)
str8="A string with a hex value: \x49"
print(str8)
String concatenation
“hello” + “world”
String length
len(str)
String slicing
A string in python can be sliced for getting a part of the strings.
Accessing parts of a string is called slicing.

The index in a sting starts from 0 to (length -1) in Python.


In order to slice a string, we use the following syntax:

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()

Definition: Removes all trailing (right-side) whitespace characters from a


string.
Details: It trims spaces, tabs, or newline characters from the end only.

 strip()

Definition: Removes both leading and trailing whitespace characters from a


string.

Details: It’s essentially a combination of lstrip() and rstrip().

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() Finds string and returns index (0 based)


Syntax Example
Find(“any word) Find(“n”
Find(“My name”)
Str="My name is Tanveer"

#Find()
str1=[Link]("are") #-1 mean not found
print(str1)

index() Same as find() but raises exception if not found


Syntax Example
index(“any word) index(“n”
index(“My name”)
Str="My name is Tanveer"

#2. Index
str2=[Link]("ni") #Error
print(str2)

rfind() Finds last location of string and returns index (0 based)


Syntax Example
rfind(“any word) rfind (“n”
rfind (“My name”)
Str="My name is Tanveer"

str2=Str. rfind ("ani") #-1 mean not


found
print(str2)

rindex() Same as rfind() but raises exception if not found


Syntax Example
rindex(“any word) rindex(“n”
rindex(“My name”)
Str="My name is Tanveer"

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)

# return -1 if not found


if n != -1:
print(lookfor, "occures at position",n)
else:
print(lookfor, "is not in the string")
Program of index():
# with the use of index()
# index() does the same thing but throws an ex
n=[Link](lookfor)
print(n)
n=[Link](lookfor)
print(n)
n=[Link](lookfor)
print(n)
# return -1 if not found

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)

# String slicing using index


substr=tststr[5:11]
print(substr)
reststr=tststr[5:]
print(reststr)
lefttstr=tststr[:5]
print(lefttstr)
#
# Indexed from the end. End is not include
endstr=tststr[-5:-1]
print(endstr)
endstr=tststr[-5:len(tststr)]
print(endstr)
#
# String cancatanation
newstr=tststr+tststr
print(newstr)
Determining the Type of a String
isalnum() True if alphanumeric string
isalpha() True if alphabetic string
isascii() True if ascii string
isdecimal() True if all characters are decimals
isdigit() True if all characters are digits
isnumeric() True if all characters are digits
isidentifier() True if can be the name of a variable
islower() True if all characters are lower case
isupper() True if all characters are uppercase
isprintable() True if all characters are printable
isspace() True if all characters are white space
istitle() True if string is title case
Program:
Note:
Isdecimal():
Isdigit():
Isnumeric():
#
#tststr="Abc123"
tststr="\u00B2" # Subscripts
print(tststr)
print(f"{[Link]()=}") # true if alphanumeric string
print(f"{[Link]()=}") # true if alphabetic string
print(f"{[Link]()=}") # true if ascii string
print(f"{[Link]()=}") # True if alla characters are decimal
print(f"{[Link]()=}") # true if
print(f"{[Link]()=}") #true if
print(f"{[Link]()=}") # true if can be the name of variable
print(f"{[Link]()=}")
print(f"{[Link]()=}")
print(f"{[Link]()=}")
print(f"{[Link]()=}")
print(f"{[Link]()=}")
Conditional Statements
If else and elif statements are a multiway decision taken by our program due
to certain conditions in our code.

Syntax:

if (condition1): # if condition1 is True

print ("yes")

elif(condition2): # if condition2 is True

print("no")

else: # otherwise

print("maybe")

Example:

a=22

if(a>9):
print("greater")

else:

print("lesser")

RELATIONAL OPERATORS

Relational Operators are used to evaluate conditions inside the if statements.


Some

examples of relational operators are:

==: equals.

> =: greater than/ equal to.

< =: lesser than/ equal to.

LOGICAL OPERATORS

In python logical operators operate on conditional statements. For Example:

• and – true if both operands are true else false.

• or – true if at least one operand is true or else false.

• not – inverts true to false & false to true.

ELIF CLAUSE

elif in python means [else if]. An if statements can be chained together with
a lot of

these elif statements followed by an else statement.

if (condition1):

#code

elif (condition2): # this ladder will stop once a condition in an if or elif is


met.

#code

elif(condition3):

#code

else:

#code
IMPORTANT NOTES:

1. There can be any number of elif statements.

2. Last else is executed only if all the conditions inside elifs fail.

Apna College: Conditional Statements

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}")

#2. sort(): Assending order


# print(f"List before sort {my_list}")
# my_list.sort()
# print(f"List sfter sort {my_list}")

#3. sort (reverser=True): Decending order


# print(f"List before sort {my_list}")
# my_list.sort(reverse=True)
# print(f"LIst after sort {my_list}")

#4. reverse()
# print(f"List before reverse {my_list}")
# my_list.reverse()
# print(f"List after reverse {my_list}")

#5. insert(indx, val)


# print(f"List before insert {my_list}")
# my_list.insert(3, 100)
# print(f"List after insert {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

clear() It will delete the elements from the list


del name_list It will delete the entire list from the memory
del list[index]
Q: What id difference between delete and remove method?
ANS:
1. Delete: Delete the entire list from the memory
2. Remove: Delete the elements from the list
Program:
fruitelist=["Apple", "banana", "cherry", "orange", "kiwi", "mango"]
print(fruitelist)
[Link]("orange")
print(fruitelist)
# Only the first occurance is removed
[Link](fruitelist)
print(fruitelist)
[Link]("Apple")
print(fruitelist)
# Removing by index: pop()
[Link](3)
print(fruitelist)
[Link]() # No index specified. Last element removed
print(fruitelist)
#Empty a list
[Link]()
print(fruitelist) # List is now empty
#del function
fruitelist=["Apple", "banana", "cherry", "orange", "kiwi", "mango"]
print(fruitelist)
#
# Deleting an elemnst using index or range of indices
#
del fruitelist[0]
print(fruitelist)
del fruitelist[0:2]
print(fruitelist)
#Delete entire list
del fruitelist
print(fruitelist) # Now we will get an error becaues the list no longer exists
{ List Comprehension
 Shortcut for creating lists based on condition
newlist = [expression for item in iterable if condition = True]
 Very powerful construct
Program:
# List comprehension
fruitelist=["Apple", "banana", "cherry", "orange", "kiwi", "mango"]
#
# Create a new list for fruitelist without an o in theire name. First with loop
myfruitlist=[]
for x in fruitelist:
if "o" not in x:
[Link](x)
print(f"{fruitelist=}")
print(f"{myfruitlist =}")
#
# Now using list comprehension with expresion x+X
#
myfruitlist2= [x for x in fruitelist if "o" not in x]
print(f"{myfruitlist2 =}")
#
#Specifing a condition is not necessary
#
myfruitlist3=[x+x+x for x in fruitelist]
print(f"{myfruitlist3 =}")
#
# Using an iterable to genarate a lsit
#
myecho=["Hellow," for x in range(5)]
print(f"{myecho =}")
#
# Or using the number of elements in another iterable
#
myecho=["Hellow word" for x in fruitelist]
print(f"{myecho = }")
#
# creating a list of numbers divisible by 7
#
mylist=[x for x in range(100) if x%7==0]
print(f"{mylist= }")
#
# Condition can also b applied to the expression befor a adding to the list
#
mylist=[x if x<50 else 0 for x in range(100) if x%7==0]
print(f"{mylist= }")
}

List Method - Sorting


Lists can be sorted using:
 sort()
 sort(reverse = True)
 sort(key = function)
Program:
# List sorting
fruitelist=["Apple", "banana", "cherry", "orange", "kiwi", "mango"]
print(f"List before sorting; {fruitelist}")
#1. Sort()
[Link]()
print(f"List after sorting: {fruitelist}")
#2. Sort(reverse=True)
[Link](reverse=True)
print(f"List after reverse sorting: {fruitelist}\n")
#3. sort(key = function)
# Case intensive sort
fruitelist=["Banana", "cherry", "apple", "orange", "kiwi", "mango"]
[Link]()
print(f"List after sorting:{fruitelist}")
[Link](key=[Link])
print(f"List after sorting with key: {fruitelist}\n")
#
#Numerical sort
#
myNums=[10, 9, 7, 8, -11, 12, -13]
print(f"List before sorting; {myNums}")
#1. sort()
[Link]()
print(f"List after sorting: {myNums}")
#2. sort(reverse=True)
[Link](reverse=True)
print(f"List after reverse sorting: {myNums}\n")
#3. sort(key=abs)
[Link](key=abs)
print(f"Numerical list after sorting on absolute value: {myNums}")

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")

# Using the list () constructor


fruitelist1=["banana", "cherry","apple", "orange", "kiwi"]
fruitelist2=list(fruitelist1)
fruitelist1[0]="Watermelon"
print(f"List constructor: {fruitelist1 =}")
print(f" Second list: {fruitelist2 =}\n")
# Using the slice operator
# Making deep copy
fruitelist1=["banana", "cherry","apple", "orange", "kiwi"]
fruitelist2=fruitelist1[:]
fruitelist1[0]="Watermelon"
print(f"Slice operator: {fruitelist1 =}")
print(f" Second list: {fruitelist2 =}\n")
CHAPTER 05 – TUPLES
Tuples in Python
A built-in data type that lets us create immutable sequences of values.
 Created with () or tuple()
 Single element needs a comma
 Can hold mixed data types
 Allows duplicates
tup = (87, 64, 33, 95, 76) #tup[0], tup[1]..
tup[0] = 43 #NOT allowed in python
a = () # empty tuple
a = (1,) # tuple with only one element needs a comma
a = (1,7,2) # tuple with more than one element
Note:
tuple=(1) #This is not a tuple this give us interger value
tuple=(2.4) # Not a tuple only float value
tuple=("Ali") # String
Program:
#<---- Tuple ----->
atuple=(1, "fox", 3)
btuple=tuple([1, "fox", 3])
ctuple=tuple() #Create tuple with tuple constructor
dtuple=("single")
print(f"{atuple =}")
print(f"{btuple =}")
print(f"{ctuple =}")
print(f"{dtuple =}")
#
# Duplicate values allowed

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)

print(mytuple, print(mytuple, print(mytuple,


type(mytuple), type(mytuple), type(mytuple),
len(mytuple)) len(mytuple)) len(mytuple))

# for tuple1 in mytuple: # for i in # i=0


# print(tuple1) range(len(mytuple)): # while i < len(mytuple):
# print(mytuple[i]) # print(mytuple[i])
# i=i+1 #i+=1

mytuple = ("House 123", "Lane 5", "Peshawar Road", "Rawalpindi", 54600)


# print(mytuple, type(mytuple), len(mytuple))

# for tuple1 in mytuple:


# print(tuple1)
# for i in range(len(mytuple)):
# print(mytuple[i])

# i=0
# while i < len(mytuple):
# print(mytuple[i])
# i=i+1 #i+=1

mytuple[2]=3000 #Error assignment of tuple not allowed mean tuple is


immutable.
Tuple Slicing
mytuple = ("The", "quick", "brown", "fox")
# Membership operators
print("quick" in mytuple)
print("quick" not in mytuple)
# Tuple slicing using index
subtuple = mytuple[1:3]
print(subtuple)
resttuple = mytuple[1:]
print(resttuple)

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)

# One workaround would be to convert tuple to a list, change the list


fruitlist = list(fruittuple) # Convert tuple into list with the help of list() i.e.
constructor
fruitlist[1] = "blackcurrant"
print(fruitlist)
# Using this technique, all of the list changing methods can be applied
Exception: Tuples can be extended by another tuple using assignment
fruittuple = ("apple", "banana", "cherry", "orange", "kiwi", "mango")
dryfruittuple = ("Almonds", "Pistachios", "Walnuts")
fruittuple += dryfruittuple # works because LHS becomes a new definition
print(fruittuple)
Tuple Extending with assignments Tuple Concatenation
fruittuple = ("apple", "banana", fruittuple = ("apple", "banana",
"cherry", "orange", "kiwi", "mango") "cherry", "orange", "kiwi", "mango")
dryfruittuple = ("Almonds", dryfruittuple = ("Almonds",
"Pistachios", "Walnuts") "Pistachios", "Walnuts")
fruittuple += dryfruittuple # works new_tuple=fruittuple + dryfruittuple
because LHS becomes a new definition print(new_tuple)
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"

fruittuple = ("apple", "banana", "cherry", "orange", "kiwi", "mango")


print(fruittuple)

# 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

f1, f2, f3, *f4 = fruittuple


print(f"{f1=}, {f2=}, {f3=}, {f4=}")

f1, f2, *f3, f4 = fruittuple


print(f"{f1=}, {f2=}, {f3=}, {f4=}")

*f1, f2, f3, f4 = fruittuple


print(f"{f1=}, {f2=}, {f3=}, {f4=}")
Note: Make practice of it.
Python Consistency
fruitlist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
print(fruitlist)
# A list can be unpacked by providing the correct number of variables
f1, f2, f3, f4, f5, f6 = fruitlist
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

f1, f2, f3, *f4 = fruitlist


print(f"{f1=}, {f2=}, {f3=}, {f4=}")

f1, f2, *f3, f4 = fruitlist


print(f"{f1=}, {f2=}, {f3=}, {f4=}")

*f1, f2, f3, f4 = fruitlist


print(f"{f1=}, {f2=}, {f3=}, {f4=}")

# Unpacking strings

stdstr = "MyString"
print(stdstr)

# A string can be unpacked by providing the correct number of variables


f1, f2, f3, f4, f5, f5, f7, f8 = "MyString"
print(f"{f1=}, {f2=}, {f3=}, {f4=}, {f5=}, {f6=}, {f7=}, {f8=}")

# If the number of elements on the LHS are less,


# * will put the remaining into a list with each element = single character

f1, f2, f3, *f4 = stdstr


print(f'{f1=}, {f2=}, {f3=}, {f4=}')

f1, f2, *f3, f4 = stdstr


print(f'{f1=}, {f2=}, {f3=}, {f4=}')

*f1, f2, f3, f4 = stdstr


print(f'{f1=}, {f2=}, {f3=}, {f4=}')
}
Adding & Multiplying Tuples
Two tuples can be added to give a third
• Multiplying a tuple with an integer gives a new tuple
• The same applies to lists and strings – consistent
# Adding & Multiplying Tuples

# firsttuple = (1,2,3)
# secondtuple = (4, 5, 6)
# thirdtuple = firsttuple + secondtuple
# fourthtuple = 2 * firsttuple
# print(f"{firsttuple=}, \n{secondtuple=}, \n{thirdtuple=}, \n{fourthtuple=}")

# Again, Python is consistent. Applies to lists and strings as well


#List
# firstlist = [1,2,3]
# secondlist = [4, 5, 6]
# thirdlist = firstlist + secondlist
# fourthlist = 2 * firstlist
# print(f"{firstlist=}, \n{secondlist=}, \n{thirdlist=}, \n{fourthlist=}")
# Finally, strings
firststr = "The "
secondstr = "quick"
thirdstr = firststr + secondstr
fourthstr = 2 * firststr
print(f"{firststr=}, \n{secondstr=}, \n{thirdstr=}, \n{fourthstr=}")
Tuple Methods
tup = (2, 1, 3, 1)
1. [Link]( el ) #returns index of first occurrence
e.g. [Link](1) is 1
It returns the index (position) of the first occurrence of the given element in
the tuple.
2. [Link]( el ) #counts total occurrences
e.g. [Link](1) is 2
Note: Consider it
mytuple = (1, 2, 3, 1, 2, 3, 1, 2)
print(f"Tuple= {mytuple}") #Tuple= (1, 2, 3, 1, 2, 3, 1, 2)
print(f"{mytuple= }") #mytuple= (1, 2, 3, 1, 2, 3, 1, 2)
Tuple Method
# Tuple Methods
# Count() and index()

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)}")

del mytuple # No longer exists


print(mytuple) # Will cause an error
Chapter 4 - Practice Set
1. Write a program to store seven fruits in a list entered by the user.
2. Write a program to accept marks of 6 students and display them in a sorted
manner.
3. Check that a tuple type cannot be changed in python.
4. Write a program to sum a list with 4 numbers.
5. Write a program to count the number of zeros in the following tuple:
a = (7, 0, 8, 0, 0, 9)
[Link] to ask the user to enter names of their 3 favorite movies & store them in a
list.
[Link] to check if a list contains a palindrome of elements. (Hint: use copy( )
method)
[1, 2, 3, 2, 1] [1, “abc”, “abc”, 1]
Palindrome: Its mean if we reverse a string or number there is no change in it.
e.g.
racecar
maam
[Link] to count the number of students with the “A” grade in the following tuple.
[”C”, “D”, “A”, “A”, “B”, “B”, “A”]
9. Store the above values in a list & sort them from “A” to “D”.
CHAPTER 06 – DICTIONARY
Dictionary In Python
Dictionary is a collection of keys-value pairs.
Just like dictionary which has words and its meaning, words are keys and
meanings are values. We can store tuple and list in the dictionary
Syntax:
a={
"key": "value",
"harry": "code",
"marks": "100",
"list": [1, 2, 9]
}
print(a["key"]) # Output: "value"
print(a["list"]) # Output: [1, 2, 9]
Properties of python dictionaries
 Stores data as key:value pairs.
 Ordered, mutable, no duplicate keys.
 Keys must be unique; values can repeat.
 Created via {key: value}, dict(), or dict(key=value) syntax.
 Indexed by keys, not position. It mean we can index or iterate over dictionary
with the help of keys
Indexing in list Indexing in dictionary
My_list[0] My_dict[“key”]

Q: How many way to create dictionary in python?


Created via
 {key: value},
 dict()
 dict(key=value) syntax.
{key: value} dict()
Program: #Creating a dictionary by
#Creating a dictionary by using the dict constructor
giving key:value paires
in {} my_dictionary=dict(
my_dictionary={ Name= "Tanveer",
"Name": "Tanveer", Age= 28
"Age": 28 )
} print(my_dictionary)
print(my_dictionary)
Program {key: value:
#1. Creating a dictionary by giving key:value paires in {}
first_dict={
"play":"Hamlet",
"author": "Shakespeare",
"year": 1600
}
# print(first_dict)
print(f"This is dictionary created by me: {first_dict= }\n") #Prints as a dictionary
with {} and comma separated key-value pairs
Program dict():
#2. Creating a dictionary by using the dict constructor
second_dict=dict(key1=1, key2="You", key3="Me")
print(f"{second_dict=}\n")

# Creating an empty dictionary by using {} or the dict constructor


third_dict={}
print(f"Empty dictionary created using empty braces: {third_dict= }\n")

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")

Changing Dictionary Items


- Items are changed by referencing their key.
- New items are added by providing a new key.
- The update method:
• accepts an iterable of key-value pairs.
• updates existing keys or adds new ones.
Program:
You do not change the keys in a dictionary. You change the values.
#Changing the values and items in dictionaries
my_dict={
"play":"Hamlet",
"author": "Shakespeare",
"year": 1600,
1: 1000
}
print(f"Original Dictionary:\n{my_dict= }\n")
#Chane a value by reffering to key
my_dict["year"]=1601
print(f"Dictionary with year changed by referring to key: \n{my_dict}\n")
#
# Adding an item by providing a new key
#
my_dict["publisher"] = "Nicholas Ling"
print(f"Dictionary with publisher added by giving a new key: \n{my_dict}\n")
# Adding items using the update method
#1. We can update with a dictionary
dict_upd={"act":3, "Scene": 1}
my_dict.update(dict_upd)
print(f"Dictionary after update with another dictionary: \n{my_dict}\n")
#
#2. We can update with a list of lists
list_upd=[["speaker","Hamlet"], ["words", 100]]
my_dict.update(list_upd)
print(f"After update with a list of lists: \n{my_dict}\n")
#
#3. We can Update with a tuple of tuples
tuple_upd=(("name","Tanveer"), ("RollNo","Bc220201330"))
my_dict.update(tuple_upd)
print(f"After update with a tuple of tuples: \n{my_dict}\n")

#4. We can update with list of tuples


mix_upd=[("Subject","math"),("Mark",197)]
my_dict.update(mix_upd)
print(f"After update with a list of tuple: \n{my_dict}\n")
#5. We can update with tuple of lists
mix_1_upd=(["Class",8],["Marks",197])
my_dict.update(mix_1_upd)
print(f"After update with a tuple of list: \n{my_dict}\n")
Note:
Use dictionaries as arguments. And remember this very simple cardinal rule.
If a key exists in a dictionary and you try to update it, the value does get updated.
You can change the value, if a key does not exist, it is created and the value
assigned to it. This works for the update state the method and also works with the
assignment method.
Removing Dictionary Items
- Items can be removed using
• Pop(key, default) method with key provided
• Popitem() removes last item added
• Del dictionary[key] removes item with specified key
- As with lists, sets and tuples:
• Clear – deletes all items in dictionary
• Del dictionary – removes dictionary from memory
Program:
my_dict={'play': 'Hamlet', 'author': 'Shakespeare', 'year': 1601, 1: 1000, 'publisher':
'Nicholas Ling', 'act': 3, 'Scene': 1, 'speaker': 'Hamlet', 'words': 100, 'name':
'Tanveer', 'RollNo': 'Bc220201330', 'Subject': 'math', 'Mark': 197, 'Class': 8, 'Marks':
197, 'audience': 'Alone'}
#1. <--- pop(key, default) ----->
# Items can be deleted by using the pop method and specifying the key
# Item mean: key+value
print(f"Original Dictionary: \n{my_dict}\n")
pop_value = my_dict.pop("audience", "Not found")
print(f"The value popped for the key \"audience\" is \n\t{pop_value} \nand the
remaining Dictionary is: \n{my_dict}\n")
#2. <--- popitem() ----->
# The last item can be deleted by using the popitem() method
pop_value=my_dict.popitem()
print(f"The item poped is \n\t{pop_value} \nand the remaining Dictionary is: \n\
{my_dict}\n")
#4. <---- del (“key”) ------->
# Items can be deleted by using the del function and specifying the dictionary
name and key
#
del my_dict["Scene"]
print(f"Item deleted using del fn on my_dict with the key \"scene\" leaving the
remaining Dictionary as: \n{my_dict}\n")
#4. <---- clear() ------->
# The entire dictionary can be cleared result is empty dictionary
my_dict.clear()
print(f"Dictionar Cleared: \n{my_dict}\n")
#5. <---- del () ------->
#Finally the entire dictionary is removed from memory
del my_dict
# print(my_dict) #Error
Note:
Clear Method Delete Method
Removes all key-value pairs from the Removes a specific key or deletes the
dictionary entire dictionary from memory
[Link]() del dict[key] or del dict
Looping through Dictionaries
- For loops can be used with membership
• With dictionary name only – loop variable is dictionary key
• With [Link]() – loop variable is dictionary keys
• With [Link]() – loop variable is dictionary values
• With [Link]() – loop variables are dictionary (key, value) tuples
Program:
#Looping through dictionaries
my_dict={'play': 'Hamlet', 'author': 'Shakespeare', 'year': 1601, 1: 1000, 'publisher':
'Nicholas Ling', 'act': 3, 'Scene': 1, 'speaker': 'Hamlet', 'words': 100, 'name':
'Tanveer', 'RollNo': 'Bc220201330', 'Subject': 'math', 'Mark': 197, 'Class': 8, 'Marks':
197, 'audience': 'Alone'}
print(f"Dictionary is: \n{my_dict}\n")

#1. Loopiny using just the dictionary name


print("\nLooping using just the dictionary name, the loop var is the key:")
for loop_var in my_dict:
print(loop_var) #Print the dictionary key
#2. looping using [Link]()
print("\nLooping using [Link](), the loop var is the key:")
for loop_var in my_dict.keys():
print(loop_var) #Print the key
#3. looping using [Link]()
print("\nLooping using [Link](), the loop var is the value:")
for loop_var in my_dict.values():
print(loop_var) #Print the value
#4. looping using [Link]()
print("\nLooping using [Link](), the loop vars are the (key: value)
tuples:")
for loop_var in my_dict.items():
print(loop_var) #Print the key and value return as tuples
Copying Dictionaries
• A shallow copy does not work:
o Dict2 = dict1 simply creates a reference
Two ways for create a deep copy:
o The copy() method
o The dict() constructor
Program:
#1. Create Copying-Dictionaries
first_dict={
"play":"Hamlet",
"author": "Shakespeare",
"year": 1600
}
#Trying to make copy using a simple assignment (reference)
second_dict=first_dict
print(f"Copy created using simple assignment\n{first_dict= }\n{second_dict= }\n")
#Changing a value in first_dict
first_dict["play"] = "Macbeth"
print(f"Value of 'play' changed in first_dict changes second_dict as well:\
n{first_dict = }\n{second_dict = }")

#2. Copy created using the copy() method


second_dict = first_dict.copy()
print(f"Copy created using the copy() method:\n{first_dict = }\n{second_dict = }\
n")

# Changing a value in first_dict


first_dict['play'] = "Hamlet"

print(f"Value of 'play' changed in first_dict does NOT change second_dict:\


n{first_dict = }\n{second_dict = }\n")

# Copy created using the dict() constructor


second_dict = dict(first_dict)
print(f"Copy created using the dict() constructor:\n{first_dict = }\n{second_dict
= }\n")

# Changing a value in first_dict


first_dict["play"] = "Othello"

print(f"Value of 'play' changed in first_dict does NOT change second_dict:\


n{first_dict = }\n{second_dict= }\n")
{ see latter
Nested Dictionaries
• Dictionaries can contain other dictionaries and so on
• Known as “nested” dictionaries
• Useful when organizing data of similar type e.g. employees
• Items are accessed using stacked key indexing - [ ] [ ]
Program:
# Create multiple dictionaries - students
student1 = {"name": "Ahmad", "age": 19, "grade": "A"}
student2 = {"name": "Bilal", "age": 22, "grade": "B+"}
student3 = {"name": "Durrani", "age": 20, "grade": "B"}

# 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")

# Hence, looping through the keys would be like:


for student in my_class:
print(student)
for key2 in my_class[student]:
print(f"\t{key2}: {my_class[student][key2]}") ## The second variable prints
the value of the nested d
# Dictionaries can be nested further. e.g three layers
neighborhood = {
"house1":{
"name":{"first":"Abdul","middle":"H","last":"Mateen"},
"address":{"houseno":"1-A","street":"Green
Street","mohalla":"Gulberg","city":"Lahore"}
},
"house2":{
"name":{"first":"Sheikh","middle":"Idrees","last":"Ahmad"},
"address":{"houseno":"2","street":"Blue Street","mohalla":"Gulberg
III","city":"Lahore"}
}
}

print(neighborhood["house1"]["address"]["mohalla"])

# Triple nested loop


for nbrhood in neighborhood:
print(nbrhood)
for key2 in neighborhood[nbrhood]:
print(f"\t{key2} :")

for key3 in neighborhood[nbrhood][key2]:


print(f"\t\t{key3} : {neighborhood[nbrhood][key2][key3]}")
Note: See it again.}
{Other Dictionary Methods
Fromkeys(list/tuple, value)
• Method of dict() class
• Creates a new dictionary with keys specified in list/tuple
• If a value is specified, the same value is given to all keys
Setdefault(key, value)
• Returns value of item with specified key (value is ignored)
• If key does not exist, it is created & the value assigned
• If the value is not provided, the key is created with None as the value
Program:
# car = {
# "brand": "Ford",
# "model": "Mustang",
# "year": 1964
#}
key_list = ["brand", "model", "year"]
my_dict = [Link](key_list)
print(f"Dictionary created from a key list without values:\n{my_dict}\n")

# 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")

# Let us set the value to something proper


my_dict["model"]="Mustang"
my_dict["year"]=1964
print(f"Dictionary with values updated:\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")

# and add another key and value


color = my_dict.setdefault("color", "white")
print(f"The updated dictionary is:\n{my_dict}\n")
Note: See it again.}
DICTIONARY METHODS
Consider the following dictionary:
a={"name":"Tanveer" "from":"Pakistan" "marks":[92,98,96]}
1. [Link]( ) #returns all keys
2. [Link]( ) #returns all values
3. [Link]( ) #returns all (key, val) pairs as tuples
4. [Link]( “key““ ) #returns the value according to key
5. [Link]( newDict ) #inserts the specified items to the dictionary
Form Apna College:
#print("Before")
print(Student["name2"]) #Error
#print("After")
#print([Link]("name2")) #None
Note: When Error come than before the error lines are executed and afetr error no
signle one line could be executed
Other Dictionary Concepts
Other Dictionary Concepts
• [Link]()
• [Link]()
• [Link]()
Dictionary views are dynamic, automatically updating to reflect changes in keys
or values.
Program:
#Create Dictionary
my_car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#1. Obtain the keys, values and items from this dictionary
car_keys = my_car.keys()
car_values = my_car.values()
car_items = my_car.items()

# Print the type and values of these lists


print(f"The type of car_keys is: {type(car_keys)}\nand the list is: \n{car_keys}\n")
print(f"The type of car_values is: {type(car_values)}\nand the list is: \
n{car_values}\n")
print(f"The type of car_items is: {type(car_items)}\nand the list is: \n{car_items}\
n")

#2. Now update the dictionary


#Update two keys

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

# Logical tests use the membership operator as well


# Check if both "owl" and "cat" exist in the set
if "owl" in set1 and "cat" in set1:
set1 = {1, 2, 3, 'owl', 'dog', 'cat'}
print("We have found a cat and an owl!")
Note:
Iterating through a set can only be done with the membership operator
# Define a set with mixed data types
set2 = {"the", 100, "quick", 200, "brown", 300}
# Print a message before iterating
print(f"\nIterating over a set, elements appear in random order:")
# Iterate through the set and print each element
for x in set2:
print(x)
Sets: Fine Points
Some fine points
- No duplicates allowed. If defined, will be ignored.
- True == 1 and False == 0. Treated identically
• Membership test can be done with either!
The usual Python functions apply:
• type() len() and the constructor set()
# Duplicate values are ignored
set1 = {1, 2, 3, 1, 2, 3, 4}
print(f"Duplicate values have been ignored: {set1 = }\n")

# 1 and True are identical, hence duplicates are removed


set2 = {1, "Fox", True, "Good morning"}
print(f"Only one out of 1 and True is kept: {set2 = }\n")

# (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")

# We did not see a 0 in set3. Does it exist?

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")

# Add a new value to the set. Duplicates will be ignored


[Link](100)
print(f"After adding a new value: 100, {set1 = }\n") #Unordered print
Sets: Update
# Augment a set with another full set using the update() method
set1 = {1, 2, 3}
set2 = {"the", "quick", "fox"}
tuple1 = (11, 22, 33)
list1 = [111, 222, 333]

# Update method changes original set


#1. Update set with another set
print(f"{set1 = }") # set1 = {1, 2, 3}
[Link](set2)
print(f"set1 updated with the set {set2} \nchanges set1 to: {set1}\n")
# Update can take multiple args of type iterable
[Link](list1, tuple1)
print(f"set1 updated with list {list1} \nand tuple {tuple1} \nchanges set1 to: {set1}\
n")
# The following update changes nothing since duplicates are ignored/removed
[Link](list1, tuple1)
print(f"Updated again with the same iterables changes nothing: \n{set1}\n")
Sets: Removing
• We can use remove elements by
 Remove(): take at least one argument
 Discard()
 Pop()
• Emptying a set:
• clear() method
• Deleting a set from memory:
• del function
Note:
remove() deletes the element but throws KeyError if not found
discard() deletes the element but does nothing if not found
A random element is removed and returned.
clear(): Emptying a set using clear() it mean it clear the element of set.
del: The del function removes the set from memory
#1. remove(): take at least one argument
set1 = {1, 2, 3, 100, 'Dog', 200, 'quick', 300, 'fox', 'Lazy', 'brown'}
print(f"set1 = \n{set1}\n")
# remove() deletes the element but throws KeyError if not found
[Link]("Dog")
print(f"After removing the value Dog: \n{set1 = }\n")
#2. Discard(): take at least one argument
# discard() deletes the element but does nothing if not found
[Link]("Dog") # No error if value not found. remove() would give KeyError
print(f"After discarding the value Dog again - no error: \n{set1 = }\n")
# [Link]("Dog") # Throw a KeyError
#3. Pop(): take no argument
a = [Link]() # A random element is removed and returned
print(f"The value removed is {a}, and the remaining set is \n{set1}\n")
#4. Clear()
# Emptying a set using clear()
[Link]()
print(f"set1 after the clear() method is called: {set1}\n")
#5. Del
# The del function removes the set from memory
#
del set1
print(set1) #Error
Sets: Union
- Returns a new set
- Can take 1 or more args
- Args can be a mix of iterables like tuple, list etc
- Shorthand is the | operator, but works ONLY with sets
Program:
# Define two sets
set1 = {1, 2, 3}
set2 = {"the", "quick", "fox"}
# Using union() to join two sets
set3 = [Link](set2)
# Display results with formatted printing
print(f"set1 = {set1},\nset2 = {set2},\nand their union: {set3 =}\n")

# Set3 union Set1 results in nothing new since all elements are duplicates

set4 = [Link](set1) # set1 = {1, 2, 3}

print(f"set3 union set1 gives nothing new: {set4 =}\n") # No change so set

#1. Union can be with multiple sets


set5 = {False, 100}
set6 = [Link](set2, set5)

print(f"The union of {set1} with {set2} and {set5} gives:\n{set6}\n")

#1 Union can be with other iterables

tuple1 = (11, 22, 33)


list1 = [111, 222, 333]
set7 = [Link](tuple1, list1)

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}")

print(f"And identically:\n\t{set2 =}\nintersection\n\t{set1 =}\ngives\n\t{set4 =}\


n")

# The intersection can be done with some other iterables!


list1 = ["The", "quick", "brown", 1, 11, 111]
set5 = [Link](list1)
print(f"A set\n\t{set1 =}\nintersection with a list\n\t{list1 =}\ngives\n\t{set5 =}\n")

# And remember that 1=True and 0=False in sets:

set1 = {"apple", 1, "banana", 0, "cherry"}


set2 = {False, "google", True, "apple", 2}
set7 = [Link](set2)
print(f"Intersection of sets with True/False values\n\t{set1 =}\nintersection with\n\
t{set2 =}\ngives\n\t{set7 =}\n")

# Finally, intersection_update() changes the calling set:

set2 = {False, True, 2, "apple", "google"}


set1.intersection_update(set2)
print("Intersection update 'set1.intersection_update(set2)' changes the calling
set1:")
print(f"\tset1 = {set1}")
Sets: Difference
Set methods - Difference
- difference()
- Method returns a new set with values that are in the calling set only
- The method can work with other iterables as well
- The method can take multiple arguments
- Shorthand is the - operator, but works only with sets

A-B has difference result as compare to B-A.


Set methods - Difference
- difference_update()
- Changes the calling set leaving values ONLY present in the calling set
- symmetric_difference()
- Returns a new set with all common values removed
- symmetric_difference_update()
- Changes* the calling set, removing all common values
What exactly the word update used in these method>
Update mean make change in the original set.
Program:
# The difference method returns a new set with elements that are on

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= }")

# The difference can be done with some other iterables!

list1 = ["The", "quick", "brown", 1, 11, 111]


set5 = [Link](list1)
print(f"A set\n\t{set1= }\ndifference with a list\n\t{list1= }\ngives\n\t{set5= }")

# The difference can be done with multiple iterables!

set6 = [Link](list1, set3)


list1 = ["The", "quick", "brown", 1, 11, 111]
print(f"A set\n\t{set1 = }\ndifference with a list\n\t{list1 = }\nand a set\n\t{set3
= }\ngives\n\t{set6 = }")

# difference_update() changes the calling set:


#
print(f"Difference_update() changes the calling set. Thus\n\t{set1= }\
nDifference_update\n\t{set2= }\ngives\n")
set2 = {1, 3, 5, 7}
set1.difference_update(set2)
print(f"\t{set1= })\n")

# symmetric_difference() returns a new set with no common elements:


#
set1 = {"apple", "banana", "cherry"}
set2 = {"samsung", "redmi", "apple"}

set3 = set1.symmetric_difference(set2)

print(f"symmetric_difference removes all common values. Thus:\n\t{set1= }\


nsymmetric_difference\n\t{set2= }\ngives")
print(f"{set3= }")

# symmetric_difference_update() changes the calling set removing all common


values:
#
set1 = {"apple", "banana", "cherry"}
set2 = {"samsung", "redmi", "apple"}

set1.symmetric_difference_update(set2)

print("symmetric_difference_update removes all common values and updates the


calling set:")
print(f"\tset1 = {set1}\n")

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= }")

# The set constructor can also be used to create a copy


#
set3a = set(set1)
[Link](300)

print(f"The set() constructor works and returns a new set:\n\t{set1= }\n\


t{set3a= }")
#
# The following methods return boolean values
#
# isdisjoint() returns True if sets do not have any elements in common

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {4, 5, 6}

print(f"isdisjoint() returns True if sets do not have any common values:\n\


t{set1= }\n\t{set2= }\n")
print(f"\t{set3= }\n\t{[Link](set3)= }\n")

#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}

print(f"issuperset() returns True if the calling set is a superset of the argument:\n\


t{set1= }\n\t{set2= }\n")
print(f"\t{[Link](set2)= }\n\t{[Link](set1)= }")

# A frozen set is created by its constructor


# and creates an immutable set

set1 = {"brand", "model", "year"}


fset1 = frozenset(set1)

print(f"Set1 is an ordinary set:\n\tset1 = {set1}")


print(f"while fset1 is an immutable frozen set:\n\tfset1 = {fset1}")
Sets: Example
# Some examples of set usage

Students = ["Abid", "Bashir", "Chaudhry", "Dogar", "Elahi", "Fazal", "Ghafoor"]


Mess_members = ["Bashir", "Chaudhry", "Dogar", "Hafeez"]
Gym_members = ["Abid", "Bashir", "Chaudhry", "Ijaz"]

# Find all students who are Mess_members and Gym_members


# (Begins by converting Student list to a set for calling set methods)
#
Mess_and_Gym_Students = set(Students).intersection(Mess_members,
Gym_members)
print(f'Students who are Mess and Gym members:\n{Mess_and_Gym_Students}\
n')

# Find students who are not Mess_members nor Gym_members


Not_Mess_Gym = set(Students).difference(Mess_members, Gym_members)
print(f"Students who are neither Mess nor Gym members:\n{Not_Mess_Gym}\n")

# Find students who are Mess_members but not Gym_members


#
Mess_not_Gym =
set(Students).intersection(Mess_members).difference(Gym_members)
print(f"Students who are Mess members but not Gym members:\
n{Mess_not_Gym}\n")
Note:
Cs306 Lecture 77 see again
Not included in apna college + Harry combined Notes }
Chapter 6 & 7 - Practice Set
1. Write a program to create a dictionary of Hindi words with values as their
English translation. Provide user with an option to look it up!
2. Write a program to input eight numbers from the user and display all the unique
numbers (once).
3. Can we have a set with 18 (int) and '18' (str) as a value in it?
4. What will be the length of following set s: s = set() [Link](20) [Link](20.0)
[Link]('20') # length of s after these operations?
5. s = {} What is the type of 's'?
6. Create an empty dictionary. Allow 4 friends to enter their favorite language as
value and use key as their names. Assume that the names are unique.
7. If the names of 2 friends are same; what will happen to the program in problem
6?
8. If languages of two friends are same; what will happen to the program in
problem 6?
9. Can you change the values inside a list which is contained in set S? s = {8, 7, 12,
"Harry", [1,2]}

1. Store following word meanings in a python dictionary :


table : “a piece of furniture”, “list of facts & figures”
cat : “a small animal”
[Link] are given a list of subjects for students. Assume one classroom is required
for 1
subject. How many classrooms are needed by all students.
”python”, “java”, “C++”, “python”, “javascript”,
“java”, “python”, “java”, “C++”, “C”
[Link] to enter marks of 3 subjects from the user and store them in a dictionary.
Start with
an empty dictionary & add one by one. Use subject name as key & marks as value.
[Link] out a way to store 9 & 9.0 as separate values in the set.
(You can take help of built-in data types)
CHAPTER 08 – Loop
Cs306 part
Loops In Python
Loops are used to repeat instructions.

Note:

Iteration: One cycle of loop

Iterator or variable: Counter

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

Perform some instructions

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.

While Loop Syntax

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!

If the loop is entered, the process of [condition check & execution]


is continued until the condition becomes False.

Let‘s Practice:

College Page 02

Break , Continue and Pass statements form Harry and College:

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:

Write a program to print 1 to 50 using a while loop.

Example:

i=0

while i < 5: # print "Harry" – 5 times!

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.

??

The Range Function


Range functions returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default), and stops before a specified number.

Syntax:

range (number)

range (start, stop)

range (start, stop, step)

where all arguments are integers

• Returns a “range” object that can be used to iterate

through

• Most useful in for-loops

The membership operator


• Syntax:

i in range (number)

(range could be any other group like list etc.)

• Returns True if i is in the range

• Returns False otherwise

• 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:

for x in <Some Sequence>:

Perform some instructions

optional: break

continue

else

For Loop Harry and College part

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:

for variable_name in name_list (tuple, string ect)

Let‘s Practice:

College P 5

Below All Example From cs306:

Program:
# for loop

for i in range(0,10, 2): #options: range (1, 10) ,range(1, 10, 2)


if(i>5):
break
print(i)
else:
print("The loop has been successfully exit")

Sum using For Loop

While loop run as well as condition is true.


For loop run as specific number if time.
# sum of first n natural number

print("The sum of first n natural number where n is entered by user: \n")


n=int(input("Please eneter a positive integer. "))
sum=0;
for i in range(1, n+1):
sum+=i
print("\nThe sum of first ",n, "natural number is: ", sum, "\n")
Check Divisibility using For Loop
#
a=int(input("Enter the starting number: "))
b=int(input("Enter the ending number: "))
c=int(input("Enter the number to divide by: "))
count=0;
for index in range(a, b+1):
if(index%c==0):
count+=1;
print("There are",count, "numbers between",a, "and", b, "which are exactly
divisible by",c)
Summing & Even Numbers Within Given Range Using for Loop
#Summing of even number

a=int(input("Enter the starting number: "))


b=int(input("Enter the endig number: "))
sum=0
for index in range(a, b+1):
if(index%2==0):
sum+=index
print("The sum of all even integers between",a, "and",b,"is",sum)
Computing Exponentiation using Loop
Note:
1. When sum is involve in the code/question we initialize with zero (0).
2. When multiplication is involve in the code/question we initialize with one
(1).
#Computing Exponentiation

print("Calculate base nunber raise to a specifid opwer using loop:\n")


x=float(input("Enter a base number:"))
n=int(input("Enter the power in which it should be raised (0 or higher):"))
noring=n
result=1
while(n>0):
result*=x
n-=1
print("\n",x,"raised to the power",noring, "is",result,"\n")
print("\nConfirmed using x**n built in function formal: \n",x, "raised to the
power", noring,"is",x**noring)
Computing Factorial of a Number Using Loop

#Computing factorial

n=int(input("Enter a positive integer: "))


fac=1
for index in range(1, n+1):
fac*=index
print("The factorail of ",n, "is",fac)
CHAPTER 8 – PRACTICE SET
1. Write a program to print multiplication table of a given number using for
loop.

2. Write a program to greet all the person names stored in a list ‘l’ and which
starts

with S.

l = ["Harry", "Soham", "Sachin", "Rahul"]

3. Attempt problem 1 using while loop.

4. Write a program to find whether a given number is prime or not.

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.

7. Write a program to print the following star pattern.

*
***

***** for n = 3

8. Write a program to print the following star pattern:

**

*** for n = 3

9. Write a program to print the following star pattern.

***

* * for n = 3

***

10. Write a program to print multiplication table of n using for loops in


reversed

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.
}

You might also like