Description:
All these coding examples , exercises and problems are taken from "PYTHON CRASH COURSE book" by Eric Matthes
Chapter 2 Variable and Simple Data Types And Chapter 3 List Introduction
# In[3]:
message="Hello Python"
print(message)
mean=message
# In[4]:
name="tayyar hussain"
print(name.title())
#title.() method will capitalize the first letter after space
# In[6]:
print(name.capitalize())
print(name.upper())
print(name.lower())
# In[9]:
#saving input into lower case so user won't cause error
a=input("Enter your name \n").lower()
if a=="tayyar":
print("Yes")
else:
print("No")
# In[16]:
#using variable in a string
a="Tayyar"
b="Hussain"
full_name=f"Hello! {a} {b}".upper()
print(full_name)
# In[20]:
#using same variable inside a string with .fomat
fullname="hello, {} {}".format(a,b)
print(fullname)
# In[21]:
print("Pyton\nC\nJava\n")
# In[27]:
#stripping whitespace
language=" python "
c=input("Enter your string")
if c==language.strip():
print("without space")
elif c==" python ":
print("yes")
#.rstrip()
#strip function is useful to compare string
#by remoing their extra space in them
# In[29]:
message_to="Elric"
print(f"Hello {message_to}, would you like to learn some Pyton today?")
# In[30]:
name="elric sama"
print(name.upper())
print(name.lower())
print(name.title())
# In[31]:
print('''Albert Einstein once said,"A person who never made a mistake never tried anything new"''')
# In[34]:
message='''Albert Einstein once said,"A person who never made a mistake never tried anything new"'''
print(message)
# In[35]:
name=" Elric "
print(name)
# In[38]:
name.rstrip()
# In[39]:
name.lstrip()
# In[40]:
name.strip()
# In[41]:
value=10_00
print(value)
#to look value more readable you can use _
#but en you print it will print number without underscore
# In[43]:
#assigning multiple value in python
x,y,z=0,1,2
print(x)
print(y)
print(z)
#you will use this technique more often than you think!
# In[44]:
'''in python you don't have constants but when
you want to treat a variable as constant you
write it in all the capital letters
'''
#eg
MAX_VALUE=1000
# In[47]:
#operations
print(5+3)
print(2*4)
print(16/2)
print(2%16)
# In[49]:
favourite_number=4
print('Your favourite number is',favourite_number)
# In[50]:
import this
# In[56]:
a="string"
print(a.index("s"))#locate the actually index position in the string
# In[60]:
#---------------- LIST-----------------#
bicyles=["trek","cannondale","redline","specialized"]
print(bicyles[0].title())
#you can even use .lower and .upper in that
#you can call any element of the list by indexing
#in simple words calling it's postion
# In[61]:
#retriving an index value into f string
print(f"My first bicyle was {bicyles[0].title()}")
# In[62]:
name=["Ahsan","Umair","Ali"]
print(name[0])
print(name[1])
print(name[2])
# In[63]:
print(f"Greetings {name[0]}, How are you?")
print(f"Greetings {name[1]}, How are you?")
print(f"Greetings {name[2]}, How are you?")
# In[2]:
favourite_bikes_brands=["honda","suzuki","yamaha"]
print(f"i would like to own {favourite_bikes_brands[0].title()} motorcycle ")
print(f"i would like to own {favourite_bikes_brands[1].title()} motorcycle ")
print(f"i would like to own {favourite_bikes_brands[2].title()} motorcycle ")
# In[3]:
print(favourite_bikes_brands)
favourite_bikes_brands[0]="ducati"
print(favourite_bikes_brands)
#modified or updated the list
# In[6]:
#appending an element in list
favourite_bikes_brands.append("hero")
print(favourite_bikes_brands)
# In[9]:
#inserting an element in list at your required index
favourite_bikes_brands
favourite_bikes_brands.insert(0,"Bmw")
print(favourite_bikes_brands)
# In[15]:
#removing an element from list
del favourite_bikes_brands[0]
# In[16]:
print(favourite_bikes_brands)
# In[18]:
del favourite_bikes_brands[0]
print(favourite_bikes_brands)
# In[23]:
motorcycle=["honda","yamaha","suzuki"]
print(motorcycle)
last_owned=motorcycle.pop()
print(last_owned)
print(motorcycle)
#eliminate last element from the index
'''Slight difference between in .pop() and
del on list elimination
del will permanantly remove the element and
pop will not remove the element but rather
it will check it out that it's already been used
'''
# In[25]:
#you can use pop method with giving the element index
#position
motorcycle
motorcycle.pop(1)
print(motorcycle)
# In[26]:
#sometimes you don't know the position of the
#element in the list, like we did used
#pop and del method but here in python you can
#also delete or remove an element from the list
a=["a","b","c","d","e"]
print(a)
a.remove("a")
print(a)
#here you can see you actually removed the element
#from the list without giving it's index position
# In[29]:
#inviting people for dinner
people=["Ruby","Fareen","Ahmar Raza","Abdul Aziz"]
print(f"My beloved Teacher {people[0]},Please come to this avenue")
print(f"My beloved Teacher {people[1]},Please come to this avenue")
print(f"My beloved Teacher {people[2]},Please come to this avenue")
print(f"My beloved Teacher {people[3]},Please come to this avenue")
# In[32]:
people=["Ruby","Fareen","Ahmar Raza","Abdul Aziz"]
print("Sending invitations to respected guests....")
print("Sorry! One your guest named Ruby wont be able to come")
print("Would you like to send invitation to any other person?")
people[0]="Ahsan"
print("Again sending invitations to guests according to changes")
print(f"My beloved Teacher {people[0]},Please come to this avenue")
print(f"My beloved Teacher {people[1]},Please come to this avenue")
print(f"My beloved Teacher {people[2]},Please come to this avenue")
print(f"My beloved Teacher {people[3]},Please come to this avenue")
print("Done sending the invitations")
# In[36]:
people=["Ruby","Fareen","Ahmar Raza","Abdul Aziz"]
print("Sending invitations to respected guests....")
print("Sorry! One your guest named Ruby wont be able to come")
print("Would you like to send invitation to any other person?")
people[0]="Ahsan"
print("Again sending invitations to guests according to changes")
print(f"My beloved Teacher {people[0]},Please come to this avenue")
print(f"My beloved Teacher {people[1]},Please come to this avenue")
print(f"My beloved Teacher {people[2]},Please come to this avenue")
print(f"My beloved Teacher {people[3]},Please come to this avenue")
print("Done sending the invitations")
print("Hey the is from Hotel! we have got a free table would you like to book it?")
people.insert(4,"Larry")
people.insert(5,"Marry")
print(f"hey, you are invited for dinner {people[4]}")
print(f"hey, you are invited for dinner {people[5]}")
# In[38]:
print(people)
print(f"Sorry to inform you we can't invite you for dinner {people.pop()}")
print(f"Sorry to inform you we can't invite you for dinner {people.pop()}")
print(f"Sorry to inform you we can't invite you for dinner {people.pop()}")
# In[40]:
print(people)
print(f"Sorry to inform you we can't invite you for dinner {people.pop()}")
print(people)
# In[43]:
#remember that pop metod returns the removed element and del method does not
#and pop() is empty it will automatically removes from te end of the string
print(people)
del people[0]
# In[45]:
print(people)
del people[0]
print(people)
# In[47]:
cars=["bmw","toyota","audi","frarri"]
cars.sort()
# In[48]:
print(cars)
#.sort method is permanent
# In[50]:
#reverse order alphabetical in list
cars.reverse()
print(cars)
# In[52]:
#sorting list temporarily
a=sorted(cars)
print(a)
# In[53]:
#length of the list
len(a)
#shows total number od elements in te list
# In[61]:
tes_list=["king","zing","elric","minhaj"]
print(tes_list)
print(sorted(tes_list))
print(tes_list)
print(reverse(tes_list))
# In[65]:
print(tes_list)
tes_list.sort()
print(tes_list)
# In[66]:
tes_list.reverse()
# In[67]:
print(tes_list)
# In[68]:
rivers=["ravi","chinab","jehlum","sindh"]
rivers.sort()
# In[70]:
print(rivers)
rivers.reverse()
print(rivers)
# In[72]:
print(sorted(rivers))
# In[74]:
#index error
rivers
rivers[4]
# In[ ]:
---------------------------------------------------------------------------------------------------------------------------
Chapter 4 Working with List , Tuples and For Loop:
# In[1]:
magicians=["David","Asan","Anjam"]
for magician in magicians:
print(magician)
# In[7]:
for magician in magicians:
print(f"{magician} that was a great trick")
print(f"{magician} i cant wait to see your other trick")
print("Thank you for you time, All the magicians")
# In[15]:
even_numbers=[2,4,6,8,10,12,14,16,18,20]
for numbers in even_numbers:
print(numbers)
# In[19]:
favourite_pizza=["Chicken Pizza","Malai Boti Pizza","Bar B Q","Chicken Tandoori"]
for pizza in favourite_pizza:
print(f"I like {pizza}")
print('''I just love pizza! \nI really like to eat it when i am hungry''')
# In[23]:
common_animals=["dog","cat","horse"]
for animals in common_animals:
print(f"{animals.title()} is a domestic animal")
print("These animals are common in USA\nbecause they are pet animals")
# In[25]:
for num in range(0,10):
print(num)
print("start from 0 to 10 in the range of 10")
# In[27]:
#converting range in list
for num in list(range(0,6)):
print(num)
print("Start from 0 to range of 6")
# In[32]:
for num in list(range(0,11,2)):
print(num)
# In[34]:
sequares=[]
for value in range(1,11):
sequares.append(value**2)
print(sequares)
# In[35]:
#some methods of the lists
li=[1,2,3,4,5,6,7,8,9,0]
print(min(li))
print(max(li))
print(sum(li))
# In[37]:
import math
from math import prod
print(prod(li))
print("Its zero because when we multiple anythin with zero we get 0!")
# In[38]:
li2=[1,2,3,4,5,6]
print(prod(li2))
# In[39]:
#List comprehensions
sequres=[value**2 for value in range(1,11)]
print(sequares)
# In[41]:
to_twenty=[a for a in range(1,21)]
print(to_twenty)
#another wayt to code this is on the other side
# In[44]:
to_twety2=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
for a in to_twety2:
print(a)
# In[7]:
one_million=[x for x in range(1,100001)]
print(one_million)
# In[8]:
print(min(one_million))
# In[9]:
print(max(one_million))
# In[12]:
odd_number=[x for x in range(1,21,2)]
print(odd_number)
# In[34]:
table=[3,6,9,12,15,18,21,24,27,30,33]
for i in table:
print(i)
# In[36]:
#by list comprehensions
cube=[x**3 for x in range(1,10)]
print(cube)
# In[38]:
#by simple loop method
cube1=[1,2,3,4,5,6,7,8,9]
for i in cube1:
print(i**3)
# In[39]:
#list slicing
players=['charles','martina','michael','florence','eli']
print(players[0:2])
# In[41]:
print(players[:2])
#start from 0 till in the range of 2
# In[42]:
print(players[2:])
#start from 2 till the end
# In[43]:
print(players)
# In[44]:
for p in players:
print(p)
# In[45]:
for p in players[:2]:
print(p)
# In[46]:
#copying a list
my_food=['pizza','falafel','carrot cake']
fried_food=my_food[:]
# In[48]:
print(fried_food)
# In[49]:
my_food.append('russian salad')
print(my_food)
print(fried_food)
# In[51]:
test_list=["pie","cake"]
test2=[]
# In[52]:
test2=test_list
# In[53]:
print(test2)
print(test_list)
# In[54]:
test2.append("harry")
# In[55]:
print(test2)
print(test_list)
'''putting a list = list 2 is not good option
since if you append other list it will append the
other also
istead just a list to another and i you want changes
you could do that easily and yet it wont affect the
other list !'''
# In[61]:
#list slicing questions
food=['shawarma','burger','tikka','paratha','biryani']
print("the first thee items from the list are ",food[0:3])
print("the middle three items from the list are ",food[1:4])
print("the last three items from the list are ",food[2:5])
# In[68]:
my_pizzas=["Tikka","Extra chessy","Beef pizza"]
friend_pizzas=["special beef pizza"]
for p1 in my_pizzas:
print("My pizza list",p1)
for p2 in friend_pizzas:
print("Friend pizza list",p2)
# In[69]:
friend_pizzas=my_pizzas[:]
print(my_pizzas)
print(friend_pizzas)
# In[70]:
for items in my_pizzas:
print(items)
# In[71]:
for items in friend_pizzas:
print(items)
# In[72]:
friend_pizzas.append("mushroom pizza")
# In[73]:
my_pizzas.append("mutton pizza")
# In[76]:
for items in friend_pizzas:
print(items)
# In[77]:
for items in my_pizzas:
print(items)
# In[80]:
num1=[1,2,3,4,5,6,7]
num2=[]
num2=num1[:]
print(num2)
num1.append(8)
num1.append(9)
# In[81]:
print(num1)
print(num2)
# In[84]:
my_t=(3,)
type(my_t)
#assigning a single value in tuple we would have to user , after the first items
# In[85]:
test_loop=(1,2,3,4,4,5,6,7,8)
for i in test_loop:
print(i)
# In[86]:
#although you cannot change items in tuples but
#you can reassign te whole tuple to change it's items
dimensions=(50,20)
print(dimensions)
# In[87]:
dimensions=(60,20)
print(dimensions)
# In[88]:
dimensions
#as you can see i re-assigned the value of the tuple
#by changing the whole tuple
# In[89]:
Buffet=("Nihari","Malai Boti","Biryani","Pulao")
for items in Buffet:
print(items)
# In[95]:
Buffet[0]="Tikka"
# In[96]:
Buffet=("Shami", "Biryani","Fis","Malai Boti")
# In[97]:
print(Buffet)
# In[ ]:
magicians=["David","Asan","Anjam"]
for magician in magicians:
print(magician)
# In[7]:
for magician in magicians:
print(f"{magician} that was a great trick")
print(f"{magician} i cant wait to see your other trick")
print("Thank you for you time, All the magicians")
# In[15]:
even_numbers=[2,4,6,8,10,12,14,16,18,20]
for numbers in even_numbers:
print(numbers)
# In[19]:
favourite_pizza=["Chicken Pizza","Malai Boti Pizza","Bar B Q","Chicken Tandoori"]
for pizza in favourite_pizza:
print(f"I like {pizza}")
print('''I just love pizza! \nI really like to eat it when i am hungry''')
# In[23]:
common_animals=["dog","cat","horse"]
for animals in common_animals:
print(f"{animals.title()} is a domestic animal")
print("These animals are common in USA\nbecause they are pet animals")
# In[25]:
for num in range(0,10):
print(num)
print("start from 0 to 10 in the range of 10")
# In[27]:
#converting range in list
for num in list(range(0,6)):
print(num)
print("Start from 0 to range of 6")
# In[32]:
for num in list(range(0,11,2)):
print(num)
# In[34]:
sequares=[]
for value in range(1,11):
sequares.append(value**2)
print(sequares)
# In[35]:
#some methods of the lists
li=[1,2,3,4,5,6,7,8,9,0]
print(min(li))
print(max(li))
print(sum(li))
# In[37]:
import math
from math import prod
print(prod(li))
print("Its zero because when we multiple anythin with zero we get 0!")
# In[38]:
li2=[1,2,3,4,5,6]
print(prod(li2))
# In[39]:
#List comprehensions
sequres=[value**2 for value in range(1,11)]
print(sequares)
# In[41]:
to_twenty=[a for a in range(1,21)]
print(to_twenty)
#another wayt to code this is on the other side
# In[44]:
to_twety2=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
for a in to_twety2:
print(a)
# In[7]:
one_million=[x for x in range(1,100001)]
print(one_million)
# In[8]:
print(min(one_million))
# In[9]:
print(max(one_million))
# In[12]:
odd_number=[x for x in range(1,21,2)]
print(odd_number)
# In[34]:
table=[3,6,9,12,15,18,21,24,27,30,33]
for i in table:
print(i)
# In[36]:
#by list comprehensions
cube=[x**3 for x in range(1,10)]
print(cube)
# In[38]:
#by simple loop method
cube1=[1,2,3,4,5,6,7,8,9]
for i in cube1:
print(i**3)
# In[39]:
#list slicing
players=['charles','martina','michael','florence','eli']
print(players[0:2])
# In[41]:
print(players[:2])
#start from 0 till in the range of 2
# In[42]:
print(players[2:])
#start from 2 till the end
# In[43]:
print(players)
# In[44]:
for p in players:
print(p)
# In[45]:
for p in players[:2]:
print(p)
# In[46]:
#copying a list
my_food=['pizza','falafel','carrot cake']
fried_food=my_food[:]
# In[48]:
print(fried_food)
# In[49]:
my_food.append('russian salad')
print(my_food)
print(fried_food)
# In[51]:
test_list=["pie","cake"]
test2=[]
# In[52]:
test2=test_list
# In[53]:
print(test2)
print(test_list)
# In[54]:
test2.append("harry")
# In[55]:
print(test2)
print(test_list)
'''putting a list = list 2 is not good option
since if you append other list it will append the
other also
istead just a list to another and i you want changes
you could do that easily and yet it wont affect the
other list !'''
# In[61]:
#list slicing questions
food=['shawarma','burger','tikka','paratha','biryani']
print("the first thee items from the list are ",food[0:3])
print("the middle three items from the list are ",food[1:4])
print("the last three items from the list are ",food[2:5])
# In[68]:
my_pizzas=["Tikka","Extra chessy","Beef pizza"]
friend_pizzas=["special beef pizza"]
for p1 in my_pizzas:
print("My pizza list",p1)
for p2 in friend_pizzas:
print("Friend pizza list",p2)
# In[69]:
friend_pizzas=my_pizzas[:]
print(my_pizzas)
print(friend_pizzas)
# In[70]:
for items in my_pizzas:
print(items)
# In[71]:
for items in friend_pizzas:
print(items)
# In[72]:
friend_pizzas.append("mushroom pizza")
# In[73]:
my_pizzas.append("mutton pizza")
# In[76]:
for items in friend_pizzas:
print(items)
# In[77]:
for items in my_pizzas:
print(items)
# In[80]:
num1=[1,2,3,4,5,6,7]
num2=[]
num2=num1[:]
print(num2)
num1.append(8)
num1.append(9)
# In[81]:
print(num1)
print(num2)
# In[84]:
my_t=(3,)
type(my_t)
#assigning a single value in tuple we would have to user , after the first items
# In[85]:
test_loop=(1,2,3,4,4,5,6,7,8)
for i in test_loop:
print(i)
# In[86]:
#although you cannot change items in tuples but
#you can reassign te whole tuple to change it's items
dimensions=(50,20)
print(dimensions)
# In[87]:
dimensions=(60,20)
print(dimensions)
# In[88]:
dimensions
#as you can see i re-assigned the value of the tuple
#by changing the whole tuple
# In[89]:
Buffet=("Nihari","Malai Boti","Biryani","Pulao")
for items in Buffet:
print(items)
# In[95]:
Buffet[0]="Tikka"
# In[96]:
Buffet=("Shami", "Biryani","Fis","Malai Boti")
# In[97]:
print(Buffet)
# In[ ]:
----------------------------------------------------------------------------------------------------------------------------
Chapter 5 if Statements with For Loops
cars=["bmw","audi","toyota","honda"]
if "bmw" in cars:
print("yes")
# In[13]:
#with loop
cars=["bmw","audi","toyota","honda"]
for car in cars:
if car=="audi":
print('Yes')
else:
print("no sorry we dont have that car")
# In[18]:
#with loop
cars=["bmw","audi","toyota","honda"]
for car in cars:
if car=="audi":
print('Yes')
else:
print("no sorry we dont have that car")
'''is trah se hume agar boht bari list ho to automate
kr k hum list main us element in ki index maloom kr sktey aur wo
element nikal sktey'''
# In[20]:
list1=[1,2,3,4,5,6,7,8]
print(list1.index(3))
# In[21]:
#checking equality
car="bmw"
car=="bmw"
'''python if statements work on boolean algebra
t==t=TRUE
f==t=False'''
# In[22]:
car=="python"
# In[ ]:
'''python is case sensitive when we compare to
strings '''
# In[24]:
list1=[1,2,3]
list2=[1,2]
list1==list2
#you can we compare list if they are equal or not
# In[25]:
tup=(1,2,3)
tup1=(1,2,3)
tup==tup1
#you can even compare tuples i they are equal or not
# In[28]:
#python is case sensitive proving that
King="Shah Lateef"
King=="Shah lateef"
#notice here i checked it it gave me false as output
# In[31]:
#using lower and upper to compare strings
ls=["lateef"]
ls[0].upper()=="LATEEF"
'''You can't use string methods on list unless
you call its index position tan use that method
if they are strings'''
# In[32]:
requested="mushrooms"
if requested != "onions":
print("HOLD ON!")
# In[33]:
age=18
18==age
# In[34]:
answer=17
if answer != 47:
print("Please try again this is not correct answer")
# In[40]:
age=19
age_1=22
age_1>=21 and age <=2
# In[2]:
requested=["mushrooms","onion"]
"mushrooms" in requested
# In[3]:
banned_users=["ali",'taimoor','ahsan']
user='marie'
if user not in banned_users:
print(f"{user.title()} you can post here")
# In[6]:
car='bmw'
if car == 'bmw':
print(True)
elif car == 'sabaru':
print(False)
# In[7]:
car_list=['giat','short','bmw']
car in car_list
# In[8]:
random='everything'
random in car_list
# In[9]:
random1='everything'
random==random1
# In[10]:
random.upper()==random1
# In[12]:
16 >15
# In[13]:
17<15
# In[14]:
16 < 15 or 17>15
# In[15]:
16 < 15 and 17 >15
# In[17]:
social_medias=['fb','twitter','youtube','telegram','tiktok']
'linkdin' in social_medias
# In[18]:
'fb' in social_medias
# In[23]:
age=19
if age >=18:
print("you are old enough to vote".upper())
print("have you registered the vote yet?".upper())
# In[24]:
age =17
if age >=18:
print("You can vote ".upper())
print("have you registered your vote?".upper())
else:
print("sorry you too young to vote ")
print("please register your vote as soon as your turn 18")
# In[28]:
age =19
if age <4:
print("your admission cost is 0$")
elif age <18:
print("your admission cost is 40$")
else:
print("your admission cost is 100$")
# In[30]:
requested_topping=["mushrooms","extra cheese"]
if 'mushrooms' in requested_topping:
print("yes mushrooms")
if 'extra cheese' in requested_topping:
print("yes cheesy")
if 'ketchup'in requested_topping:
print("red")
print("Finished checking the pizza")
# In[32]:
alien_color='red'
if alien_color == 'green':
print("Player as earned 5 points")
if alien_color =='red':
print("player has earned 10 points")
if alien_color == "white":
print("player has earned 20 points")
# In[33]:
alien_color2="red"
if alien_color2 =='green':
print("Player earned only 5 points")
else:
print("Player has earned 10 points")
# In[39]:
alien_color3='green'
if alien_color3 == 'green':
print("5 points")
elif alien_color3 == 'red':
print("10 points")
elif alien_color3 == 'grey':
print("20 points")
else :
print("nothing")
# In[51]:
fav_fruits=["apple","orange","strawberry"]
if "apple" in fav_fruits:
print("you really like apple")
if "orange" in fav_fruits:
print("you really like orange")
if "strawberry" in fav_fruits:
print("you really like strawberry")
if "juice" in fav_fruits:
print("you really that too")
if "vineger" in fav_fruits:
print("good choice")
# In[53]:
piz=[]
if 'lol' in piz:
print("lol")
else:
print("do you want pizza")
# In[54]:
available=["chai","paratha","egg"]
requests=["sugar",'daal','rice']
for requested in requests:
if requests in available:
print("add this menu")
else:
print("sorry we dont have that")
# In[5]:
users=["admin","sarah","ahsan","malaika","hussain"]
for greet in users:
if greet == 'admin':
print("Hello Admin would you like to see report?")
else:
print(f"Hello {greet} thanks for logging in")
# In[10]:
a=[]
if len(a) == 0:
print("We need to find some users")
elif len(a) > 0:
print("That's good we have the users")
# In[15]:
current_users=["Abdullah","Zeeshan","Faisal"]
new_users=["Zeeshan","Zaid","Faisal"]
for i in new_users:
if i in current_users:
print(f"'{i}' This username is already in use")
if i not in current_users:
print(f"'{i}' you an select this username")
# In[ ]:
if "bmw" in cars:
print("yes")
# In[13]:
#with loop
cars=["bmw","audi","toyota","honda"]
for car in cars:
if car=="audi":
print('Yes')
else:
print("no sorry we dont have that car")
# In[18]:
#with loop
cars=["bmw","audi","toyota","honda"]
for car in cars:
if car=="audi":
print('Yes')
else:
print("no sorry we dont have that car")
'''is trah se hume agar boht bari list ho to automate
kr k hum list main us element in ki index maloom kr sktey aur wo
element nikal sktey'''
# In[20]:
list1=[1,2,3,4,5,6,7,8]
print(list1.index(3))
# In[21]:
#checking equality
car="bmw"
car=="bmw"
'''python if statements work on boolean algebra
t==t=TRUE
f==t=False'''
# In[22]:
car=="python"
# In[ ]:
'''python is case sensitive when we compare to
strings '''
# In[24]:
list1=[1,2,3]
list2=[1,2]
list1==list2
#you can we compare list if they are equal or not
# In[25]:
tup=(1,2,3)
tup1=(1,2,3)
tup==tup1
#you can even compare tuples i they are equal or not
# In[28]:
#python is case sensitive proving that
King="Shah Lateef"
King=="Shah lateef"
#notice here i checked it it gave me false as output
# In[31]:
#using lower and upper to compare strings
ls=["lateef"]
ls[0].upper()=="LATEEF"
'''You can't use string methods on list unless
you call its index position tan use that method
if they are strings'''
# In[32]:
requested="mushrooms"
if requested != "onions":
print("HOLD ON!")
# In[33]:
age=18
18==age
# In[34]:
answer=17
if answer != 47:
print("Please try again this is not correct answer")
# In[40]:
age=19
age_1=22
age_1>=21 and age <=2
# In[2]:
requested=["mushrooms","onion"]
"mushrooms" in requested
# In[3]:
banned_users=["ali",'taimoor','ahsan']
user='marie'
if user not in banned_users:
print(f"{user.title()} you can post here")
# In[6]:
car='bmw'
if car == 'bmw':
print(True)
elif car == 'sabaru':
print(False)
# In[7]:
car_list=['giat','short','bmw']
car in car_list
# In[8]:
random='everything'
random in car_list
# In[9]:
random1='everything'
random==random1
# In[10]:
random.upper()==random1
# In[12]:
16 >15
# In[13]:
17<15
# In[14]:
16 < 15 or 17>15
# In[15]:
16 < 15 and 17 >15
# In[17]:
social_medias=['fb','twitter','youtube','telegram','tiktok']
'linkdin' in social_medias
# In[18]:
'fb' in social_medias
# In[23]:
age=19
if age >=18:
print("you are old enough to vote".upper())
print("have you registered the vote yet?".upper())
# In[24]:
age =17
if age >=18:
print("You can vote ".upper())
print("have you registered your vote?".upper())
else:
print("sorry you too young to vote ")
print("please register your vote as soon as your turn 18")
# In[28]:
age =19
if age <4:
print("your admission cost is 0$")
elif age <18:
print("your admission cost is 40$")
else:
print("your admission cost is 100$")
# In[30]:
requested_topping=["mushrooms","extra cheese"]
if 'mushrooms' in requested_topping:
print("yes mushrooms")
if 'extra cheese' in requested_topping:
print("yes cheesy")
if 'ketchup'in requested_topping:
print("red")
print("Finished checking the pizza")
# In[32]:
alien_color='red'
if alien_color == 'green':
print("Player as earned 5 points")
if alien_color =='red':
print("player has earned 10 points")
if alien_color == "white":
print("player has earned 20 points")
# In[33]:
alien_color2="red"
if alien_color2 =='green':
print("Player earned only 5 points")
else:
print("Player has earned 10 points")
# In[39]:
alien_color3='green'
if alien_color3 == 'green':
print("5 points")
elif alien_color3 == 'red':
print("10 points")
elif alien_color3 == 'grey':
print("20 points")
else :
print("nothing")
# In[51]:
fav_fruits=["apple","orange","strawberry"]
if "apple" in fav_fruits:
print("you really like apple")
if "orange" in fav_fruits:
print("you really like orange")
if "strawberry" in fav_fruits:
print("you really like strawberry")
if "juice" in fav_fruits:
print("you really that too")
if "vineger" in fav_fruits:
print("good choice")
# In[53]:
piz=[]
if 'lol' in piz:
print("lol")
else:
print("do you want pizza")
# In[54]:
available=["chai","paratha","egg"]
requests=["sugar",'daal','rice']
for requested in requests:
if requests in available:
print("add this menu")
else:
print("sorry we dont have that")
# In[5]:
users=["admin","sarah","ahsan","malaika","hussain"]
for greet in users:
if greet == 'admin':
print("Hello Admin would you like to see report?")
else:
print(f"Hello {greet} thanks for logging in")
# In[10]:
a=[]
if len(a) == 0:
print("We need to find some users")
elif len(a) > 0:
print("That's good we have the users")
# In[15]:
current_users=["Abdullah","Zeeshan","Faisal"]
new_users=["Zeeshan","Zaid","Faisal"]
for i in new_users:
if i in current_users:
print(f"'{i}' This username is already in use")
if i not in current_users:
print(f"'{i}' you an select this username")
# In[ ]:
---------------------------------------------------------------------------------------------------------------------------
Chapter 6 Dictionary
a={"hus":123,"na":456}
a["bitch"]=65
# In[3]:
print(a)
# In[7]:
for i in a:
print(i)
# In[8]:
print(a)
# In[10]:
a['hus']=66
print(a)
#modiied the dictionary
# In[12]:
alien_0={'x position':0,'y position':25,'speed':'medium'}
print(f"Original position: {alien_0['x position']}")
# In[21]:
#condition statements on dictioanry
print(alien_0)
if alien_0['speed'] == 'slow':
x_increment = 1
print("only 1 point is increased")
elif alien_0['speed'] == 'medium':
x_increment = 2
print("only 2 points are increased")
else:
x_increment=5
print("only 5 points are increased")
alien_0['x position'] =alien_0['x position']+x_increment
print(alien_0)
# In[23]:
b={"value":3,"size":40}
if b["value"]==40:
val_increment=5
elif b["value"]==41:
val_increment=5
else:
val_increment=10
b['value']=b['value']+val_increment
print(b['value'])
# In[24]:
print(b)
# In[27]:
c={"adoon":3,"hadoon":8}
print(c.keys())
del c["adoon"]
print(c)
#removing the key and its associated value from the dictionary
# In[29]:
favourite_language={
'jen':'python',
'sarah':'c',
'mushtaq':'java',
'zeeshan':'r'
}
print(favourite_language)
#this way the dictioanry is more humar readable
# In[32]:
favourite_language.get('yo',"No points also")
#this way if there is no key in the dictionary
#it wont show error rather it will print the next
#line which is after the comma
# In[34]:
favourite_language.get("he")
#python will only show none if there is no key
#in the dictionary associated in it
# In[37]:
user1={'first name':'Ahsan','last name':'Munir','age':'22','city':'lahore'}
print(user1['first name'])
print(user1['last name'])
print(user1['age'])
print(user1['city'])
# In[3]:
user1={
'username':'efermi',
'first':'enrico',
'last':'fermi'
}
for key , value in user1:
print(f"{key}")
print(f"{value}")
# In[8]:
dicq={
"ahsan":32,
"munir":34,
'tayyar':98,
"withstand":90
}
for key in dicq:
print(f"please check you name in {list(dicq.keys())}")
for value in dicq:
print(f"please check you average{list(dicq.values())}")
# In[9]:
for name in dicq.keys():
print(name.title())
# In[15]:
for name in dicq.values():
print(name)
# In[ ]:
# In[8]:
favrt_languages={
"sarah":'c',
"james":"pyton",
"william":"java"
}
lis1=["sarah","macho","james","william"]
for name in favrt_languages.keys():
if name in lis1:
print(f"{name} your favourite language is {favrt_languages.get(name)}")
# In[9]:
if "nisha" not in favrt_languages.keys():
print("Please take a poll on it")
# In[10]:
print(favrt_languages)
# In[6]:
nat={
"ahsan":123,
"munir":332,
"mustaq":444
}
for na in nat:
print(nat.values())
# In[11]:
print(favrt_languages)
# In[14]:
for languages in favrt_languages.values():
print(languages.title())
# In[21]:
#for collecting common elements from dictionary datasets
data_set={
"tayyar":"python",
"hussain":"c++",
"munir":"java",
"ahmar":"kotlin",
"mukesh":"python",
"ambani":"c++"
}
for languages in data_set.values():
print(languages) #set(languages)
#jupyter notebook is not working good rigt now
#but it will help yout to gether common elements from a data sets
# In[36]:
data_set={
"tayyar":"python",
"hussain":"c++",
"munir":"java",
"ahmar":"kotlin",
"mukesh":"python",
"ambani":"c++"
}
data_set["rajesh"]="javascript"
data_set["raghini"]="sql"
for name in data_set.keys():
print(name)
# In[37]:
del data_set["mukesh"]
# In[38]:
print(data_set)
# In[55]:
#rivers
rivers={
"ravi":"lahore",
"ganga":"kanpur",
"jehlum river":"jehlum"
}
for name in rivers.keys():
print(f"The {name.title()} runs throught {rivers[name]} ")
#{rivers.get(name).upper()}
#this method can also word but the commented will workd mush better than
#the block of code with i am using
# In[27]:
favrt_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
poll_rist=['sarah','ahsan','tayyar','jen']
for x in favrt_languages.keys():
if x in poll_rist:
print(f"Thanks for taking part in this poll {x.title()}")
elif x not in poll_rist:
print(f"{x.title()}, Please join the poll!")
# In[19]:
#nested dictionaries
users={
"ahsan":{
"first":'ahsan',
"second":'munir',
"location":"pakistan"
},
"zain":{
'first':'zain',
'second':'malik',
'location':'lahore'
}
}
for username,user_info in users.items():
print(f"username:{username}")
full_name=f"{user_info['first']}{user_info['second']}"
location =user_info["location"]
print(f"{full_name}")
print(f"{location.title()}")
# In[18]:
print(users.items())
# In[36]:
#last exercise of dictionaries
ahsan={
"name":"Ahsan Munir",
"height":"5.7ft",
"weight":"60kg",
"location":"lahore"
}
zain={
"name":"Zain Malik",
"height":"5.5ft",
"weight":"52kg",
"location":"lahore"
}
saadat={
"name":"Saadat Malik",
"height":"5.7ft",
"weight":"50kg",
"location":"lahore"
}
people=[ahsan,zain,saadat]
for x in people:
print(f"you information is here please check{x.values()}")
# In[51]:
dog={
"owner":"sarah",
"pet name":"milly",
"age of pet":"3 years"
}
cat={
"owner":"billy",
"pet name":"mano",
"age of pet":"5 year"
}
chicken={
"owner":"hussain",
"pet name":"momo",
"age of pet":"2 year"
}
pet=[dog,cat,chicken]
print("List order is owner name,pet name and pet age ")
for pet_info in pet:
if "owner" in pet_info:
print("name of the owner is",pet_info.get("owner").upper())
if "pet name" in pet_info:
print("owner's pet name is" ,pet_info.get("pet name").upper())
if "age of pet" in pet_info:
print("pet age is " ,pet_info.get("age of pet"))
# In[71]:
peting={
"sarah":{
"pet owner name": "sarah",
"pet name":"lucy",
"pet species":"dog",
"pet age":"2 year"
},
"ahsan":{
"pet owner name ":"ahsan",
"pet name":"mike",
"pet species":"cat",
"pet age":" 3 year"
}
}
col=[peting]
for x in col:
if "sarah" in peting:
print(x.get("sarah"))
if "ahsan" in peting:
print(x.get("ahsan"))
# In[86]:
favorite_places={
"ahsan":{"Muree","Lahore"},
"saleem":"Kashmir",
"mohsin":"Gilgit"
}
for x in favorite_places.keys():
print(f"{x} favourite place or places are ",favorite_places.get(x))
# In[87]:
favourite_num={
"ahsan":{"favourite number ":2},
"laiba":{"favourite number":4},
}
for x in favourite_num.keys():
print(f"{x} favourite numbers are ",favourite_num.get(x))
# In[97]:
cities={
"lahore":{
"country located":"Pakistan",
"population":"1 crores",
"fact":"it is located near Wahgha border"
},
"karachi":{
"country located":"Pakistan",
"population":"2.2 crores",
"fact":"Biggest city of the country"
},
"Islamabad":{
"country located":"Pakistan",
"population":"34 lakhs",
"fact":"It is the capital of the city"
}
}
for x in cities.keys():
print(f"{x.upper()}, some little about them:",cities.get(x))
# In[ ]:
print(100,0)
# In[3]:
n=19
print(n)
# In[5]:
response = input("What is your radius? ")
r = float(response)
area = 3.14159*r**24
print("The area is ", area)
# In[8]:
import turtle
window=turtle.Screen()
alex=turtle.Turtle()
alex.forward(50)
alex.left(90)
alex.forward(30)
window.mainloop()
# In[9]:
for _ in range(5):
print(_)
#you can assign any name or just it a _ symbol
# In[13]:
dip={1:"Greek",2:"Turkish",3:{'Name':'Ahsan','Country':'Pakistan','City':'Lahore'}}
# In[25]:
#by roll number calling:
class_info={200:{'Name':'Ahsan','Class':'12th','City':'Lahore','Gender':'Male'},
201:{'Name':'Ishfaq','Class':'12th','City':'Lahore','Gender':'Male'},
202:{'Name':'Malik','Class':'12th','City':'Lahore','Gender':'Male'},
203:{'Name':'Sabir','Class':'12th','City':'Lahore','Gender':'Male'},
205:{'Name':'Tehmina','Class':'12th','City':'Lahore','Gender':'Female'},
206:{'Name':'Sidra','Class':'12th','City':'Lahore','Gender':'Female'}}
#this is the example of nested dictionary
# In[27]:
#simple dictionary
dislike={1:"Ahsan",2:"Male",3:"Hero"}
print(dislike[1])
# In[31]:
dislike[4]="Merry"
#adding a new element in the distionary!
#defines it's key than put assign value to it!
# In[35]:
print(dislike)
# In[37]:
print(class_info.keys())
# In[40]:
class_info[207]={'Name':'Saima','Class':'12th','City':'Lahore','Gender':'Female'}
# In[42]:
print(class_info)
# In[46]:
new_dict={"Tup":"Big","Hans":"Rajpot"}
new_dict["Hans"]#accessing dictionary by it's key name
# In[47]:
class_info.get(200)
#.get() method to call any key value
# In[49]:
print(class_info.get("Ahsan"))
#.get() method only work on keys if there is no key found then python will say NONE!
# In[53]:
print(class_info)
# In[61]:
#accessing nested distionary by key and value
class_info[200]["Name"]
# In[62]:
#deleting speciic key rom a dictionary
del class_info[207]
# In[63]:
print(class_info)
# In[64]:
#delete a speciic element from a key value
del class_info[206]["Gender"]
# In[65]:
print(class_info)
# In[67]:
del class_info[206]["Name"]#["Class"]
#you can only delete 1 element from a key at a single time!
# In[68]:
class_info[206]
# In[70]:
new_dict=class_info.copy()
#.copy method will copy your whole dictionary into another variable
# In[71]:
print(new_dict)
# In[78]:
str(new_dict)
# In[76]:
'''Dictionary Problems'''
# Write a Python script to add a key to a dictionary
current_dictionary={1:40,3:80,4:100}
print(current_dictionary)
current_dictionary[2]={60}
print(current_dictionary)
# In[89]:
#Write a Python script to concatenate following dictionaries to create a new one
dict1={1:10,2:20}
dict2={2:30,4:40}
dict3={5:50,6:60}
Added_dict={dict1}
# In[93]:
#Write a Python program to sum all the items in a dictionary
print(Added_dict1)
print(sum(Added_dict1.keys())) #2+4=6
# In[98]:
#Write a program to get min and maximum value of keys in a dictionary
print(max(Added_dict1.keys()))
print(min(Added_dict1.keys()))
---------------------------------------------------------------------------------------------------------------------------
Chapter 7 User input and While Loop and Chapter 8 Functions
#!/usr/bin/env python
# coding: utf-8
# In[3]:
user_input=input("Enter your car name to check")
print(f"Let me check a {user_input.title()} if it's avialable")
# In[5]:
people=int(input("Please tell me how many people are in your group?"))
if people >= 8:
print("Sorry you have to wait for a day for your table!")
else:
print("Your table is ready please come at 8 o clock pm")
# In[7]:
current =1
while current <= 5:
print(current)
current = current+1
# In[9]:
prompt="enter your message \n type 'quit' to leave this program "
message=""
while message != "quit":
message = input(prompt)
print(message)
# In[16]:
#active flag problems
active = True
while active:
user = input("Enter something here to check ")
if user == 'quit':
active = False
print("Do something")
if user == 'ping':
active = False
print("Do something other than that")
# In[17]:
#break statement example
active = True
while active:
user = input("Enter something here to check ")
if user == 'quit':
break
print("Do something")
if user == 'ping':
active = False
print("Do something other than that")
#if i type quit it will end the while loop it won't even output the
#print statement at the end
# In[28]:
promo="Enter here something"
while True:
message = input(promo)
if message == "yolo":
print("YOLO")
else:
print(message)
break
# In[ ]:
#questions!!!!
# In[29]:
topping="what you want on your pizza? "
while True:
message=input(topping)
if message == "quit":
break
else:
print(f"{message} is added on your pizza")
# In[34]:
act="Enter your age"
while True:
ask=int(input(act))
if ask <=3:
print("Your are free")
if ask in range(4,13):
print("10$ for a ticket")
if ask >=13:
print("15$ for a ticket")
# In[35]:
act="Enter your age"
while True:
ask=int(input(act))
if ask <=3:
print("Your are free")
break
if ask in range(4,13):
print("10$ for a ticket")
if ask >=13:
print("15$ for a ticket")
# In[36]:
'''active variable main while loop sab kuch true hoga pr agar sirf simple while loop lga
ho to ap kisi certain condition pr while loop ko false kr sktey
'''
#using while loops on dictionary and list
# In[44]:
confirmed_users=["line","piek","reiner"]
unconfirmed=[]
while confirmed_users:
users=confirmed_users.pop()
unconfirmed.append(users)
print(users)
# In[48]:
#removing some commong elements from a list wit while loop
pet=["cat","dog","duck","horse","cat"]
print(f"before while loop {pet}")
while 'cat' in pet:
pet.remove('cat')
print(f"after the while loop {pet}")
#these is also a easily method to remove common elements from a list
# In[51]:
pet=["cat","dog","duck","horse","cat"]
# In[52]:
set(pet)
#no matter how many times a object is repeating it will only unique once in the list
# In[56]:
reponse={}
active = True
while active:
key = input("Enter the key")
value = input("Enter the value")
reponse[key]=value
print(reponse)
if key == 'quit':
break
if value == 'quit':
break
# In[57]:
mydictionary={}
mydictionary["key"]="Value"
print(mydictionary)
# In[63]:
sandwich_orders=[]
pick = True
while pick:
sandwich_name=input("what you want to order? ")
sandwich_orders.append(sandwich_name)
if sandwich_name == 'quit':
pick = False
if 'quit' in sandwich_orders:
sandwich_orders.remove("quit")
for x in sandwich_orders:
print(f"you have ordered {x}")
# In[73]:
destination={}
while True:
name=input("Enter your name here: ")
place=input("where you want to go? ")
destination[name.title()]=place.title()
if name == 'quit':
break
if place == 'quit':
break
print(f" {name.title()} wants to go {destination.get(name.title())}")
# In[ ]:
# functions
# In[1]:
def greet(username):
print(f"Hello {username}!")
# In[2]:
greet("Tayyar")
# In[3]:
def display_topic():
print("Today we are going to learn about functions: ")
# In[7]:
display_topic()
# In[13]:
#book title
def favourite_book(name):
print(f"My favourite book is '{name.title()}'")
# In[14]:
favourite_book("Alice the wonderland")
# In[8]:
#passing the argument
#Positional argument
def get_there(animal_type,pet_name):
print(f"I have a {animal_type}")
print(f"My {animal_type}'s name is {pet_name}")
# In[9]:
get_there("Chicken","Momo")
# In[10]:
get_there("Dog","Buckey")
#position of the argument matter in this condition
#if you are defining with multiple argument
#there is a method to prevent this type error
# In[11]:
#error type
get_there("Buckey","Dog")
#lol
#i have a Buckey
#My Buckey's name is Dog loool
#there is method for fucntions to prevent it
# In[12]:
#keyword arguments
get_there(animal_type="Dog",pet_name="Lara")
#even though the positions of these peramete are not
#when i created the fucntion but i am using
#the actually defined perameters in the function
#and i am assigning them them to the argument
#by doing positions of the argument does not matter
# In[13]:
#default values of a function
def describe_pet(name,animal_type="Cat"):
print(f"I have a {animal_type}")
print(f"My pet name is {name}")
# In[14]:
describe_pet("Chia")
#here i just passed the argument for only the name
#in my defined function i have used default paramete
#for pet type so i did not need pass the argument
#for it's type!
# In[15]:
#but you can still the function to change the default parameters
#in case if someones have a different pet type!
describe_pet("Momo","Chicken")
#now python is not using the default parameter
#for the argument
# In[17]:
#postional arguments and default argument can also
#be used
describe_pet(animal_type="Lizard",name="Larry")
# In[20]:
#avoiding error while using functions
def my_self(name,age):
print(f'My name is {name}')
print(f'My age is {age}')
# In[21]:
my_self("Ahsan",23)
#no error but if we don't give required arguments
#then we will face issues
# In[22]:
my_self("Ahsan")
# 1 missing position argument is missing!!!!
#to prevent this we can use few following methods
#1) Use required ammount of positional arguments
#2) use a default argument for a parameter
#3)
# In[23]:
def make_shirt(size,text):
print(f"This is a {size} size shirt")
print(f"'{text}' is printed on it ")
# In[24]:
make_shirt("Medium","I love Programming")
# In[25]:
make_shirt(text="I love computer science",size="Large")
# In[26]:
def make_shirt(size="Large",text="I love Python"):
print(f"This is a {size} size shirt")
print(f"'{text}' is printed on it ")
# In[27]:
make_shirt()
#just using default arguments which i have provided
# In[28]:
make_shirt(size='Medium')
#just changed the size only
# In[29]:
make_shirt(text="I love Computer Science")
# In[38]:
def make_shirt(size,txt="I love Python"):
if size == 'large':
print(f"This is a {size} size shirt")
print(f"'{txt}' is written on it ")
if size == "medium":
txt =="I love programming"
print(f"This is a {size} size shirt")
print(f"'{txt}' is written on it")
# In[39]:
make_shirt(size='large')
# In[40]:
make_shirt("medium")
# In[43]:
def describe_city(name,country_name="Pakistan"):
print(f"{name.title()} is in {country_name}")
# In[44]:
describe_city("Lahore")
# In[45]:
describe_city(name="Karachi",country_name="Pakistan")
# In[46]:
describe_city(name="Delhi",country_name="India")
# In[2]:
#returning a simple value
def full_name(first_name,last_name):
name=f"{first_name.title()} {last_name.title()}"
return name
# In[4]:
musician=full_name("tayyar","hussain")
print(musician)
#function can also be use to assign to a variable
# In[5]:
#function as a variable
def get_math(a,b):
return a+b
return a-b
return a*b
return a/b
return a%b
#when created a function only the first occuring
#return statement will work not after that
'''
def get_math(a,b):
return a+b
only this piece of code will work'''
# In[7]:
operations=get_math(2,3)
print(operations)
# In[8]:
get_math(2,3)
# In[9]:
def squred(a):
return a*a
# In[10]:
squred(2)
# In[12]:
#assigning it to a variable to use it
sq=squred(10)
print(sq)
# In[16]:
def get_formatted(first_name,last_name,middle_name=''):
if middle_name:
full_name=f"{first_name} {middle_name} {last_name}"
return full_name
else:
full_name =f"{first_name} {last_name}"
# In[17]:
get_formatted("tayyar","hussain")
# In[19]:
def get_formatted(first_name,last_name,middle_name=None):
if middle_name != None:
full_name = f"{first_name} {middle_name} {last_name}"
print(full_name)
else:
full_name =f"{first_name} {last_name}"
print(full_name)
# In[21]:
get_formatted("muhammad","tayyar","hussain") #by using positional arguments
# In[24]:
#by using keyword arguments
get_formatted(first_name="Ch",last_name='Ahsan')
# In[25]:
get_formatted(first_name='Ch',middle_name="ahsan",last_name="munir")
# In[31]:
#returning a dictionary with function
def build_person(first_name,last_name):
person={'first name':first_name.title(),'last name':last_name.title()}
return person
# In[32]:
build_person("tayyar","hussain")
# In[33]:
build_person("ch",'ahsan')
# In[44]:
#another way to write this code
def build_person2(first_name,last_name):
indentity={}
indentity["first name"]=first_name.title()
indentity["last name"]=last_name.title()
return indentity
#using function to pass information in a data structure which is more meaningful is actually
#useful to access the data
#we cant show the actually actually dictioanry code
#which is parsin the information due to security and for other reasons
#we created a function which can automatically pass
#this useful information into the dictionary
# In[45]:
build_person2("ch","ahsan")
# In[47]:
#passing more information through function into
#the dictionary
def get_info(first_name,last_name,age=None):
info={}
info["first name"]=first_name.title()
info["last name"]=last_name.title()
if age:
info["age"]=age
return info
# In[49]:
get_info("ahsan","munir")
#did not provided the information but still worked
# In[50]:
get_info(first_name="tehseen",last_name="mukhtar",age=15)
# In[51]:
def get_formatted(first_name,last_name,middle_name=None):
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
print(full_name)
else:
full_name =f"{first_name} {last_name}"
print(full_name)
# In[52]:
get_formatted(first_name="ch",middle_name='ahsan',last_name="munir")
# In[53]:
get_formatted('ahsan','munir')
# In[55]:
dicti={
"first name":input()
}
print(dicti)
# In[74]:
def user_type():
while True:
print("Enter your infortion/ntype'quit' to end this program")
user={'first name':input("Enter your first name"),'last name':input("Enter your last name")}
print(user)
continue
# In[75]:
user_type()
# In[107]:
def user_type():
while True: #using flag here
print("Enter your information\ntype 'quit' to end this program")
user={'first name':input("Enter your first name: ").title(),
'last name':input("Enter your last name: ").title()}
if user["first name"] and user["last name"] == "Quit":
break
else:
print(user)
continue
# In[108]:
user_type()
# In[115]:
def city_country(city,country):
print(f"'{city},{country}'")
# In[114]:
city_country("lahore","pakistan")
# In[122]:
def album_info(name,artist):
album={"name":name,"artist":artist}
return album
# In[123]:
falak=album_info("Falak","Judah")
blackpink=album_info("Black Pink","Solo")
bts=album_info("Bts","Dynamite")
# In[124]:
print(falak)
# In[125]:
print(blackpink)
# In[126]:
print(bts)
# In[135]:
def creating_album():
info={}
while True:
info["artist name"]=input("Enter the name of the artist: ").title()
info["album name"]=input("Enter the name of the album: ").title()
if
break
else:
print(info)
# In[136]:
creating_album()
# In[4]:
#Passing a list in a function
def greet_user(names):
for name in names:
print(f"Good Morning {name.title()}!")
# In[5]:
username=["harry","larry","marry"]
# In[6]:
greet_user(username)
# In[8]:
#modyfying a list in function
unprinted_designs=["phone case","robot"," laptop"]
completed=[]
while unprinted_designs:
newdesign=unprinted_designs.pop()
completed.append(newdesign)
print(completed)
# In[13]:
def print_models(unprinted_design,completed_model):
while unprinted_design:
new=unprinted_design.pop()
completed_model.append(new)
print(completed_model)
# In[14]:
u=["which","is","this"]
b=[]
print_models(u,b)
# In[16]:
#copying a list without changing it's content
lis=["Pen",1,66,"wow"]
lis2=lis[:]
# In[17]:
print(lis2)
# In[19]:
print(lis)
# In[21]:
lis.append("I chaned something so i can prove ")
print(lis)
# In[22]:
lis2.remove(66)
lis2.append("I did not changed anythin")
print(lis2)
# In[28]:
#but if i sued like this
lis=[1,2,3,4,"something"]
lis1=lis
#if i modify or change something to lis1
#python will modify to lis too!
#so do prevent that sometimes we use [:] method!
# In[29]:
print(lis)
print(lis1)
#both are same let's try something
# In[30]:
lis.remove(4)
print(lis)
print(lis1)
#see both are affected by the change!
# In[34]:
test_list_for_function=["lets see if it can be changed in the function"]
print(test_list_for_function)
# In[39]:
def removing_and_checking(a):
for x in a:
# In[40]:
removing_and_checking(test_list_for_function)
# In[41]:
final=["cars","laptops","computers","phones"]
report=[]
# In[42]:
def check(a,b):
while a:
c=a.pop()
b.append(c)
print(b)
# In[43]:
check(final,report)
# In[45]:
print(final)
print(report)
#see the list i created have been affected
#because i used that in function and it poped out the
#objects in the list
#but there is a method or way to prevent this!
# In[46]:
final=["cars","laptops","computers","phones"]
report=[]
# In[47]:
check(final[:],report)
# In[50]:
print(final)
#can you believe that?
#it did not affect the orginal list when i
#used that in a function!!!!!
# In[51]:
print(report)
# In[56]:
shot_messages=["hey","how are you?","what are you doing","that's amazing!","i love friends","it's a great show i believe"]
print(shot_messages)
new=[]
# In[57]:
def check_messages(a,b):
while a:
c=a.pop()
b.append(c)
print(b)
#printing messages with while inside a fucntion
# In[58]:
check_messages(shot_messages[:],new)
# In[59]:
print(new)
# In[60]:
def check_again(a):
for x in a:
print(x)
# In[61]:
check_again(new)
#printing messages with for loop
# In[65]:
shot_messages=["hey","how are you?","what are you doing","that's amazing!","i love friends","it's a great show i believe"]
print(shot_messages)
new=[]
# In[66]:
def check_m_with_change(a,b):
while a:
c=a.pop()
b.append(c)
print(a)
print(b)
# In[67]:
check_m_with_change(shot_messages,new)
# In[69]:
print(shot_messages)
#after using function it's been changed
print(new)
# In[70]:
shot_messages=["hey","how are you?","what are you doing","that's amazing!","i love friends","it's a great show i believe"]
print(shot_messages)
new=[]
# In[73]:
#created a fucntion which can take list without changing it
def do_not_change(a,b): #if [:] here we will get error
while a:
c=a.pop()
b.append(c)
print(a)
print(b)
# In[74]:
do_not_change(shot_messages[:],new)
# In[6]:
#passing an Arbitrary number of arguments
def make_pizza(*toppings):
print(toppings)
# In[7]:
make_pizza("chicken","extra cheese","mushrooms")
# In[14]:
#using a for loop
def make_pizza(*toppings):
for topping in toppings:
print(f"Topping of pizza contain '{topping}'")
# In[15]:
make_pizza("chicken cheese","mushrooms","onion")
# In[22]:
#mixing positional argument and arbitrary argument
def make_pizza(size,*toppings): #*topping is the example of args!
print(f"The size of the pizza is {size}")
print("Your pizza is made from: ")
for topping in toppings:
print(f"{topping.title()}")
# In[23]:
make_pizza(18,"Mushroom","Chicken","Extra cheese")
# In[24]:
make_pizza(12,"Beef","extra cheese","olives")
# In[29]:
def build_profile(first,last,**user_info):#** will automatically create te dictionary
#**user_info is te example of *kwargs!
user_info["first"]=first
user_info["last"]=last
print(user_info)
# In[30]:
build_profile("tayyar","hussain")
# In[32]:
def building(name,location,**kwargs):
print(kwargs)
# In[33]:
building("sunny tower","lahore")
# In[36]:
#use of **args and *kwargs
def add(*args):
print(args)
print(sum(args))
# In[37]:
add(1,2)
# In[39]:
def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print(arg)
# In[40]:
#*args are list o arguments #they act like list
#**kargs are key word argument #tey act like dictionary
#args= unlimited number o arguments!
# In[41]:
#eg o args again
blog_1="I am cool"
blog_2="I am a Pyton Programmer"
blog_3="Computer Science is Amazing"
blog_4="I love Information Security"
# In[42]:
def blog_posts(*args):
for k in args:
print(k)
# In[44]:
blog_posts(blog_1) #only 1 argument
blog_posts(blog_2,blog_3) #more than 1 argument
# In[45]:
blog_posts(blog_1,blog_2,blog_3,blog_4)
#many arguments passed with getting into a problem
#but if had just defined certain numbers of argument
# In[46]:
def user_name(name,ID,**user_info):
user_info["name"]=name
user_info["ID"]=ID
print(user_info)
# In[47]:
user_name("fs142","247")
# In[49]:
#order sandwich
def sandwiches(*ingredients):
for k in ingredients:
print(f"You sandwich conatins: {k.title()}")
# In[61]:
sandwiches("Chicken","Mayo","Onions","Cabagge")
# In[62]:
sandwiches("Beef","Ketchup","Onion")
# In[63]:
sandwiches("Olives","mayo","mushrooms")
# In[5]:
def user_information(name,location,gender,**info):
info["name"]=name.title()
info["location"]=location.title()
info["gender"]=gender.title()
print(info)
# In[6]:
user_information("ahsan","lahore","male")
# In[8]:
user_information("tehseen","lahore","male")
# In[9]:
user_information("mehak","lahore","female")
# In[20]:
def cars_info(model,company_name,*about_car,**full_info):
full_info["model"]=model
full_info["company name"]=company_name
print(full_info)
print("OTHER INFORMATION ABOUT YOUR VEHICAL")
for x in about_car:
print(f"-->{x}")
# In[21]:
cars_info("YBR","Yamaha","Blue","125cc")
# In[22]:
cars_info("CD125","Honda Pakistan","125cc","Red color","2 Wheels","2 Side Mirrors")
# In[ ]:
def make_pizza(size,*toppings):
print("You have ordered {size} inches pizza")
print("Which contains: ")
for x in toppings:
print(x.title())
# In[6]:
make_pizza(17,"extra cheese","chicken tikka")
# In[ ]:
#steps to modularize code
'''
1) write code and functions
2) download them as .py format
3)upload this downloaded .py file in the jupyter notebook directory where you are
currently working because it will be easier to track and check the file name etc
4) import the code into the new cell where your are working
5)method:
import x.py(it's the name of the file)
from x import'''
import pizza
from pizza import make_pizza
# In[9]:
make_pizza(16,"mushrooms","extra cheese")
# In[10]:
#steps to modularize code
'''
1) write code and functions
2) download them as .py format
3)upload this downloaded .py file in the jupyter notebook directory where you are
currently working because it will be easier to track and check the file name etc
4) import the code into the new cell where your are working
5)method:
import x.py(it's the name of the file)
from x import x(function)--> any function you want to use!'''
# In[14]:
import math #imported a math module
from math import sqrt #from the math module i called a special function of sqrt
a=4
sqrt(a)
# In[19]:
#made a .py file which will take name and id and convert it into a dictionary
import example
from example import your_info
your_info("ahsan","223") #here as you can see i made my own code then imported into new cell to reuse the code
# In[23]:
import example
your_info("ahsan",33)
# In[1]:
import test
from test import user
# In[2]:
user(1,2)
# In[3]:
user(5,9)
# In[5]:
user(1,2)
# In[7]:
user(1,2)
# In[9]:
import pizza
# In[12]:
pizza.make_pizza(23,"Mushrooms","Chicken","Extra cheese") #emporting the entire module
# In[14]:
#importing specifice functions from a module
import math
from math import sqrt #importing just sqrt function from whole math module
sqrt(100)
# In[15]:
import pizza
from pizza import make_pizza
# In[17]:
make_pizza(22,"chicken tikka","olives","mushrooms","extra mozzarella chesse")
# In[18]:
'''uf te name of a function your are importing
might conflict with an existing name in your program
or if the function name is long your can use a short
unique alia an alternae name similar to nickname for the function
which you are trying to import
'''
import math
from math import sqrt as square
# In[22]:
square(100)
#see here i changed the name of sqrt as square!
# In[23]:
sqrt(100) #even with changing you can still use the perivious name
# In[26]:
#lol you can even import the module and change the name of it
import pizza as order
from pizza import make_pizza
# In[29]:
import math as m
m.sqrt(100) # changed the module name here
# In[32]:
#changing the module name and also the function name at the same time
import math as m
from math import sqrt as s
# In[34]:
s(100)
# In[35]:
m.sqrt(100)
# In[36]:
#importing all the functions in a module
from math import *
# In[38]:
#styling your function
def riches(p1,p2,p3,p4,
p5,p6,p7,p8,p9,p10):
return sum(int(p1,p2,p4,p5,
p6,p7,p8,p9,p10))
#if the functions have too many arguments
#then you should use styling method to code
#your function so it can be readable easily to others
#
---------------------------------------------------------------------------------------------------------------------
# coding: utf-8
# In[3]:
user_input=input("Enter your car name to check")
print(f"Let me check a {user_input.title()} if it's avialable")
# In[5]:
people=int(input("Please tell me how many people are in your group?"))
if people >= 8:
print("Sorry you have to wait for a day for your table!")
else:
print("Your table is ready please come at 8 o clock pm")
# In[7]:
current =1
while current <= 5:
print(current)
current = current+1
# In[9]:
prompt="enter your message \n type 'quit' to leave this program "
message=""
while message != "quit":
message = input(prompt)
print(message)
# In[16]:
#active flag problems
active = True
while active:
user = input("Enter something here to check ")
if user == 'quit':
active = False
print("Do something")
if user == 'ping':
active = False
print("Do something other than that")
# In[17]:
#break statement example
active = True
while active:
user = input("Enter something here to check ")
if user == 'quit':
break
print("Do something")
if user == 'ping':
active = False
print("Do something other than that")
#if i type quit it will end the while loop it won't even output the
#print statement at the end
# In[28]:
promo="Enter here something"
while True:
message = input(promo)
if message == "yolo":
print("YOLO")
else:
print(message)
break
# In[ ]:
#questions!!!!
# In[29]:
topping="what you want on your pizza? "
while True:
message=input(topping)
if message == "quit":
break
else:
print(f"{message} is added on your pizza")
# In[34]:
act="Enter your age"
while True:
ask=int(input(act))
if ask <=3:
print("Your are free")
if ask in range(4,13):
print("10$ for a ticket")
if ask >=13:
print("15$ for a ticket")
# In[35]:
act="Enter your age"
while True:
ask=int(input(act))
if ask <=3:
print("Your are free")
break
if ask in range(4,13):
print("10$ for a ticket")
if ask >=13:
print("15$ for a ticket")
# In[36]:
'''active variable main while loop sab kuch true hoga pr agar sirf simple while loop lga
ho to ap kisi certain condition pr while loop ko false kr sktey
'''
#using while loops on dictionary and list
# In[44]:
confirmed_users=["line","piek","reiner"]
unconfirmed=[]
while confirmed_users:
users=confirmed_users.pop()
unconfirmed.append(users)
print(users)
# In[48]:
#removing some commong elements from a list wit while loop
pet=["cat","dog","duck","horse","cat"]
print(f"before while loop {pet}")
while 'cat' in pet:
pet.remove('cat')
print(f"after the while loop {pet}")
#these is also a easily method to remove common elements from a list
# In[51]:
pet=["cat","dog","duck","horse","cat"]
# In[52]:
set(pet)
#no matter how many times a object is repeating it will only unique once in the list
# In[56]:
reponse={}
active = True
while active:
key = input("Enter the key")
value = input("Enter the value")
reponse[key]=value
print(reponse)
if key == 'quit':
break
if value == 'quit':
break
# In[57]:
mydictionary={}
mydictionary["key"]="Value"
print(mydictionary)
# In[63]:
sandwich_orders=[]
pick = True
while pick:
sandwich_name=input("what you want to order? ")
sandwich_orders.append(sandwich_name)
if sandwich_name == 'quit':
pick = False
if 'quit' in sandwich_orders:
sandwich_orders.remove("quit")
for x in sandwich_orders:
print(f"you have ordered {x}")
# In[73]:
destination={}
while True:
name=input("Enter your name here: ")
place=input("where you want to go? ")
destination[name.title()]=place.title()
if name == 'quit':
break
if place == 'quit':
break
print(f" {name.title()} wants to go {destination.get(name.title())}")
# In[ ]:
# functions
# In[1]:
def greet(username):
print(f"Hello {username}!")
# In[2]:
greet("Tayyar")
# In[3]:
def display_topic():
print("Today we are going to learn about functions: ")
# In[7]:
display_topic()
# In[13]:
#book title
def favourite_book(name):
print(f"My favourite book is '{name.title()}'")
# In[14]:
favourite_book("Alice the wonderland")
# In[8]:
#passing the argument
#Positional argument
def get_there(animal_type,pet_name):
print(f"I have a {animal_type}")
print(f"My {animal_type}'s name is {pet_name}")
# In[9]:
get_there("Chicken","Momo")
# In[10]:
get_there("Dog","Buckey")
#position of the argument matter in this condition
#if you are defining with multiple argument
#there is a method to prevent this type error
# In[11]:
#error type
get_there("Buckey","Dog")
#lol
#i have a Buckey
#My Buckey's name is Dog loool
#there is method for fucntions to prevent it
# In[12]:
#keyword arguments
get_there(animal_type="Dog",pet_name="Lara")
#even though the positions of these peramete are not
#when i created the fucntion but i am using
#the actually defined perameters in the function
#and i am assigning them them to the argument
#by doing positions of the argument does not matter
# In[13]:
#default values of a function
def describe_pet(name,animal_type="Cat"):
print(f"I have a {animal_type}")
print(f"My pet name is {name}")
# In[14]:
describe_pet("Chia")
#here i just passed the argument for only the name
#in my defined function i have used default paramete
#for pet type so i did not need pass the argument
#for it's type!
# In[15]:
#but you can still the function to change the default parameters
#in case if someones have a different pet type!
describe_pet("Momo","Chicken")
#now python is not using the default parameter
#for the argument
# In[17]:
#postional arguments and default argument can also
#be used
describe_pet(animal_type="Lizard",name="Larry")
# In[20]:
#avoiding error while using functions
def my_self(name,age):
print(f'My name is {name}')
print(f'My age is {age}')
# In[21]:
my_self("Ahsan",23)
#no error but if we don't give required arguments
#then we will face issues
# In[22]:
my_self("Ahsan")
# 1 missing position argument is missing!!!!
#to prevent this we can use few following methods
#1) Use required ammount of positional arguments
#2) use a default argument for a parameter
#3)
# In[23]:
def make_shirt(size,text):
print(f"This is a {size} size shirt")
print(f"'{text}' is printed on it ")
# In[24]:
make_shirt("Medium","I love Programming")
# In[25]:
make_shirt(text="I love computer science",size="Large")
# In[26]:
def make_shirt(size="Large",text="I love Python"):
print(f"This is a {size} size shirt")
print(f"'{text}' is printed on it ")
# In[27]:
make_shirt()
#just using default arguments which i have provided
# In[28]:
make_shirt(size='Medium')
#just changed the size only
# In[29]:
make_shirt(text="I love Computer Science")
# In[38]:
def make_shirt(size,txt="I love Python"):
if size == 'large':
print(f"This is a {size} size shirt")
print(f"'{txt}' is written on it ")
if size == "medium":
txt =="I love programming"
print(f"This is a {size} size shirt")
print(f"'{txt}' is written on it")
# In[39]:
make_shirt(size='large')
# In[40]:
make_shirt("medium")
# In[43]:
def describe_city(name,country_name="Pakistan"):
print(f"{name.title()} is in {country_name}")
# In[44]:
describe_city("Lahore")
# In[45]:
describe_city(name="Karachi",country_name="Pakistan")
# In[46]:
describe_city(name="Delhi",country_name="India")
# In[2]:
#returning a simple value
def full_name(first_name,last_name):
name=f"{first_name.title()} {last_name.title()}"
return name
# In[4]:
musician=full_name("tayyar","hussain")
print(musician)
#function can also be use to assign to a variable
# In[5]:
#function as a variable
def get_math(a,b):
return a+b
return a-b
return a*b
return a/b
return a%b
#when created a function only the first occuring
#return statement will work not after that
'''
def get_math(a,b):
return a+b
only this piece of code will work'''
# In[7]:
operations=get_math(2,3)
print(operations)
# In[8]:
get_math(2,3)
# In[9]:
def squred(a):
return a*a
# In[10]:
squred(2)
# In[12]:
#assigning it to a variable to use it
sq=squred(10)
print(sq)
# In[16]:
def get_formatted(first_name,last_name,middle_name=''):
if middle_name:
full_name=f"{first_name} {middle_name} {last_name}"
return full_name
else:
full_name =f"{first_name} {last_name}"
# In[17]:
get_formatted("tayyar","hussain")
# In[19]:
def get_formatted(first_name,last_name,middle_name=None):
if middle_name != None:
full_name = f"{first_name} {middle_name} {last_name}"
print(full_name)
else:
full_name =f"{first_name} {last_name}"
print(full_name)
# In[21]:
get_formatted("muhammad","tayyar","hussain") #by using positional arguments
# In[24]:
#by using keyword arguments
get_formatted(first_name="Ch",last_name='Ahsan')
# In[25]:
get_formatted(first_name='Ch',middle_name="ahsan",last_name="munir")
# In[31]:
#returning a dictionary with function
def build_person(first_name,last_name):
person={'first name':first_name.title(),'last name':last_name.title()}
return person
# In[32]:
build_person("tayyar","hussain")
# In[33]:
build_person("ch",'ahsan')
# In[44]:
#another way to write this code
def build_person2(first_name,last_name):
indentity={}
indentity["first name"]=first_name.title()
indentity["last name"]=last_name.title()
return indentity
#using function to pass information in a data structure which is more meaningful is actually
#useful to access the data
#we cant show the actually actually dictioanry code
#which is parsin the information due to security and for other reasons
#we created a function which can automatically pass
#this useful information into the dictionary
# In[45]:
build_person2("ch","ahsan")
# In[47]:
#passing more information through function into
#the dictionary
def get_info(first_name,last_name,age=None):
info={}
info["first name"]=first_name.title()
info["last name"]=last_name.title()
if age:
info["age"]=age
return info
# In[49]:
get_info("ahsan","munir")
#did not provided the information but still worked
# In[50]:
get_info(first_name="tehseen",last_name="mukhtar",age=15)
# In[51]:
def get_formatted(first_name,last_name,middle_name=None):
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
print(full_name)
else:
full_name =f"{first_name} {last_name}"
print(full_name)
# In[52]:
get_formatted(first_name="ch",middle_name='ahsan',last_name="munir")
# In[53]:
get_formatted('ahsan','munir')
# In[55]:
dicti={
"first name":input()
}
print(dicti)
# In[74]:
def user_type():
while True:
print("Enter your infortion/ntype'quit' to end this program")
user={'first name':input("Enter your first name"),'last name':input("Enter your last name")}
print(user)
continue
# In[75]:
user_type()
# In[107]:
def user_type():
while True: #using flag here
print("Enter your information\ntype 'quit' to end this program")
user={'first name':input("Enter your first name: ").title(),
'last name':input("Enter your last name: ").title()}
if user["first name"] and user["last name"] == "Quit":
break
else:
print(user)
continue
# In[108]:
user_type()
# In[115]:
def city_country(city,country):
print(f"'{city},{country}'")
# In[114]:
city_country("lahore","pakistan")
# In[122]:
def album_info(name,artist):
album={"name":name,"artist":artist}
return album
# In[123]:
falak=album_info("Falak","Judah")
blackpink=album_info("Black Pink","Solo")
bts=album_info("Bts","Dynamite")
# In[124]:
print(falak)
# In[125]:
print(blackpink)
# In[126]:
print(bts)
# In[135]:
def creating_album():
info={}
while True:
info["artist name"]=input("Enter the name of the artist: ").title()
info["album name"]=input("Enter the name of the album: ").title()
if
break
else:
print(info)
# In[136]:
creating_album()
# In[4]:
#Passing a list in a function
def greet_user(names):
for name in names:
print(f"Good Morning {name.title()}!")
# In[5]:
username=["harry","larry","marry"]
# In[6]:
greet_user(username)
# In[8]:
#modyfying a list in function
unprinted_designs=["phone case","robot"," laptop"]
completed=[]
while unprinted_designs:
newdesign=unprinted_designs.pop()
completed.append(newdesign)
print(completed)
# In[13]:
def print_models(unprinted_design,completed_model):
while unprinted_design:
new=unprinted_design.pop()
completed_model.append(new)
print(completed_model)
# In[14]:
u=["which","is","this"]
b=[]
print_models(u,b)
# In[16]:
#copying a list without changing it's content
lis=["Pen",1,66,"wow"]
lis2=lis[:]
# In[17]:
print(lis2)
# In[19]:
print(lis)
# In[21]:
lis.append("I chaned something so i can prove ")
print(lis)
# In[22]:
lis2.remove(66)
lis2.append("I did not changed anythin")
print(lis2)
# In[28]:
#but if i sued like this
lis=[1,2,3,4,"something"]
lis1=lis
#if i modify or change something to lis1
#python will modify to lis too!
#so do prevent that sometimes we use [:] method!
# In[29]:
print(lis)
print(lis1)
#both are same let's try something
# In[30]:
lis.remove(4)
print(lis)
print(lis1)
#see both are affected by the change!
# In[34]:
test_list_for_function=["lets see if it can be changed in the function"]
print(test_list_for_function)
# In[39]:
def removing_and_checking(a):
for x in a:
# In[40]:
removing_and_checking(test_list_for_function)
# In[41]:
final=["cars","laptops","computers","phones"]
report=[]
# In[42]:
def check(a,b):
while a:
c=a.pop()
b.append(c)
print(b)
# In[43]:
check(final,report)
# In[45]:
print(final)
print(report)
#see the list i created have been affected
#because i used that in function and it poped out the
#objects in the list
#but there is a method or way to prevent this!
# In[46]:
final=["cars","laptops","computers","phones"]
report=[]
# In[47]:
check(final[:],report)
# In[50]:
print(final)
#can you believe that?
#it did not affect the orginal list when i
#used that in a function!!!!!
# In[51]:
print(report)
# In[56]:
shot_messages=["hey","how are you?","what are you doing","that's amazing!","i love friends","it's a great show i believe"]
print(shot_messages)
new=[]
# In[57]:
def check_messages(a,b):
while a:
c=a.pop()
b.append(c)
print(b)
#printing messages with while inside a fucntion
# In[58]:
check_messages(shot_messages[:],new)
# In[59]:
print(new)
# In[60]:
def check_again(a):
for x in a:
print(x)
# In[61]:
check_again(new)
#printing messages with for loop
# In[65]:
shot_messages=["hey","how are you?","what are you doing","that's amazing!","i love friends","it's a great show i believe"]
print(shot_messages)
new=[]
# In[66]:
def check_m_with_change(a,b):
while a:
c=a.pop()
b.append(c)
print(a)
print(b)
# In[67]:
check_m_with_change(shot_messages,new)
# In[69]:
print(shot_messages)
#after using function it's been changed
print(new)
# In[70]:
shot_messages=["hey","how are you?","what are you doing","that's amazing!","i love friends","it's a great show i believe"]
print(shot_messages)
new=[]
# In[73]:
#created a fucntion which can take list without changing it
def do_not_change(a,b): #if [:] here we will get error
while a:
c=a.pop()
b.append(c)
print(a)
print(b)
# In[74]:
do_not_change(shot_messages[:],new)
# In[6]:
#passing an Arbitrary number of arguments
def make_pizza(*toppings):
print(toppings)
# In[7]:
make_pizza("chicken","extra cheese","mushrooms")
# In[14]:
#using a for loop
def make_pizza(*toppings):
for topping in toppings:
print(f"Topping of pizza contain '{topping}'")
# In[15]:
make_pizza("chicken cheese","mushrooms","onion")
# In[22]:
#mixing positional argument and arbitrary argument
def make_pizza(size,*toppings): #*topping is the example of args!
print(f"The size of the pizza is {size}")
print("Your pizza is made from: ")
for topping in toppings:
print(f"{topping.title()}")
# In[23]:
make_pizza(18,"Mushroom","Chicken","Extra cheese")
# In[24]:
make_pizza(12,"Beef","extra cheese","olives")
# In[29]:
def build_profile(first,last,**user_info):#** will automatically create te dictionary
#**user_info is te example of *kwargs!
user_info["first"]=first
user_info["last"]=last
print(user_info)
# In[30]:
build_profile("tayyar","hussain")
# In[32]:
def building(name,location,**kwargs):
print(kwargs)
# In[33]:
building("sunny tower","lahore")
# In[36]:
#use of **args and *kwargs
def add(*args):
print(args)
print(sum(args))
# In[37]:
add(1,2)
# In[39]:
def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print(arg)
# In[40]:
#*args are list o arguments #they act like list
#**kargs are key word argument #tey act like dictionary
#args= unlimited number o arguments!
# In[41]:
#eg o args again
blog_1="I am cool"
blog_2="I am a Pyton Programmer"
blog_3="Computer Science is Amazing"
blog_4="I love Information Security"
# In[42]:
def blog_posts(*args):
for k in args:
print(k)
# In[44]:
blog_posts(blog_1) #only 1 argument
blog_posts(blog_2,blog_3) #more than 1 argument
# In[45]:
blog_posts(blog_1,blog_2,blog_3,blog_4)
#many arguments passed with getting into a problem
#but if had just defined certain numbers of argument
# In[46]:
def user_name(name,ID,**user_info):
user_info["name"]=name
user_info["ID"]=ID
print(user_info)
# In[47]:
user_name("fs142","247")
# In[49]:
#order sandwich
def sandwiches(*ingredients):
for k in ingredients:
print(f"You sandwich conatins: {k.title()}")
# In[61]:
sandwiches("Chicken","Mayo","Onions","Cabagge")
# In[62]:
sandwiches("Beef","Ketchup","Onion")
# In[63]:
sandwiches("Olives","mayo","mushrooms")
# In[5]:
def user_information(name,location,gender,**info):
info["name"]=name.title()
info["location"]=location.title()
info["gender"]=gender.title()
print(info)
# In[6]:
user_information("ahsan","lahore","male")
# In[8]:
user_information("tehseen","lahore","male")
# In[9]:
user_information("mehak","lahore","female")
# In[20]:
def cars_info(model,company_name,*about_car,**full_info):
full_info["model"]=model
full_info["company name"]=company_name
print(full_info)
print("OTHER INFORMATION ABOUT YOUR VEHICAL")
for x in about_car:
print(f"-->{x}")
# In[21]:
cars_info("YBR","Yamaha","Blue","125cc")
# In[22]:
cars_info("CD125","Honda Pakistan","125cc","Red color","2 Wheels","2 Side Mirrors")
# In[ ]:
Using Functions as Module
def make_pizza(size,*toppings):
print("You have ordered {size} inches pizza")
print("Which contains: ")
for x in toppings:
print(x.title())
# In[6]:
make_pizza(17,"extra cheese","chicken tikka")
# In[ ]:
#steps to modularize code
'''
1) write code and functions
2) download them as .py format
3)upload this downloaded .py file in the jupyter notebook directory where you are
currently working because it will be easier to track and check the file name etc
4) import the code into the new cell where your are working
5)method:
import x.py(it's the name of the file)
from x import'''
import pizza
from pizza import make_pizza
# In[9]:
make_pizza(16,"mushrooms","extra cheese")
# In[10]:
#steps to modularize code
'''
1) write code and functions
2) download them as .py format
3)upload this downloaded .py file in the jupyter notebook directory where you are
currently working because it will be easier to track and check the file name etc
4) import the code into the new cell where your are working
5)method:
import x.py(it's the name of the file)
from x import x(function)--> any function you want to use!'''
# In[14]:
import math #imported a math module
from math import sqrt #from the math module i called a special function of sqrt
a=4
sqrt(a)
# In[19]:
#made a .py file which will take name and id and convert it into a dictionary
import example
from example import your_info
your_info("ahsan","223") #here as you can see i made my own code then imported into new cell to reuse the code
# In[23]:
import example
your_info("ahsan",33)
# In[1]:
import test
from test import user
# In[2]:
user(1,2)
# In[3]:
user(5,9)
# In[5]:
user(1,2)
# In[7]:
user(1,2)
# In[9]:
import pizza
# In[12]:
pizza.make_pizza(23,"Mushrooms","Chicken","Extra cheese") #emporting the entire module
# In[14]:
#importing specifice functions from a module
import math
from math import sqrt #importing just sqrt function from whole math module
sqrt(100)
# In[15]:
import pizza
from pizza import make_pizza
# In[17]:
make_pizza(22,"chicken tikka","olives","mushrooms","extra mozzarella chesse")
# In[18]:
'''uf te name of a function your are importing
might conflict with an existing name in your program
or if the function name is long your can use a short
unique alia an alternae name similar to nickname for the function
which you are trying to import
'''
import math
from math import sqrt as square
# In[22]:
square(100)
#see here i changed the name of sqrt as square!
# In[23]:
sqrt(100) #even with changing you can still use the perivious name
# In[26]:
#lol you can even import the module and change the name of it
import pizza as order
from pizza import make_pizza
# In[29]:
import math as m
m.sqrt(100) # changed the module name here
# In[32]:
#changing the module name and also the function name at the same time
import math as m
from math import sqrt as s
# In[34]:
s(100)
# In[35]:
m.sqrt(100)
# In[36]:
#importing all the functions in a module
from math import *
# In[38]:
#styling your function
def riches(p1,p2,p3,p4,
p5,p6,p7,p8,p9,p10):
return sum(int(p1,p2,p4,p5,
p6,p7,p8,p9,p10))
#if the functions have too many arguments
#then you should use styling method to code
#your function so it can be readable easily to others
#
---------------------------------------------------------------------------------------------------------------------
Chapter 9 Classes and OOP
CISSP training certificate from Al-Nafi