ItP2 - Conditionals Flashcards

1
Q

A conditional statement is one that allows us to make..

The programme can change what it does - (2)

A

a decision when the program is running.

next depending on what is happening now.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

A conditional statement allow the program to execute different blocks of code depending on whether

A

a condition is true or false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

The conditional statement is expressed in Python using key word

A

if

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

The conditional statement is expressed using the keyword if.

In other words,

A

if is used to start a conditional statement in Python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

In Python, ‘if’ keyword can be extended with

A

else and elif

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

‘else’ keyword is used in conjunction with

A

‘if’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

‘else’ provides an

A

alternative block of code to execute when the condition specified with if is false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

If you mentally expand elif to else if, these statements almost translate to

A

what they would mean if you read them out in natural language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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

A

“else if”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

‘elif’ allows you to check- (3)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is output of code below if a is 10?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What do we see on line 1?

A

On line 1, we set a variable a to the value 10.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What do we see on line 3? - (2)

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Explain this code - (4)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

‘if’ statement in Python evaluates - (2)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

The general form of ‘if’ statement in Python - (2)

A

if CONDITION.

CONDITION can be anything which evaluates to a bool - i.e. True or False.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

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)

A

we are comparing numbers

e.g., ‘if a > 10’: this condition evaluates whether value of ‘a’ is greater than 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What do we find with line 3 of code?

A

a is not greater than 10.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Lines 4 and 5 of code below are…

A

We note that lines 4 and 5 are indented:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

As with for loops, blocks of statements which are inside an if need to be

A

indented

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Because a is not greater than 10, we do not run…

A

we do not run lines 4 and 5; instead, we skip straight down to line 7.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

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

A

False, we jump to the last block…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

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

A

execute the code there.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

ften we use if statements to check for a ‘special’ condition. For example, - (2)

A

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:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Example image of else statement used in conjunction with if CONDITION

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

You do not have to have a

A

else statement (i.e., with if statement or in any loops like for and while)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

If you do use an ‘else’ statement then it means:

A

“if nothing else matched, run this code”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

The else statement, if it exists, must always be the final part of the

A

if block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is output of this code? - (2)

A

Test subject with age 9999 ignored

The total of all the real ages is 155

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

A final keyword that comes handy in ‘if’ statements is

A

‘elif’ statements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Mentally expand ‘elif’ to

A

‘else if’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

‘elif’ statement is a neat way of stringing together lots of

A

statements in a row

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

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!

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Explain this code - (4)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is output of this code? - (6)

A

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!”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

The combination of if, elif and else provides us with

A

the flexibility to make decisions and have our code adapt to the data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

You can nest multiple ‘if’ statements nested inside each other to produce

A

more complex conditions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

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

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What would be output?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Explain the code, what would be output and why? - (11)

A

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”.

42
Q

In this code example, be careful to follow

A

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.

43
Q

In our examples so far, the conditions that we have used have been

A

comparisons (greater than, equal to, less than).

44
Q

if statements can evaluate any expression that results in

A

boolean value (True or False).

45
Q

if statements can evaluate any expression that results in a boolean value (True or False). This means you can use

A

not just simple comparisons (e.g., greater than, equal to, less than).) but also complex statements than just checking the value of a variable

46
Q

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,.

A

such as using a the ‘modulus’ operator % in if statement and using string operations such as ‘startswith’ and ‘endswith’

47
Q

Remember:

Modulus operator ‘%’ returns the

A

‘remainder’ when you divide one thing by another thing.

48
Q

Write a code that

stores number 4 into variable ‘a’

Checks if a is odd

A
49
Q

Explain this code - (4):

A

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.

50
Q

What is output?- (2)

A

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.

51
Q

How do we compare strings in Python code?

A

we can compare strings using equality operator ==:

52
Q

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

A
53
Q

What would be output of this code?

A
54
Q

Explain this code and why it produces that output? - (4)

A

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”.

55
Q

We can also perform advanced string operations such as checking whether one string starts with another using the

A

‘startswith’ member function

56
Q

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

A
57
Q

What is the output of this code?

A
58
Q

Explain the output of the code and justify why it produces that output. - (4)

A

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.

59
Q

There is a corresponding counterpart to ‘startswith’ member function there is also a

A

‘endswith’ that is another advanced string operator ,member function, that checks whether a string ends with a specific substring.

60
Q

Example of code using endswithmember function

A
61
Q

What is output of this code?

A
62
Q

Whats one useful operation that works with strings, lists, tuples and dictionaries?

A

‘in’ keyword

63
Q

Whats ‘in’ keyword in Python?

A

checks whether one thing is in the object being checked.

64
Q

What is output of the code?

A
65
Q

Explain the execution of the code and provide reasoning for why a certain condition fails to find b in the dictionary e.

A

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.

66
Q

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:

A
67
Q

The ‘not, ‘and’ and ‘or keywords modifies

A

the boolean to ask for the opposite thing.

68
Q

The ‘not operator returns..

A

It returns True if the expression is False, and False if the expression is True.

69
Q

The ‘and keyword - (2)

A

combines two expressions.

It returns True if both expressions are True, otherwise, it returns False

70
Q

The ‘or keyword - (2)

A

The or keyword combines two expressions.

It returns True if at least one of the expressions is True, otherwise, it returns False.

71
Q

we can write conditions that combine multiple requirements using

A

‘and’ and ‘or’ keywords in Python

72
Q

What is the output?

A
73
Q

You can chain together as many of ‘and and ‘or’ operators but

A

Be careful about which conditions will be combined in which order.

74
Q

Parentheses can be used when writing multiple conditions to clarify to the

A

reader (esp writing multiple conditions using ‘and’, ‘or and ‘not’ in Python) even if if Python does not need them

75
Q

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

A
76
Q

Explain what the code does? - (4)

A

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.

77
Q

What is output of this code?

A
78
Q

You can use single-character shorthand for

A

‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

79
Q

using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

e.g.,

or =

A

|

80
Q

using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

e.g.,

and =

A

&

81
Q

using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

e.g.,

not =

A

~

82
Q

Example code of using using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

A
83
Q

We can also combine conditionals with

A

loops

84
Q

What is the output?

A
85
Q

Example output of this code:

A
86
Q

Explain this code - (7):

A

We prompt the user to input two numbers: lowerNumber and higherNumber. These will determine the range of numbers to count from and to.

We check if higherNumber is less than lowerNumber using the if statement. If it is, it means we need to count down from lowerNumber to higherNumber

Inside the if block, we use a for loop to iterate over the range of numbers from lowerNumber to higherNumber - 1 in reverse order (i.e., counting down). We specify -1 as the step size to decrement the numbers (-1 after highNumber-1)

Within the loop, we print each number.

If the condition in the if statement is not met, meaning higherNumber is greater than or equal to lowerNumber, we execute the else block.

Inside the else block, we use another for loop to iterate over the range of numbers from lowerNumber to higherNumber + 1 (inclusive). The default step size is 1, so we don’t need to specify it explicitly.

Within this loop, we also print each number.

87
Q

Create a dictionary (use whichever variable name you like) which maps strings to integers as follows:

Print out the whole dictionary, then print out the list of keys (i.e. person names). Finally, print out just the entry for personC.

A
88
Q

Use a for loop to print every number from 1 to 20 inclusive, but don’t print when the number is 13.

A
89
Q

use a for loop to print numbers from 1 to 20 inclusive, but this time use a combination of formatting, if statements (think about how you can test if a number is evenly divisible by 5) and the end argument to print to print five numbers per line and line everything up neatly:

Your output should look like this:

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

16 17 18 19 20 - (4)

A

for num in range(1, 21):: This line initializes a for loop that iterates over numbers from 1 to 20 (inclusive). The variable num takes on each of these values in sequence.

if num % 5 == 0:: This if statement checks whether the current value of num is divisible by 5. The % operator gives the remainder when num is divided by 5. If the remainder is 0, it means num is divisible by 5.

print(f’{num:2d}’): If num is divisible by 5 (i.e., if the condition in the if statement is true), this line prints the value of num with a minimum width of 2 characters. It adds leading spaces if necessary to ensure that the number occupies at least 2 characters. Additionally, it adds a newline character at the end, so the next print statement will start on a new line.

print(f’{num:2d}’, end=” “): If num is not divisible by 5 (i.e., the condition in the if statement is false), this line prints the value of num with a minimum width of 2 characters, similarly to the previous line. However, it does not add a newline character at the end. Instead, it ends the print statement with a space (“ “), meaning that the next thing to be printed will appear on the same line.

90
Q

Set up a list containing the numbers 5, 10, 15, 20, 25. Print out the list, then randomise the order of the elements in the list (don’t forget to import the right routine). Print the list again.

A
91
Q

Think of the data structures (list, dictionary or tuple) which would be most appropriate for storing the following information when coding in python. Explain your choices and, if using a dictionary, which item would be the key and which the value:

Words to be used as stimuli for an experiment

A

a.

A list of strings
# For example: [‘my’, ‘list’, ‘of’, ‘words’]

92
Q

Think of the data structures (list, dictionary or tuple) which would be most appropriate for storing the following information when coding in python. Explain your choices and, if using a dictionary, which item would be the key and which the value:

The date of birth for each participant in an experiment (assume that participants have a unique identifier) - (3)

A

A dictionary with the participant id as the key and
# date of birth as the values
# For example: {‘P1’: ‘1980-01-01’, ‘P2’: ‘1975-12-22’}

93
Q

Think of the data structures (list, dictionary or tuple) which would be most appropriate for storing the following information when coding in python. Explain your choices and, if using a dictionary, which item would be the key and which the value:

Percentage correct scores for an experiment - (2)

A

A list of scores
# For example: [77, 56, 75, 51, 62, 61]

94
Q

Think of the data structures (list, dictionary or tuple) which would be most appropriate for storing the following information when coding in python. Explain your choices and, if using a dictionary, which item would be the key and which the value:

Advanced: For the next question you may wish to think about more complex options, for instance a list containing dictionaries or a dictionary in which the items are lists. Make sure you think about the difference between the two

A set of five scores for each participant in a study - (4)

A

A dictionary with the participant id as the key and
# a list of scores as the values
# For example: {‘P1’: [9, 8, 5, 5, 7],
# ‘P2’: [6, 1, 2, 5, 4]}

95
Q

Question 1: String Formatting Issue

What is problem with code?

A

Use {} not [] to embed variables in f-strings

96
Q

Question 2: Dictionary Key Error

The above code snippet attempts to print the location of the person. Identify the error and suggest a quick fix. In addition, suggest a general way to handle missing keys in a dictionary so that the code does not produce an error. - (3)

A

There is no key called ‘location’.

Probably ‘city’ is what you wanted.

Use the “get” function to try to access dict values by keys and return a None value rather than an error if the key is missing.

97
Q

Question 3: While Loop Condition Error

Explain why the loop might not work as expected. How would you fix it to count down from 10 to 1. - (3)

A

The loop will never stop because the count is always <=10. There are lots of ways of fixing it. For example…

1: Add in an ‘and’ statement to the while loop (while (count<=10 and count >=1):

2: Just use a for loop with a range statement (for count in range(10,0,-1):

98
Q

Question 4: Conditional Statement Syntax Error

Identify the syntax error in the conditional statements.

A

The last ‘else’ is missing a colon

else:

99
Q

Question 5: Incorrect Use of the ‘is’ Operator

Explain why the is operator might not be appropriate in this context and suggest a correct approach. - (2)

A

‘is’ is usually used for lists or dictionaries or strings. For numbers, just use == instead

if (x>3) and (y==10):

100
Q

Question 6: While loop and conditional

Describe the purpose of the else clause in this while loop and under what circumstances it is executed. - (2)

A

It is evaluated when the countdown gets to zero.

It tells the program what to do when the countdown is not 3,2,1…

101
Q

Question 7: Rounding and mixing Data Types in F-String

How would you make this f-print statement round to the nearest integer? - (2)

A

Use the formatting string :something.0f following ‘score’ inside the first {}. The something part says how many figures to have in front of the decimal place, the ‘0’ part says to have nothing after the decimal place. For example

print(f”Your rounded score is {score:2.0f}, which is a {result}”)