Welcome to lesson 2 of this python workshop
What will we be doing today
- Do more practices to get you familar with coding
- Introduce new concepts like while loop and dictionary
- Some interesting things that you can do with python
Warm up and recap
- Try to figure out what the following outputs before you run the code to check
Q1 : Final Score Calculator
Let's write some Python code that helps you calculate your final cumulative score for a course titled "Introduction to University Life".
This course has several assessments. For each assessment, there is a total score, which is the maximum score you could achieve for that assessment. Each assessment counts towards a certain percentage of the final cumulative score. The final cumulative score is on a scale of [0 - 100].
The assessments of this course are shown below:
- Assignments:
- Assignment 1: (total score 10 marks), 10%
- Assignment 2: (total score 10 marks), 10%
- Assignment 3: (total score 10 marks), 10%
- Tests:
- Test 1: (total score 30 marks), 15%
- Test 2: (total score 40 marks), 20%
- Exam: (total score 140 marks), 35%
For example, Test 1 is 30 marks in total and counts towards 15% of your final score. If your raw score for Test 1 is 20 marks, it is two thirds of the total score for Test 1 and it will contribute 10 marks (which is two thirds of 15) to your final cumulative score.
Your code should produce the following sample output:
# ######################### # Write your code below: # ######################### A1 = float(input("What's your score for Assignment 1?")) A2 = float(input("What's your score for Assigment 2?")) A3 = float(input("What's your score for Assignment 3?")) T1 = float(input("What's your score for Test 1?")) T2 = float(input("What's your score for Test 2?")) EX = float(input("What's your score for the exam?")) final= ((A1+A2+A3) + (15*(T1/30)) + (20*(T2/40)) + (35*(EX/140))) print("Your final cumulative score is " + str(final) + "/100")
Q2: Currency
If you visit the United States, you'll need to get familiar with their currency and the various coins and notes in circulation. Look at this link to find out more about their various coins and notes: http://www.immihelp.com/newcomer/usa-currency-coins.html
Here's a list of common coins:
- Penny - 1 cent
- Nickle - 5 cents
- Dime - 10 cents
- Quarter - 25 cents
And the commonly used notes are : $1, $5, $10 and $20 notes.
Let's write some Python code that prompts the user for an amount to pay (in US$) and that helps him/her to know how many coins or notes he/she has to provide in each denomination, to provide the exact change.Some starting code is already given to you (which takes care of the conversion pricision from float to int - you can ignore ).
Your code should produce the following sample output:
#Q2 ######### amount = float(input("Enter payment amount (US$) :")) # ################################ # Write your code below: # ################################ money_list = [20,10,5,1,0.25,0.1,0.05,0.01] num_list = [] for value in money_list: num = amount // value num_list.append(num) amount = round(amount%value,2) print("You need to give:" + '\n'+ str(num_list[0]) + " 20 dollar notes" +'\n'+ str (num_list[1]) + " 10 dollar notes" + '\n'+ str(num_list[2]) + " 5 dollar notes" +'\n'+ str(num_list[3]) + " 1 dollar notes"+ '\n'+ str (num_list[4]) + " quarter coins" + '\n'+ str (num_list[5]) + " dime coins" + '\n'+ str (num_list[6]) +" nickle coins" + '\n'+ str (num_list[7]) + " penny coins")
You need to give: 7.0 20 dollar notes 1.0 10 dollar notes 1.0 5 dollar notes 2.0 1 dollar notes 3.0 quarter coins 1.0 dime coins 0.0 nickle coins 4.0 penny coins
For loops and if else statements
for Loops
(Top) A
for
loop acts as an iterator in Python; it goes through items that are in a sequence or any other iterable item. Objects that we've learned about that we can iterate over include strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or values.We've already seen the
for
statement a little bit in past lectures but now let's formalize our understanding.Here's the general format for a
for
loop in Python:for item in object: statements to do stuff
if, elif, else Statements
if
Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results.Syntax:
if case1: perform action1 elif case2: #if case 1 not true but case 2 is true, perform action two perform action2 else: perform action3
Q3: Ciphertext
Ciphertext is a result of encryption performed on plaintext using a algorithm, inorder for you to encode and decode a ciphertext you need a key.
How the encryption work: you have a string from a-z and for all the letters in the key, you take out these letters from the string and place it at the back of the string to give you a different series of 26 characters. Then you map whatever that is in the text from the first string to the second string
Part 1 [ ** ]: Implement a function called
cipher_text
that takes in the following parameters:- `text`: the text to be encrypted
- `key`: the key used to encrypt the text
and returns the encrypted text
For example, The text is i love sutd, the key is apple then the second string will be bcdfghijkmnoqrstuvwxyzaple Then you compare the first string, the second string and the text. i is at position 8 of the first string and hence it should be replace by the character at position 8 of the second string which is k so on and in the end you will get a encrypted text k oszg wyxf
You may find the function string.index(ch) useful, it reutrns you the position of ch in the string, this works with a list also
def cipher_text(text,key): #can break down into smaller functions first_string = 'abcdefghijklmnopqrstuvwxyz' second_string = '' unique_ch = '' for ch in first_string: if ch not in key: second_string += ch else: unique_ch += ch second_string += unique_ch encrypted_text = '' for ch in text: if ch == ' ': encrypted_text += ' ' else: pos = first_string.index(ch) encrypted_text += second_string[pos] return encrypted_text
Part 2 [ ** ]
: Those of you who are interested or faster than the rest can try to implement a function called
decipher_text
to convert the encrypted message into normal language.Dictionary
Dictionary is a structure in python just like list. Both are mutable, dynamic(no fix size) and can be nestd
For dictionary there are only 2 things to note
- key
- value
The data that is stored in dictionary is always a key-value pair.
You can access the value of a pair via the key.
Dictionary is very uesful for database creation and packaging of data and transmit it. ie: transmitting user details from the server to the website frontend.
Some basic syntax
#declaring my_dict = {}
#a dictionary can hold differnt kind of data my_dict['another_dict'] = {'key_one':'value_one','key_two':'value_two'} print(my_dict['another_dict'])
my_dict['a_list'] = ['a','b','c','d'] print(my_dict['a_list'])
#accessing all the key and values in a dictionary for key in my_dict.keys(): print(key)
for value in my_dict.values(): print(value)
for key,value in my_dict.items(): print(key,value)
#Sorting a dictionary test_dict = {1:'a',53:'a',15:'e',3:'q',63:'q',4:'k',24:'s',14:'r',3:'c'}
#By their keys print(sorted(test_dict.items()))
How to sort a dictionary by their values
Now that we know how to sort the dictionary by their keys, how do we do so for values?
code your own logic that outputs a sorted version of the dictionary
#By their values sorted_dict = {}# create another empty dict ''' This method is very ineffective since for every value in sorted list you have to iterate through the entire dictionary to find the matching key_value pair ''' for sorted_value in sorted(test_dict.values()): #iterate through a sorted list containing the values of the dictionary for key,value in test_dict.items(): #iterate through all the items in the dictionary if value == sorted_value: sorted_dict[key]=value print(sorted_dict) print(sorted(test_dict.items(),key = lambda item:item[1]))
While loop
- abit similar to for loop, but it keeps running until the condition is false
- the main difference between for loop and while loop is
- for loop is used in situations where you know the number of iterations to go through
- while loop is used in situations where you do not know the number of iterations to go through but you know what is the condition that it should stop
# Only when the condition behind the while statement is True, then only it will enter the loop # So do remember to update the condition for you to exit the while loop. # Unless you want it to run forever index = 1 while index < 5: print('This statement is printed {} times'.format(index)) index += 1 print(index)
# one of the important application of while loop is to validate input from user # prompt the user to input their gender and if its not M or F you will notify them that its wrong input and ask them to input again # Put your code below gender= input("What's your gender? Please enter M or F: ") while not(gender == 'M' or gender == 'F'): print("Wrong input") gender= input("What's your gender? Please enter M or F: ") if gender == 'M': print("Thanks! Your gender is male.") if gender == 'F': print("Thanks! Your gender is female")
Q4: Number Guessing Game
Part 1 Write a piece of code that does the following:
- The program first generates a random number between 1 and 100 (both inclusive). You can try to make the range to be a user inputYou can use the
randrange()
orrandint()
function from therandom
module to generate the number.
- The program then keeps prompting the user to guess the random number generated until the user's guess is correct. When the guess is wrong, the program gives a hint about whether the guess is too low or too high.
A sample run of the program can be found below. Note that in this sample run 95 is the random number generated in the beginning.
Enter your guess (between 1 and 100) :34 Your guess is too low! Enter your guess (between 1 and 100) :58 Your guess is too low! Enter your guess (between 1 and 100) :73 Your guess is too low! Enter your guess (between 1 and 100) :86 Your guess is too low! Enter your guess (between 1 and 100) :99 Your guess is too high! Enter your guess (between 1 and 100) :90 Your guess is too low! Enter your guess (between 1 and 100) :95 Bingo!
# Put your code below import random random_value= random.randrange(1,100) guess= int(input("Enter your guess (between 1 and 100): "))#select a random number within the range while not (guess == random_value):#if they have not guess the value, keep the loop running if guess > random_value: print("Your guess is too high!") guess= int(input("Enter your guess (between 1 and 100): ")) if guess < random_value: print("Your guess is too low!") guess= int(input("Enter your guess (between 1 and 100): ")) print("Bingo!")
Q4: Number Guessing Game
Part 2 Write a piece of code that does the following:
- The program first generates a random number between 1 and 100 (both inclusive). You can try to make the range to be a user inputYou can use the
randrange()
orrandint()
function from therandom
module to generate the number.
- The program then keeps prompting the user to guess the random number generated until the user's guess is correct. When the guess is wrong, the program gives a hint about whether the guess is too low or too high and keep track of the current range of valid guesses.
A sample run of the program can be found below. Note that in this sample run 95 is the random number generated in the beginning.
Enter your guess (between 1 and 100) :34 Your guess is too low! Enter your guess (between 34 and 100) :58 Your guess is too low! Enter your guess (between 58 and 100) :73 Your guess is too low! Enter your guess (between 73 and 100) :86 Your guess is too low! Enter your guess (between 86 and 100) :99 Your guess is too high! Enter your guess (between 86 and 99) :90 Your guess is too low! Enter your guess (between 90 and 99) :95 Bingo!
import random #get the range from the user input start = int(input('Enter the start of the range:')) end = int(input('Enter the end of the range:')) random_value= random.randrange(start,end)#select a random number within the range guess= int(input("Enter your guess (between"+ str(start)+" and " +str(end)+ "): ")) while not (guess == random_value):#if they have not guess the value, keep the loop running if guess > random_value: print("Your guess is too high!") end = guess #if the guess is higher than the value then change the upper bound guess= int(input("Enter your guess (between"+ str(start)+" and " +str(end)+ "): ")) else: print("Your guess is too low!") start = guess#if the guess is smaller than the value then change the lower bound guess= int(input("Enter your guess (between"+ str(start)+" and " +str(end)+ "): ")) print("Bingo!")
That is all for today!!!
- Hope you have fun today! If you don't understand it is ok, coding really takes some time to get yourself familiar with it.
- If you are more confident in coding you can try to work on some projects using python. may help in your 1d project also
- Here are some of my recommendations:
- web scraping
- data analysis using pandas
- backend development using django or flask
- telegram bot https://medium.com/ieee-manipal/build-a-telegram-bot-using-python-23b13549856f