0% found this document useful (0 votes)
5 views

Lecture Python Basics

The document contains various Python programming concepts including string manipulation, control flow statements (if-elif), loops, functions, and data structures like lists, dictionaries, and sets. It provides examples of operations such as concatenation, slicing, and methods for lists and dictionaries. Additionally, it discusses mutable and immutable sequences, along with practical exercises for user input and calculations.

Uploaded by

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

Lecture Python Basics

The document contains various Python programming concepts including string manipulation, control flow statements (if-elif), loops, functions, and data structures like lists, dictionaries, and sets. It provides examples of operations such as concatenation, slicing, and methods for lists and dictionaries. Additionally, it discusses mutable and immutable sequences, along with practical exercises for user input and calculations.

Uploaded by

ay34345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Lecture 2 str1= "I love Pakistan.

\nI lives in lahore"


str2= 'I am awais'
str3= """I love Pakistan"""
print(str1)
print(str2)
print(str1 + str2)
• \n endline
• \t tab space
• Concatenate str1 + str2 str1= "I love Pakistan.”
Print (len(str1))
• Len(str)
str1= "I love Pakistan."
• We can only access index ,,, no changes.print (len(str1))
ch = str1[0]
print (ch)
• Slicing:
• str str1= "Pakistan"
print (len(str1))
str2= str1[0:]
print (str2)
str2= str1[:5]
print (str2)
str1= "pakistan"
str1= "pakistan" Print(str1.capitalize())

print (len(str1))

str2= str1[-5:-1]

print (str2)

print(str1.endswith("aan"))
• str1= "pakistan is is my homeland"
• print (str1.capitalize())
• print (str1.replace("pakistan", "lahore"))
• print (str1.find("is"))
• print (str1.count("is"))
• a = input("enter your name")
• print(a)
• print(len(a))
• print(str1.find("pa"))
If elif age = 19 light = "orange" marks = 30
if(age > 18): if(light == "green"): if(marks >=90):
else print("hi") print("run") print("Grade A")
elif(light == "red"): elif(90>marks>=80):
print("stop") print("Grade B")

marks = int(input("enter marks elif(light == "yellow"): elif(80>marks>=70):


of the student")) print("ready") print("Grade C")
#marks= 12
else: else:
if(marks >=90):
print("not working") print("marks below
Grade = "A"
elif(marks >=80 and marks < 90): 70")
Grade = "B"
elif(marks >=70 and marks < 80):
Grade = "C"
else:
Grade = "F"
print("Grade of the student
is :", Grade)
nestin num1= int(input("enter 1st number"))
#print (num1)

g
age = 93
num= int(input("enter a
num2= int(input("enter 2nd number"))
#print (num2)

f(age > 18): number")) num3= int(input("enter 3rd number"))


#print (num3)
if(age >=80): print (num) if(num1>num2):
print("cant drive")
else: if ((num%2) == 0): highest = num1
elif(num2>num3):
print("can drive") print("number is highest = num2
else:
print("cant drive") even") elif(num3>num1):
highest = num3
else: elif(num1>num3):

print("number is highest = num1


print(highest)
num = int(input("enter a odd")
number"))
print(num) num1 = int(input("Enter 1st number: "))
if((num%7) == 0): num2 = int(input("Enter 2nd number: "))
print("entered number is a num3 = int(input("Enter 3rd number: "))
multiple of 7")
else: highest = max(num1, num2, num3) # Efficient way to find
print("entered number is not a maximum
multiple of 7") print("Highest number is:", highest)
name = ["Awais","Raza","Zaidi",56,556] name = ["Awais","Awais","Zaidi","Hurr", "Qasim",
name1 = [22,21,12,1,13,4,44] "Awais"]
print(name) print(name)
print(type(name)) name.sort()
print(len(name)) print(name)
print (name[0]) name.reverse()
print (name[1]) print(name)
print(name[4]) name.insert(1,"Nimra")
print(name[1:3]) print(name)
name.append("shah") name.remove("Nimra")
print(name) print(name)
print(name1) name.pop(5)
name1.sort() print(name)
print(name1)
name1.sort(reverse=True)
print(name1)
Mutable Sequences: • Immutable Sequences
Can be changed after creation (e.g., elements • Cannot be changed after creation. Any
can be modified, added, or removed). modification results in a new object.

Examples in Python: • Examples in Python:


• tuple → my_tuple = (1, 2, 3); my_tuple[0] =
list → my_list = [1, 2, 3]; my_list[0] = 10 10

bytearray → my_bytes = • str → my_str = "hello"; my_str[0] = "H"


bytearray(b"hello"); my_bytes[0] = 72
• bytes → my_bytes = b"hello"; my_bytes[0] =
72
Operations allowed:
In-place modifications
• Operations allowed:
like .append(), .remove(), .extend(), and
slicing assignments. • Only those that create new sequences, like
slicing, concatenation (+), and repetition (*).
Tuples in Python
• Built in data type that allows us to create immutable
sequences of values

• Tup = (1,1,2,1,3,1)
• Tup.index() returns index of first occurrence
• Tup.count() counts total occurrences
movie=[]
a = input("1st movie
name")

b = input("2nd movie
name")

c = input("3rd movie
name")
print(a)
print(b)
print(c)
movie.append(a)
movie.append(b)
movie.append(c)
Palindro
me
GRADE =
list1 = [1,2,3,2,1] ("A","B","C","A","B", "A")
print(GRADE.count("A"))
#print(list1)
copy_list1=list1.copy(
)
copy_list1.reverse()
if(copy_list1 == list1):
print("palindrome")
else:
print("not
grade = ["A", "B", "C", "A", "B",
palindrome")
"A"]
grade.sort()
print(grade)
Dictionary and Set
• Dictionary and Set are data structures
• Dictionaries are used to store data values in key:value
pairs , they are unordered , mutable (changeable) &
duplicate keys are not allowed.
info =
{
"key" : "value",
"name" : "Awais",
"roll number" : 9024,
"age" : 35,
"Qualification" : "PhD Scholar",
"CGPA" : 3.79,
"research area" : ["ML", "Bioinformatics", "DL", "AI"],
"institutes" : ("UET", "GCU","PIEAS")

}
print(info)
print(info["name"])
print(info["Qualification"])
info = {
"key" : "value",
"name" : "awais",
"roll number" : 9024,
"age" : 35,
"Qualification" : "PhD Scholar",
"CGPA" : { "BS":"2.94", "MS":"3.31", "PhD":"3.79"},
"research area" : ["ML", "Bioinformatics", "DL", "AI"],
"institutes" : ("UET", "GCU","PIEAS")

}
print(info["CGPA"]["PhD"])
• Dict.keys() print all keys
• Dict.values() print all values
• Dict.items() print all key value pairs as tuples
• Dict.get(“key”) print the key according to values
• Dict.update(new dict)
#print(info.keys())
#print(info.values())
#print(info.items())
#print(info.get("institutes"))
#pairs = list(info.items())
#print(pairs[1])
#info.update({"city" : "Lahore"})
#print(info)
• Collection of distinct objects
Sets in Python
• Immutable & unique items
• Num , int , float , str , tuple
• List and dict can not be added in set

set = {1,2,3,4,5 , 5 ,5 , 5, "awais", 29.9}


print(set)
print(len(set))
num = {} # this is not an empty set , this is a n
empty dictionary print(type(set))
Print(type(num))
Num = set() #this is an empty set declaration
Set methods

num = set()
• Set.add(element) set1 = {1,2,3}
num.add(2) set2 = {2,3,4}
• Set.remove(element) num.add(2000) print(set1.union(set2))
print(set1.intersection(se
• Set.clear() empties the num.add(20) t2))
set num.add(200)
num.remove(200
• set.pop() deleted a randon 0)
value #num.clear()
• Set.union(set2) num.pop()
num.pop()
• se,.intersection(set2) num.pop()
print(num)
dictionary = {"words" : "meaning",
"computer" : "ELECtronic machine",
"mobile" : "2 DIMENTIONAL RADIO",
"university" : "educational degree awarding
institute",
"mr. chips" : ["literature book", "12th english"]

print(dictionary)
Practice : enter 3 subject marks by
the user and print these in a
dictionry
physics = input("enter marks of first
subject")
print([physics])

chem = input("enter marks of second


subject") Enter 9 and 9.0 in a set
print([chem])
set = {9 , "9.0"}
computer = input("enter marks of thirc print(set)
subject")
print([computer])
set = {("float",9.0),
dictionary = {"subject" : "marks", ("int",9)}
"physics" : physics, print(set)
"chem" : chem,
"computer" : computer
}
n = int(input("enter a list =

Lecture 5 Loops number")) [1,4,9,16,25,36,49,6


num = 1 4,81,100]
#print(list[1])
while num <= 10: #print(len(list))
count = 1
print(n*num) index = 0
while count <=
num +=1 while index<
5:
len(list):
print("hi")
print(list[index])
count +=1
index +=1

num = 1

while num <= 10:


print(2*num)
num +=1 heroes = ["a", "aa", "b", "bb"]
index = 0
while(index<len(heroes)):
print(heroes[index])
index +=1
Insert a number Insert a number and Factorial
print sum from 1 to n
and print sum (WHILE) n=int(input("enter a
from 1 to n n=int(input("enter a number"))
n=int(input("enter a number"))
number")) fact = 1
sum = 0 i =1
sum = 0 i =0 while(i<=n):
for i in range(1,n+1): while(i<=n): fact *=i
sum +=i sum +=i i+=1
print(sum) print(sum) print(fact)
Functions
• Block of statements performing a specific task

def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)

def is_prime(n):
return n > 1 and all(n % i for i in range(2,
int(n**0.5) + 1))

def fibonacci(n):
a, b = 0, 1
for _ in range(n): a, b = b, a + b
return a
def reverse_string(s):
return s[::-1] from math import gcd
def find_gcd(a, b):
return gcd(a, b)

def find_max(lst):
return max(lst) def is_sorted(lst):
return lst == sorted(lst)

def is_palindrome(s):
return s == s[::-1]

def
remove_duplicates(lst):
return list(set(lst))

You might also like