Lesson 3 Assignment Solution
Anchor Links
Introduction
Hi all! The purpose of this assignment was to get you familiar with the basics of Python that we covered in Lesson 3 which include:
- Variables and Data Types
- Looping By Element/Index
- If Statements
- Functions
The solution to all the questions with detailed explanations are below. Do take your time to look through and see where you went wrong.
Questions
Question 1
- Define a variable called
num_negand set its value to be a negative integer. - Define a variable called
num_posand set its value to be a positive version ofnum_neg; for e.g ifnum_negis -5, thennum_posshould be 5. - Define a variable called
myStringand set its value to a string. - Define a variable called
myListand set its value to a list containing at least 5 elements. - Define a variable called
myFloatand set its value to the decimal point version ofnum_pos; for e.g ifnum_posis 5, thenmyFloatshould be 5.0.
Solution:
num_neg = -5
num_pos = 5
myString = "Hello world!"
myList = [1, 2, 3, 4, 5]
myFloat = 5.0
This question primarily targets your understanding of variables and data types. The solution to each of the steps is pretty straight-forward and easy if you have mastered the concept, however do remember the key difference between integers and floats which is that integers are whole numbers while floats are numbers with a decimal point (or floating point, hence the name float). Not much explanation is needed for this as this way a bit of a give away question.
Question 2
Define two integers. Print the product of the two integers divided by two. Write down what data type the resulting output is in.
For e.g, if the two integers are 5 and 10, then the output should be (5 * 10) / 2 = 25.
Solution:
first = 10
second = 15
print((first*second)/2)
### OUTPUTS THIS:
75.0
Statement Answer: The resulting output is of the data type of float.
For this question, it tests you on your ability to use basic mathematical operators and whether you can identify the data types of outputs. As for the code, first you have to define two variables that store integers (the variable names can be anything you desire). Then, in order to multiply them together then divide by 2, we first bracket up the multiplication like so: (first*second) and then divide the whole thing by 2 like so: (first*second)/2 and print it out. The output should be a float because Python always returns a float when you are dividing two numbers because the output of division is not necessarily always a whole number.
Question 3
Define a variable with a data type of float. Define another variable called result which is the result of the multiplication of the float variable and 10. Print out the result variable.
Solution:
myFloat = 72.4
result = myFloat*10
print(result)
### OUTPUTS THIS:
724.0
This question was also pretty straight-forward; first define a float, then define a variable called result which stores the result of myFloat multiplied with 10. Then, print the result.
Question 4
Given a list:
lst = ["5", 5]
Use looping by element to loop through lst and print out each element. Write down the key difference between the two elements in the list.
Solution:
lst = ["5", 5]
for elem in lst:
print(elem)
Statement Answer: The key difference is that the first element is a string while the second element is a integer.
This question onwards, we move on to Control Flow and specifically for loops. Following the question’s requirements of using for loop by element, we use the format of for <temporaryIterationVariableName> in <listVariableName>: to make a for loop which will loop through the list and print out every single element by the end of two iterations. For the statement answer, you have to identify that the number 5 in the first element is surrounded by two "" (double quotation marks) and hence makes it a string, not an integer, unlike the second element which is an integer.
Question 5
Complete the code below that would give the output:
names = ["Bob", "Ashton", "Jack", "Neo"]
for ___ in range(___, ____):
print(names[____])
OUTPUT:
Bob
Ashton
Jack
Neo
Solution:
names = ["Bob", "Ashton", "Jack", "Neo"]
for index in range(0, 4):
print(names[index])
This question tests you on for looping by index. While you could easily do the same with for looping by element (which is actually a shortcut of the former), we want you to specifically try and think of a way to do the same thing with looping by index. For the solution, you have to identify that the indexing sequence of the list is from 0-3, hence you make the range function like so: range(0, 4) (remember that it is always the inclusive integer then the exclusive integer). You can give and iteration variable name you like, in this case, I put in index (do note that you have to be consistent in your usage however). Then, I accessed the individual list elements by subscripting the list using the square brackets ([]) and the variable index that changes for every iteration like so: names[index]. In layman terms, the code basically says that for ever number for the range of 0-3, use the number to access each element in the list of names and print it out.
Question 6
Given the list:
grocery_items = ["Carrots", "Capsicums", "Onions", "Milk", "Oranges"]
Write a for loop to list all the items in the grocery_list list in a neat manner like so in the sample output below:
1. Carrots
2. Capsicums
3. Onions
4. Milk
5. Oranges
Solution:
grocery_items = ["Carrots", "Capsicums", "Onions", "Milk", "Oranges"]
count = 1
for item in grocery_items:
print("{}. {}".format(count, item))
count = count + 1
Alternative Solution:
grocery_items = ["Carrots", "Capsicums", "Onions", "Milk", "Oranges"]
for count in range(1, 6):
print("{}. {}".format(count, grocery_items[count - 1]))
This question is meant to be a bit tricky and meant to force you to think outside the box. Since the question requires you to list the grocery_items in a human-readable order which includes an increasing numbering order (the 1. thing), if you are planning to use for looping by element, you will have to create a separate variable called count to keep track of the number of iterations and so that you can update and reference this variable when you output the string. First, initialise the variable with 1 since the first item would be 1.. Then, create a for loop by element like so: for item in grocery_items. Then, write a print statement that inserts the two variables of count and the current item of the iteration using string interpolation like so: print("{}. {}".format(count, item)) (remember that interpolation is like replacement, where the parameters in the format function will replace all the {} in the string in order). After that, since its an increasing order, you have to remember to increase your count variable by 1, hence do: count = count + 1 (so if count is initially 1, it would become 2, and would eventually become 5 in the end because there are 5 iterations.)
As for the alternative of using looping by index, which is a bit more complicated but also more compact, my suggested answer recommends that you create a range of 1-5 (which is the actual range of the increasing order that is to be outputted) using the range function like so: range(1, 6). Then, do some complicated string interpolation to output the grocery item; the first replacement would be the number in the order that is to be shown, which would be the count variable that is initialised as the temporary iteration variable in the for loop definition statement. The second replacement would be the actual name of the item, which we can access by subscripting the grocery_items list. Since the indexing sequence of a list actually starts at 0, we will have to minus 1 from the count variable before using it to access each element in the list. Hence, the string interpolation: "{}. {}".format(count, grocery_items[count - 1]) comes about.
Question 7
Provide the output for the following code (or write down the error if any):
prakhar = "trivedi"
ashton = "neo"
if prakhar == ashton:
print("Prakhar is the imposter.")
else:
print("Prakhar is Prakhar")
elif prakhar == "trivedi":
print("Prakhar is Trivedi.")
Solution:
Statement Answer: There is an error in the code because the else statement must be the last in an if-else chain; which is not the case here as there is an elif statement after the else statement.
This question is meant to test you on your understanding of if statements and decision-based action code. The first condition compares the values of two variables of prakhar and ashton and if they are equal, it will print out Prakhar is the imposter.; otherwise, it will print out Prakhar is Prakhar. The elif statement compares the values of prakhar and trivedi and if they are equal, it will print out Prakhar is Trivedi.; otherwise, it will print out Prakhar is Prakhar. The else statement must be the last statement in the if-else chain and it is not allowed to be after the else.
Question 8
Given two variables:
apple_cost = 1.5
orange_cost = 1.2
Write an if statement that compares the two variables in the sense that if apple_cost is higher than orange_cost, "Apple is more expensive than orange" is printed out, if not, "Apple is less expensive than orange" is printed out.
Solution:
apple_cost = 1.5
orange_cost = 1.2
if apple_cost > orange_cost:
print("Apple is more expensive than orange.")
else:
print("Apple is less expensive than orange.")
This question is pretty striaghtforward with just one condition. We compare the values of the two variables using the “more than” operator (>) and if the condition, that apple_cost is more than orange_cost, is true, we print out the string "Apple is more expensive than orange"; otherwise, we print out the string "Apple is less expensive than orange".
Question 9
NOTE: This question is one of the more tedious and difficult ones. It is meant to confuse you. Please look at the code extremely carefully and identify the difference between
falseandFalseandTrueandtruebefore answering.
Provide the output for the following code:
false = True
true = False
if True == False:
print("True is false...life is a lie.")
elif false and true:
print("Both false and true are true, I think...")
elif (not false) and true:
print("Both true and true are true, obviously.")
elif (not true) and (not false):
print("The opposite of both variables is true.")
elif false or (not true):
print("Either false or false is true..., what?")
elif not (false and true):
print("The opposite of false and true is true?????")
else:
print("I give up....")
Solution:
Output: Either false or false is true…, what?
This question is actually the hardest in the set and meant to really takes testing your understanding to the extreme. It mainly tests your understanding of boolean operators.
Recall that the boolean operators are:
and:True and True = True(both the first and second operands are true)or:True or False = True(either the first or second operands are true)not:not True = False(flips it;TruebecomesFalseand vice versa)
The key thing you need to note is the difference between true and True; the capitalisation makes a world of difference. At the start of the code, true (without the capitalisation) is actually defined as False (the Python in-built value) and false (without the capitalisation) is actually defined as True (the Python in-built value). This can get rather confusing to keep track of when you actually look at the if-else chain thats in the code.
Below is a complete translation of the if-else chain in the code to make it easier to understand:
if True == False:
print("True is false...life is a lie.")
elif True and False:
print("Both false and true are true, I think...")
elif (not True) and False:
print("Both true and true are true, obviously.")
elif (not False) and (not True):
print("The opposite of both variables is true.")
elif True or (not False):
print("Either false or false is true..., what?")
elif not (True and False):
print("The opposite of false and true is true?????")
else:
print("I give up....")
The translation will make it much clearer to understand the condition and identify the action code that will be run. If you go through the chain step-by-step, you will identify that the condition True or (not False) is the only condition that results to True and hence print("Either false or false is true..., what?") will be run.
Question 10
Write a function called percent_calculator() that takes in two arguments of score and out_of and calculates the percentage a student scored for their test.
For example, if a student got 21/30 for a test, the argument score would be 21 and out_of would be 30 and the value returned by the function would be 70 (because 21/30 is 70%).
Solution:
def percent_calculator(score, out_of):
return (score / out_of) * 100
## Test case:
print(percent_calculator(21, 30))
### OUTPUTS THIS:
70.0
This question primarily targets you on your understanding of functions, arguments and how to use them. The function percent_calculator() takes in two arguments of score and out_of and calculates the percentage a student scored for their test using some simple arithmetical percentage calculation. It is a must that you return the percentage because the question specifically requires you to use return and not a print() statement instead.
Question 11
Write the output for the code below:
def needToCharge(current_battery, low_power_mode):
if current_battery <= 10:
return True
elif current_battery <= 20 and low_power_mode == True:
return False
elif current_battery <= 20 and low_power_mode == False:
return True
else:
return False
print(needToCharge(14, False))
Solution:
Output: True
This question tests functions, function arguments and if statements. In the question, the current_battery parameter is given the value of 14 and the low_power_mode’s value is given as False based on the print() statement. Based on this information, you can step-by-step go through the conditions and come to the conclusion that the condition current_battery <= 20 and low_power_mode == False is True and hence the function needToCharge() should return True, which is then printed out. Hence, the output is True.
Question 12
Complete the code below with the most likely values:
def checkPassword(____):
if ____ == "P@55W04D123":
return True
else:
return False
print(checkPassword(input("Enter your password: ")))
Solution:
Suggested Answer:
def checkPassword(pwd):
if pwd == "P@55W04D123":
return True
else:
return False
print(checkPassword(input("Enter your password: ")))
This question tests more on your skills of deduction and your ability to identify what the argument should be based on the input() method thats passed in as a value. The input() method asks this: Enter your password: . Hence, it is most likely that the argument would be the value of the password that the user enters in. The suggested answer uses the name pwd but you can use any name you want. However, do note that you have to be consistent, so if you put password as the argument name, then you must fill in the same in the if statement.
Conclusion
Thank you to all those who attempted this assignment. We know that it is slightly longer than you would have wished for but we hope that you enjoyed the experience and learned something from this. We tried our best to design this assignment to meet you guys in the middle; the questions were made to be not too easy but not too hard either. All of them cumulatively covered all that you have learnt so far and soon you will learn something called classes, which comes under the umbrella of Object-Oriented Programming. If you wish, you can read up about it further earlier than the next lesson.
What this assignment covered:
- Variables & Data Types
forLoops- Looping by Index
- Looping by Element
ifStatements- Functions
- Function Arguments
returnvsprint