Session 2 - Part 2 Flashcards
What is the difference between a ‘for’ loop and a ‘while’ loop?
‘for’ loops iterate over a list of values for a fixed number of times, while ‘while’ loops continue iterating as long as a certain condition is met.
What caution is given regarding ‘while’ loops?
‘while’ loops can lead to infinite loops if not properly controlled, potentially causing the program to become unresponsive.
How can one escape an infinite loop?
To escape an infinite loop, one can use the Ctrl-C keyboard shortcut (holding down the Ctrl button and pressing C simultaneously) or use the stop button available in coding environments like Colab or Spyder.
What is a while loop in Python? - (2)
A while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true.
It continues to execute the block until the condition becomes false.
While loops are useful when the
number of iterations is not known in advance.
Explain the purpose of the while loop in the provided code snippet - (5).
The while loop continuously executes the block of code inside it as long as the condition a < 5 remains true.
Inside the loop, a is incremented by 1 each time.
The loop stops when a becomes equal to or greater than 5.
After the loop finishes, “Done” is printed.
Note the += syntax here: this is the same as writing a = a + 1.
What is output of this code?
1
2
3
4
5
Done
What is the crucial aspect to ensure in a while loop? - (2)
The crucial aspect is to ensure that the condition being tested will eventually evaluate to True.
If this condition never becomes False, the loop will continue indefinitely.
2.5.1 Quick Exercise
Create a list containing the words apple, banana, cherry and damson. Write a while loop which iterates over the list and prints out the words one at a time. You will need to have the while loop count over the indices and exit when you get to the end of the list.
A conditional statement is one that allows us to make..
The programme can change what it does - (2)
a decision when the program is running.
next depending on what is happening now.
A conditional statement allow the program to execute different blocks of code depending on whether
a condition is true or false.
The conditional statement is expressed in Python using key word
if
The conditional statement is expressed using the keyword if.
In other words,
if is used to start a conditional statement in Python
In Python, ‘if’ keyword can be extended with
else and elif
‘else’ keyword is used in conjunction with
‘if’
‘else’ provides an
alternative block of code to execute when the condition specified with if is false.
If you mentally expand elif to else if, these statements almost translate to
what they would mean if you read them out in natural language.
If you mentally expand elif to else if, these statements almost translate to what they would mean if you read them out in natural language.
e.g. ‘elif’ means
“else if”
‘elif’ allows you to check- (3)
for multiple conditions sequentially after an initial if statement.
If the condition associated with if is false, it checks the condition associated with elif and executes the corresponding block of code if true.
You can have multiple elif statements.
Write a piece of that that:
variable ‘a’ is storing number 10
Create if statement where if a > 10 it prints:
I’m in the first ‘if’ block
a is greater than 10
Create another if statement that if a is 10 then print
I’m in the second ‘if’ block
a is equal to 10
Create another if statement that if a is less than 10 then prints
I’m in the third ‘if’ block
a is less than 10
What is output of code below if a is 10?
What do we see on line 1?
On line 1, we set a variable a to the value 10.
What do we see on line 3? - (2)
On line 3, we ask the question “is a greater than 10”?
This is represented by the conditional if and the comparison a > 10 which returns a bool of False
Explain this code - (4)
a = 10: This line assigns the value 10 to the variable a.
if a > 10:: This line starts the first if statement. It checks if the value of a is greater than 10. If this condition is true, the code block below it is executed. However, since a is equal to 10, this condition is false, and the code block inside this if statement is skipped.
if a == 10:: This line starts the second if statement. It checks if the value of a is equal to 10. Since a is indeed equal to 10, this condition is true, and the code block below it is executed. The statements inside this if block are printed.
if a < 10:: This line starts the third if statement. It checks if the value of a is less than 10. Since a is not less than 10, this condition is false, and the code block inside this if statement is skipped.
‘if’ statement in Python evaluates - (2)
a condition, which can be any expression that results in a boolean value (True or False).
This condition determines whether the subsequent code block associated with the if statement is executed.
The general form of ‘if’ statement in Python - (2)
if CONDITION.
CONDITION can be anything which evaluates to a bool - i.e. True or False.
The general form of if is: if CONDITION. CONDITION can be anything which evaluates to a bool - i.e. True or False. Here we are - (2)
we are comparing numbers
e.g., ‘if a > 10’: this condition evaluates whether value of ‘a’ is greater than 10
What do we find with line 3 of code?
a is not greater than 10.
Lines 4 and 5 of code below are…
We note that lines 4 and 5 are indented:
As with for loops, blocks of statements which are inside an if need to be
indented
Because a is not greater than 10, we do not run…
we do not run lines 4 and 5; instead, we skip straight down to line 7.
On line 7, we check whether a is equal to 10 (a == 10: try it in a console and you will get False). Because this is
False, we jump to the last block…
Since we skip to last block,
We then continue down to line 11 where we check whether a is less than 10. It is! So we go into the block and
execute the code there.
ften we use if statements to check for a ‘special’ condition. For example, - (2)
e normally want our code to do one thing but there is a special case where it should do some other thing.
Here, the else statement becomes useful:
Example image of else statement used in conjunction with if CONDITION
You do not have to have a
else statement (i.e., with if statement or in any loops like for and while)
If you do use an ‘else’ statement then it means:
“if nothing else matched, run this code”.
The else statement, if it exists, must always be the final part of the
if block
What is output of this code? - (2)
Test subject with age 9999 ignored
The total of all the real ages is 155
A final keyword that comes handy in ‘if’ statements is
‘elif’ statements
Mentally expand ‘elif’ to
‘else if’
‘elif’ statement is a neat way of stringing together lots of
statements in a row
Write a code:
storing number ‘66’ into variable called subjectAge
if age of pp is greater than 65 it prints: “Age is too big”
if age of pp is less than 18 then print “Age too small!”
Otherwise, it would print subject age okay!
Explain this code - (4)
This code checks the value of the variable subjectAge.
If subjectAge is greater than 65, it prints “Age too big!”.
If subjectAge is less than 18, it prints “Age too small!”. Otherwise, if neither condition is met, it prints “Subject age okay!”.
The elif statement allows for checking another condition within the same block as the initial if statement.
What is output of this code? - (6)
Output: Age too big!
This code evaluates the value of the variable subjectAge, which is initially set to 66.
Since subjectAge is greater than 65, it prints “Age too big!”.
The elif statement checks for additional conditions, but they are not met because subjectAge does not fall below 18.
Hence, it doesn’t print “Age too small!”.
Finally, the else block is bypassed, and the code prints “Subject age okay!”.
The combination of if, elif and else provides us with
the flexibility to make decisions and have our code adapt to the data.
You can nest multiple ‘if’ statements nested inside each other to produce
more complex conditions
Write a code that
variable subjectAge stores number 19
numberofFunctional Eyes variable is equal to 1
Code checks if subject age is greater than 18 years old (YNiC , only allowed adults over ages of 18) and has 2 functional eyes then prints : Subject is valid
Else print right age, wrong number of eyes
Otherwise, print under age, did not check eyes
What would be output?
Explain the code, what would be output and why? - (11)
In this code, there are nested if statements. T
he outer if statement checks if the subjectAge is greater than 18.
If this condition is true, it then checks the numberOfFunctionalEyes.
If numberOfFunctionalEyes is equal to 2, it prints “Subject is valid”.
If numberOfFunctionalEyes is not equal to 2, it prints “Right age, wrong number of eyes”.
If the subjectAge is not greater than 18, it prints “Under age, didn’t check the eyes”.
Given subjectAge = 19 and numberOfFunctionalEyes = 1, here’s what happens:
The first condition subjectAge > 18 is true, so it proceeds to the nested if statement.
However, the second condition numberOfFunctionalEyes == 2 is false since numberOfFunctionalEyes is 1.
Therefore, it executes the else block of the nested if statement.
Hence, the output would be “Right age, wrong number of eyes”.
In this code example, be careful to follow
the indentation carefully in this example - there are two independent if blocks here. One of them (lines 5-8) will only occur if the condition on line 4 is True.
In our examples so far, the conditions that we have used have been
comparisons (greater than, equal to, less than).
if statements can evaluate any expression that results in
boolean value (True or False).
if statements can evaluate any expression that results in a boolean value (True or False). This means you can use
not just simple comparisons (e.g., greater than, equal to, less than).) but also complex statements than just checking the value of a variable
In our examples so far, the conditions that we have used have been comparisons (greater than, equal to, less than).
As noted above, if statements work with any statement which can evaluate to a bool value (True or False).
You can also write out more complex statements than just checking the value of a variable.
e.g,.
such as using a the ‘modulus’ operator % in if statement and using string operations such as ‘startswith’ and ‘endswith’
Remember:
Modulus operator ‘%’ returns the
‘remainder’ when you divide one thing by another thing.
Write a code that
stores number 4 into variable ‘a’
Checks if a is odd
Explain this code - (4):
a = 4: This line assigns the value 4 to the variable a.
if (a % 2) == 1:: This line sets up a conditional check. Inside the parentheses, (a % 2) computes the remainder when a is divided by 2, effectively determining whether a is even or odd.
(a % 2) will result in 0 if a is even and 1 if a is odd.
if the condition (a % 2) == 1 evaluates to True (which is the case when a is odd), the program prints “a is odd”.
However, in this case, the condition evaluates to False since a is even.
What is output?- (2)
Since the condition (a % 2) == 1 evaluates to False when a is 4 (because 4 % 2 equals 0, not 1), the print(“a is odd”) statement will not be executed.
Therefore, there will be no output for this code when a is assigned the value 4.
How do we compare strings in Python code?
we can compare strings using equality operator ==:
Write a code that compares strings to see if “Hello” and “Hello” are the same and if “Hello” and “Hello World” are the same that is stored in variables a, b, c
What would be output of this code?
Explain this code and why it produces that output? - (4)
This code initializes three variables a, b, and c with string values. Then it performs comparisons using the equality operator == to check if the strings are the same.
a = “Hello”: Assigns the string “Hello” to the variable a.
b = “Hello”: Assigns the string “Hello” to the variable b.
c = “Hello World”: Assigns the string “Hello World” to the variable c.
if a == b:: Compares the strings stored in variables a and b. Since both a and b contain the same string “Hello”, this condition evaluates to True. Therefore, it prints “a and b are the same”.
if a == c:: Compares the strings stored in variables a and c. However, a contains “Hello” and c contains “Hello World”, so these strings are different. This condition evaluates to False. Therefore, it prints “a and c are different”.
We can also perform advanced string operations such as checking whether one string starts with another using the
‘startswith’ member function
Write a code that:
stores
variable a into “hello”
variable b into “world”
variable c with “hello world”
Check if c starts with a and prints a starts with a if not then say it does not
Check if c starts with b and prints c starts with b or if not then say it does not
What is the output of this code?
Explain the output of the code and justify why it produces that output. - (4)
This code snippet initializes three string variables: a with the value “Hello”, b with the value “World”, and c with the value “Hello World”. Then, it utilizes the startswith method to check if the string c starts with the substrings represented by variables a and b.
a = “Hello”: Assigns the string “Hello” to the variable a.
b = “World”: Assigns the string “World” to the variable b.
c = “Hello World”: Assigns the string “Hello World” to the variable c.
if c.startswith(a):: Checks whether the string c starts with the substring represented by variable a (“Hello”). Since the string c does indeed start with “Hello”, this condition evaluates to True, and “c starts with a” will be printed.
if c.startswith(b):: Checks whether the string c starts with the substring represented by variable b (“World”). Since the string c does not start with “World”, this condition evaluates to False, and “c does not start with b” will be printed.
There is a corresponding counterpart to ‘startswith’ member function there is also a
‘endswith’ that is another advanced string operator ,member function, that checks whether a string ends with a specific substring.
Example of code using endswithmember function
What is output of this code?
Whats one useful operation that works with strings, lists, tuples and dictionaries?
‘in’ keyword
Whats ‘in’ keyword in Python?
checks whether one thing is in the object being checked.
What is output of the code?
Explain the execution of the code and provide reasoning for why a certain condition fails to find b in the dictionary e.
a = “Hello”: Assigns the string “Hello” to the variable a.
b = “World”: Assigns the string “World” to the variable b.
c = “A sentence with Hello in it”: Assigns the string “A sentence with Hello in it” to the variable c.
d = [‘A’, ‘list’, ‘with’, ‘Hello’, ‘in’, ‘it’]: Assigns a list containing several strings including “Hello” to the variable d.
e = {‘Hello’: 1, ‘Something’: ‘World’}: Assigns a dictionary containing key-value pairs, where “Hello” is a key mapped to the value 1, and “Something” is a key mapped to the string “World”, to the variable e.
if a in c:: Checks if the substring “Hello” (stored in variable a) is present in the string c. Since “Hello” is indeed part of the string c, the condition evaluates to True, and “String c has contents of a in it” is printed.
if a in d:: Checks if the substring “Hello” is present in the list d. As “Hello” is an element of the list d, the condition evaluates to True, and “List d has contents of a in it” is printed.
if a in e:: Checks if the substring “Hello” is present as a key in the dictionary e. Since “Hello” is a key in the dictionary e, the condition evaluates to True, and “Dict e has contents of a in it” is printed.
if b in c:: Checks if the substring “World” (stored in variable b) is present in the string c. Since “World” is not part of the string c, this condition evaluates to False, and no message is printed.
if b in d:: Checks if the substring “World” is present in the list d. As “World” is not an element of the list d, this condition evaluates to False, and no message is printed.
if b in e:: Checks if the substring “World” is present as a key in the dictionary e. This condition fails to find “World” in the dictionary e because “World” is stored as a value, not a key. In e, “Hello” is a key, not “World”. Therefore, this condition evaluates to False, and no message is printed.
If we want to examine the values, we can simply ask the dictionary for a list of its values and check that instead . Like this:
The ‘not, ‘and’ and ‘or keywords modifies
the boolean to ask for the opposite thing.
The ‘not operator returns..
It returns True if the expression is False, and False if the expression is True.
The ‘and keyword - (2)
combines two expressions.
It returns True if both expressions are True, otherwise, it returns False
The ‘or keyword - (2)
The or keyword combines two expressions.
It returns True if at least one of the expressions is True, otherwise, it returns False.
we can write conditions that combine multiple requirements using
‘and’ and ‘or’ keywords in Python
What is the output?
You can chain together as many of ‘and and ‘or’ operators but
Be careful about which conditions will be combined in which order.
Parentheses can be used when writing multiple conditions to clarify to the
reader (esp writing multiple conditions using ‘and’, ‘or and ‘not’ in Python) even if if Python does not need them
Write a code that stores 5,10,15, 20 to variable a,b,c, and d respectively
Then check if a < 10 or b >10 and c< 25 or d < 25 and prints At least one of a/b are < 10 and at least one of c/d are < 25
Explain what the code does? - (4)
a = 5, b = 10, c = 15, and d = 20 are assigned initial values.
The if statement checks two conditions:
(a < 10) or (b < 10) checks if either a or b is less than 10.
(c < 25) or (d < 25) checks if either c or d is less than 25.
If both conditions are met, the message “At least one of a/b are < 10 and at least one of c/d are < 25” is printed
In this specific case, since a = 5 (which is less than 10) and d = 20 (which is less than 25), both conditions are met, so the message will be printed.
What is output of this code?
You can use single-character shorthand for
‘and’ , ‘or’, ‘not’ operators to achieve the same functionality
using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality
e.g.,
or =
|
using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality
e.g.,
and =
&
using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality
e.g.,
not =
~
Example code of using using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality
We can also combine conditionals with
loops
What is the output?