#Tuple Example:
# We know provinces of Pakistan will not change for a while, so we can define a tuple and reference it.
provinces_of_pakistan = ("Baluchistan","Gilgit Baltistan","Punjab","Sindh","KPK")
print(provinces_of_pakistan)
# You can access the individual elements of tuple in same way as you were doing for the list.
#Let's print each element individually.
print(provinces_of_pakistan[0])
print(provinces_of_pakistan[1])
print(provinces_of_pakistan[2])
print(provinces_of_pakistan[3])
print(provinces_of_pakistan[4])
# You can also check type of a variable in same way:
type(provinces_of_pakistan)
# now, if I want to replace a value or assign a new value, it will give error. lets try doing it:
provinces_of_pakistan[0] = "Islamabad"
In simple number iterations, we use range function. range function returns consecutive numbers between two end points. its syntax is range(0,10). Note that if you put one number in range i.e. range(10), it will automatically assume that the starting point is 0.
Note that the if you set range (0,10), it will go from 0 until 9, running exactly 10 times.
syntax for for loop is as follows:
for any_variable in range(0,10):
whatever you want to print is indented inside for loop block.
This will not be a part of for loop
#Print Hello World 10 times
for i in range(0,10):
print("Hello World")
#Now Lets try to print the range value in each loop
for i in range(0,10):
print(f"This is the {i} iteration of loop")
#Let's try to add an if condition and seggregate the even and odd numbers of i.
for i in range(0,10):
if(i%2==0): # we have used remainder operator and equated it equal to 0 to check if the number is fully divisible by 2 or not.
print(f"The {i} is even")
else:
print(f"The {i} is odd")
# Similarly, lets try to print a list with for loop
fruits = ["Apple","Orange","Guava","Pear","Grapes","Mango","Watermelon"]
for i in fruits: # Here, instead of range, we have given directly the name of list. Now i, in each iteration, will be the entry of the list.
print(i) #Simply printing i will give us the list elements one by one.
# to find length of any string, we can use len().
# Now, lets try to find and print length of all entries in our fruits list
fruits = ["Apple","Orange","Guava","Pear","Grapes","Mango","Watermelon"]
for i in fruits:
print(f"The length of {i} is {len(i)}")
# Another example: lets try to add 10 numbers in a list using for loop
my_list = [] #We define an empty list for future use.
for i in range(1,11): #Notice, I started from 1 and went until 11 so that loop goes from 1 to 10.
my_list.append(i) #We saw in past the append function. It appends the value of i in my_list.
print(my_list)
#Example:
#Lets say we have a list with some garbage values in them.
#We know that garbage values have a length of 3 characters or lower and our required data has minimum 4 characters in it.
# Using For loop, we can easily differentiate between actual data and garbage values
list1 = ["Table","Chair","???","$$","Tyre","^^","Pillow"]
filtered_list = []
for i in list1:
if(len(i)>3):
filtered_list.append(i)
print("original list was ",list1)
print("filtered list is ",filtered_list)
my_list = [1,4,3,5,4,5,6,1,4,6,5,3,5,6,7,4,3,1,4,4,5,1,0]
for i in my_list:
if(i==4):
print("found a 4")
else:
print(f"{i} is not a 4")
my_list = [1,4,3,5,4,5,6,1,4,6,5,3,5,6,7,4,3,1,4,4,5,1,0]
for i in my_list:
if(i==4):
print("found a 4")
break
print(f"{i} is not a 4")
# Example 1:
students = ["Ali","Asim","Sara","Hira"]
subjects = ["English","Math","Physics","Chemistry"]
#We take one loop for students and other for subjects
for student in students:
for subject in subjects:
print(student+"-"+subject) # Notice how print statement is written inside the inner for loop
#Explanations on why is it running so?
#Lets go to line 6 and see when the for loop runs for the first time, student gets value of Ali i.e.
#first element of students list.
# now in line 7, another loop starts and subject gets value English.
# so the value that gets printed is Ali-English
# Now, the loop goes back to line 7 as the subjects list is not finished and subject now gets the value Math.
#Note that student still has value Ali since inner loop is not ended yet.
# Value printed now is Ali-Math
# In the same way the values are printed until Ali-Chemistry, after which the loop exits and goes to parent loop which now gets a new value for student and loop starts again.
#Step 1: generating password
#Password has format of 42_92_52 i.e. 3 random numbers concatenated with an underscore.
import random #This command imports random library
#Here, we are generating a random number using randint function
#and giving it the range in which we need a number to be generated
#Note that the password will change everytime you run this cell. So make sure you run it everytime you want a new password.
code1 = str(random.randint(10,99))
code2 = str(random.randint(10,99))
code3 = str(random.randint(10,99))
#Now Combining Password
password = code1+"_"+code2+"_"+code3
#Here we have three loops nested within each other.
for cd1 in range(10,99):
for cd2 in range(10,99):
for cd3 in range(10,99):
i = str(cd1)+"_"+str(cd2)+"_"+str(cd3) #in the innermost loop, we have the string that matches format of password (lets say someone told us the format ;-))
if(i==password): #If we get the password right?
print(f"Password decoded!. the password is {i}")
break # this break statement helps us break out of the code as soon as we get the password and not continue further.
variable_name = input("Prompt that is to be shown to user:")
name = input("Enter your name : ")
age = input("Enter your age: ")
#you can use input() function directly in an if statement
#Note, you cannot save the marks, hence only one if statement is possible.
if(int(input("Enter your marks: "))>50):
print("Pass")
else:
print("Fail")
#checking the types:
print(type(name))
print(type(age))
#As you can see both inputs are strings even though age is a numberic number.
#So we explicitly convert age into integer values now.
name = input("Enter your name : ")
age = int(input("Enter your age: "))
print(type(name))
print(type(age))
data_type_to_be_converted_to(variable_name or input function)
int(age)
float(temperature)
#Example:
age = "21"
temperature = "31.5"
print("Before converting, type of age is: ",type(age))
print("Before converting, type of temperature is: ",type(temperature))
print("After converting to int, type of age is: ",type(int(age)))
print("After converting to float, type of temperature is: ",type(float(temperature)))
name = name.lower()
name = name.upper()
name = name.title()
name = "AhSaN FaRoOqUi"
print("Title: ",name.title())
print("Lower case: ",name.lower())
print("Upper case: ",name.upper())
#Example:
# Lets define a list of fruits and everytime a user enters a fruit name, it checks whether the fruit name is available or not in the list.
fruits = ["Orange","Mango","Peach","Guava","Watermelon"]
for i in range(10): #Asking user 10 times
user_input = input("Enter a fruit name: ")
user_input = user_input.title()
if(user_input in fruits):
print("You guessed the fruit correctly.")
else:
print("Sorry!")
string_name = string_name.replace("character/string to be replaced","character/string to be replaced with")
my_string = my_string.replace("o","%")
# Example:
#Take a string from user and if the user string has any of the following words, replace them by aesteriks
#Words: assignment,quiz,exam
user_input = input("enter a string: ")
user_input = user_input.lower()
user_input = user_input.replace("assignment","*********")
user_input = user_input.replace("quiz","****")
user_input = user_input.replace("exam","****")
# You can also use .replace in same line
# For example
#user_input = user_input.replace("assignment","*********").replace("quiz","****").replace("exam","****")
print(user_input)
#Example:
# Coming back to the fruits problem, now we can simply replace any spaces with a null string.
fruits = ["Orange","Mango","Peach","Guava","Watermelon"]
for i in range(10): #Asking user 10 times
user_input = input("Enter a fruit name: ")
user_input = user_input.replace(" ","") #<--- Here's how I replaced any spaces with null strings
user_input = user_input.title()#<-- Notice I converted the case after replacing the spaces.
if(user_input in fruits):
print("You guessed the fruit correctly.")
else:
print("Sorry!")
my_name = {"first_name":"Ahsan","last_name":"Farooqui","age":29}
#Example1:
my_list = {"first_name":"John","last_name":"Doe","age":38,"score":45.5}
print(my_list["first_name"])
print(my_list["last_name"])
print(my_list["age"])
print(my_list["score"])
#Example2: We now define a dictionary that has keys countries, cities and population
# but instead of having one value, we have a list instead.
# lets see how we can now print values
# for this particular example, I used the same sequence i.e. first element of all lists relate to jordan and so on.
collections = {"countries":["jordan","syria","china","usa"],
"cities":["Amman","Damascus","Beijing","Washington D.C"],
"population":["9.956M","16.91M","1.39B","328.2M"]}
#Printing all countries
print(collections["countries"])
#Printing all cities
print(collections["cities"])
#Printing all popullations
print(collections["population"])
#Now, that the list is accessed, we can access any element in that list using same list referencing i.e. 0,1,2 etc.
#Lets access first element of all lists
print(collections["countries"][0])
print(collections["cities"][0])
print(collections["population"][0])
#Now, lets create a loop to display all options:
for i in range(len(collections["countries"])):
print(f'First country name is {collections["countries"][i]}. Its capital is {collections["cities"][i]} and has a population of {collections["population"][i]}' )
#Keys can be integer values as well. Lets take an example:
things_to_remember = {0:"the lowest number",
12: "a dozen",
13:"a baker's dozen",
11: "snake eyes"}
print(things_to_remember[0])
print(things_to_remember[12])
print(things_to_remember[13])
print(things_to_remember[11])
things_to_remember[25] = "Silver"
things_to_remember[50] = "Gold"
things_to_remember[0] = "smallest number"
#The updated dictionary now becomes:
things_to_remember
del things_to_remember[11]
#Now the dictionary becomes:
print(things_to_remember)
#Printing Keys and Values separately.
print(things_to_remember.keys())
print(things_to_remember.values())
print(things_to_remember.items())
for each_value in dictionary_name.values():
print(each_value)
for each_key in dictionary_name.keys():
print(each_key)
#Example for values
my_list1 = {"first_name":"Ahsan",
"last_name":"Farooqui",
"Age":29,
0:"min value",
100:"max value"}
for each_value in my_list1.values():
print(each_value)
#Example for keys
for each_key in my_list1.keys():
print(each_key)
for each_key,each_value in dictionary_name.items():
print(each_value,each_key)
customer_data = {"name":"John",
"id":30,
"joining date":"2019-04-01",
"total spent":340000}
for key,value in customer_data.items():
print(key,"-",value)
{first user data dictionary},
{second user data dictionary
]
customers_data[0][key_name]
#Let's create a list of dictionaries with 5 customer details
customers_data = [
{"name":"John",
"date_joined":"2019-02-02",
"amount_spent":45000,
"customer_level":"Gold"}
,
{"name":"Robin",
"date_joined":"2018-02-02",
"amount_spent":120000,
"customer_level":"Platinum"}
,
{"name":"Rob",
"date_joined":"2016-02-02",
"amount_spent":100,
"customer_level":"Rookie"}
]
import pprint #An optional feature just to print dictionary in beautiful way, please comment it if you get library error.
pp = pprint.PrettyPrinter(indent=4) #This is just to print the dictionary in a beautiful way. Totally optional.
#Now we print the first customer's complete data
pp.pprint(customers_data[0])
#Now let's get first customer's name only.
print(customers_data[0]["name"])
#How about last customer?
print(customers_data[-1]["name"]) #Negative indexes corresponds to the values from last. -1 is for the last value in list, -2 is second last and so on.
#Negative indexes are helpful when you dont know the actual list length.
#Any ideas on how to get all names?
for customer in customers_data: #Each customer gets a dictionary value.
print(customer["name"]) #We can simply print the values in each iteration.
#Try to get all information yourself.
Create the new user's dictionary first separately.
new_customer = {'amount_spent': 0,
'customer_level': 'Newbie',
'date_joined': '2020-05-20',
'name': 'James'}
Protip: if you wish to append the list's index as id in the new customer's data, you can do it like following:
Once we have the dictionary created, we can simply use the list's append function to append the new value.
list_name.append(new_customer)
#Example:
#Defining the new customer's data:
new_customer = {'amount_spent': 0,
'customer_level': 'Newbie',
'date_joined': '2020-05-20',
'name': 'James'}
#Now appending it to the original list
customers_data.append(new_customer)
#Printing afterwards:
customers_data
We have following user's data.
new_customer = {'amount_spent': 0,
'customer_level': 'Newbie',
'date_joined': '2020-05-20',
'name': 'James'}
Now, we wish to add a list to it.
new_customer["discounts"] = ["10PercentOn4Items","5percentOn1Item"]
new_customer = {'amount_spent': 0,
'customer_level': 'Newbie',
'date_joined': '2020-05-20',
'name': 'James'}
new_customer["discounts"] = ["10PercentOn4Items","5percentOn1Item"]
new_customer
#From previous example, lets take the customer's data
new_customer = {'amount_spent': 0,
'customer_level': 'Newbie',
'date_joined': '2020-05-20',
'name': 'James'}
new_customer["discounts"] = ["10PercentOn4Items","5percentOn1Item"]
new_customer
#Let's try to print the discounts list now.
new_customer["discounts"]
#Let us create a new keyword named discountpercent and put it equal to zero.
new_customer["discountpercent"] = 0
#Now lets make a for loop and search for discounts and add the percentages accordingly in a new keyword "discountpercent"
for item in new_customer["discounts"]:
if(item=="10PercentOn4Items"):
new_customer["discountpercent"] += 0.10
elif(item=="5percentOn1Item"):
new_customer["discountpercent"] +=0.05
else:
new_customer["discountpercent"]+=0
#So now the new dictionary becomes:
new_customer
# Previously we had the following list:
customers_data = [
{"name":"John",
"date_joined":"2019-02-02",
"amount_spent":45000,
"customer_level":"Gold"}
,
{"name":"Robin",
"date_joined":"2018-02-02",
"amount_spent":120000,
"customer_level":"Platinum"}
,
{"name":"Rob",
"date_joined":"2016-02-02",
"amount_spent":100,
"customer_level":"Rookie"}
]
# Simply replacing the square brackets [] with {} to convert it into a dictionary:
#And we need to give a key name to these values. So lets try to give them the customer's name.
customers_data_dict = {
"John":{"name":"John",
"date_joined":"2019-02-02",
"amount_spent":45000,
"customer_level":"Gold"}
,
"Robin":{"name":"Robin",
"date_joined":"2018-02-02",
"amount_spent":120000,
"customer_level":"Platinum"}
,
"Rob":{"name":"Rob",
"date_joined":"2016-02-02",
"amount_spent":100,
"customer_level":"Rookie"}
}
#Now, Let's access John's data
customers_data_dict["John"]
#For any specific data from this dictionary, we use another index ahead of the key.
customers_data_dict["John"]["customer_level"]