Lesson 2 Assignment Solution
This page contains the solution and a detailed explanation to the Lesson 2 Assignment.
Question 1
Q1) Find the output for the following code:
persons = ["John", "David", "Thomas", "Pierce", "Ronson"]
for person in persons:
print(person)
Solution:
John
David
Thomas
Pierce
Ronson
The important thing to identify in this question is that the code uses looping by element. The for loop loops through the persons list one-by-one and stores the value of each element in the person variable. The print function prints the value of the person variable. There are 5 iterations run as there are 5 elements in the list persons.
Question 2
Q2) Complete the code below:
for i in ___(___, ____):
print(i)
# Gives the following output:
1
2
3
.
.
.
70
# END OF OUTPUT
Solution:
for i in range(1, 71):
print(i)
The important thing to identify here is that the code uses looping by index using the range() function. The range() function takes in two parameters to create a range for the for loop to loop through; the first parameter is the starting inclusive number and the second parameter is the ending exclusive number. Hence, the function range(1, 71) is made so that the range becomes 1-70. The for loop loops through the range and stores the value of each index in the i variable. The print function prints the value of the i variable. There are 70 iterations run as there are 70 numbers in the range.
Question 3
Q3) Initalise any 4 variables that each have the data types of String, Integers, Floats and Lists respectively.
Solution:
myString = "Hello"
myInt = 100
myFloat = 2.5
myList = [1, 2, 3, 4, 5]
This question was the easiest out of all three of them. The code is very simple and the solution is very straightforward. The code is initialising the variables with the data types of String, Integers, Floats and Lists respectively.
Do recall that a string is any piece of text that is wrapped with quotation marks (") like so: "This is a string 2892". (numbers inside a string are not considered integers as they are considered part of the text). A integer is basically a whole number that does not have a decimal point (.). A float is a number that has a decimal point (.). A list is a collection of elements that are separated by commas (,).
Unlike the other two questions, the answers to this question can vary as you could’ve initialised any of the variables with any values of any data types.
Conclusion
The above three questions tested your understanding of the core concepts that we covered in Lesson 2 which are:
- Variables and Data Types
- Control Flow -
forloops