Session 2 - Part 1 Flashcards

1
Q

What is the term used to describe controlling text output and making it look nice in Python?

A

String formatting is the process of controlling text output and making it visually appealing in Python.

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

What is one way to print combinations of text and data in Python before the introduction of f-strings? - (3)

A

Joining them together with commas,

for example:

numberOfSubjects = 1022

print(“There were “, numberOfSubjects, “ participants”).

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

What are some drawbacks of using commas to combine text and data for output in Python? - (2)

A

Commas can be annoying and imprecise especially when trying to format output neatly

E.g., Unable to limit number of decimal places or centre things on screen

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

There were 1022 participants

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

What would be output of this code?

A

2.0 / 3.0 is roughly: 0.6666666666666666

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

Example image of:

Drawback of using commas to combine text and data for output in Python - unable to limit number of deciaml places example

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

What is a modern and preferred method for combining data and strings for output formatting in Python, beside using commas?

A

Using f-strings, which provide a more elegant and concise way to format output by embedding variables directly into strings.

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

What does f-strings stand for in Python?

A

An f-string, short for “formatted string literal,”

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

How do you create an f-string in Python?

A

Prefix the string with the letter ‘f’, (just before te quote marks) then use curly braces {} to enclose the variable names you want to include in the string.

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

What happens when an f-string is evaluated in Python?

A

When an f-string is evaluated, Python replaces the expressions enclosed within curly braces {} with their corresponding values at runtime, resulting in a formatted string.

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

Explain this code - (4)

A

the variable my_variable is assigned a value of 100.

Then, an f-string named foo is created, where the value of my_variable (100) is embedded within the string using curly braces {} .

When foo is printed, it will display the string “My variable contains the value 100”.

The ‘f’ prefix before the string indicates that it is an f-string, and Python replaces the expression {my_variable} within the string with the value of the variable during runtime.

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

What is the output of this code?

A

My variable contains the value 100

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

How can you include multiple variables in an f-string in Python?

A

Multiple variables can be included in an f-string by separating them with commas inside the curly braces {}.

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

Example of adding multiple variables in f-string in Python

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

What will be the output of this code?

A

My vars are Test, 15.0, 10

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

The way in which the variables are output in f-string depends on the

A

data type

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

Example

The way in which the variables are output in f-string depends on the data type

A

the float in this case is shown with a .0 on the end whilst the int is not.

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

Explain this code - (4):

A

three variables a, b, and c are assigned values.

a is assigned 10 (integer)
b is assigned 15.0 (float)
c is assigned ‘True’ (boolean value)

An f-string named mystr is then created, which includes these variables within curly braces {} inside the string.

When mystr is printed, it will display the formatted string “My vars are Test, 15.0, 10”, with the variables c, b, and a inserted into the string in the order specified

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

What does the term “formatting with f-strings” refer to in Python? - (2)

A

“Formatting with f-strings” in Python refers to using f-strings to manipulate the appearance of output, such as justifying text or formatting data, by adding specific formatting options after the variable name.

Formatting options always have a colon at the end of the variable name and then some numbers or characters.

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

What are two ways in which we want to format strings in f-string? - (2)

A
  1. Justifying text (for example, by making sure it takes up a certain amount of space for each variable). This is useful when we want to print tables of data
  2. Format the data itself - for example limiting the number of decimal place in a float or adding zeros to the start of an integer
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How can you force a value to occupy a certain amount of space using f-strings in Python? -

A

By adding a colon followed by the desired width after the variable name inside curly braces {} in the f-string.

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

What would be output of this code?

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

Q: What does the following f-string do?

myvar = ‘Test’
print(f’==={myvar}===’)

A

This f-string prints the value of the variable myvar surrounded by equals signs, resulting in the output ===Test===.

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

Q: Explain the purpose of the following f-string

myvar = ‘Test’
print(f’==={myvar:20}===’): - (3)

A

The output ===Test === consists of the string “===” at the beginning and end, with the variable myvar (“Test”) occupying 20 spaces.

Output is:
===Test ===

Since the word “Test” has only 4 characters, it is followed by 16 spaces to fill the specified width.

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

How to change allignment of variable in f-string?

A

You can change the alignment by adding a character before the width number inside curly braces {} in the f-string:

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

What is the default alignment behavior of a string in f-strings?

A

By default, strings are left-centered in the space provided within an f-string.

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

What is left-alignment of string in f-string?

A

<: left aligned (the default so does not usually need to be specified)

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

What is right-alignment of string in f-string?

A

> : right aligned

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

What is centred-alignment of string in f-string?

A

^: centred

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

What is the output of the following f-string?

A

The output would be ===TestText ===, with the string “TestText” occupying 8 characters and the remaining 12 spaces filled with whitespace to the right, resulting in left alignment of string “TestText” within the specified width.

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

What is the output of the following f-string?

A

The output would be
‘=== TestText===’, with the string “TestText” occupying 8 characters and the remaining 12 spaces filled with whitespace to the left, resulting in right alignment of string “TestText” within the specified width.

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

What is output of the following f-string? - (2)

A

The output would be:
=== TestText ===

with the string “TestText” occupying 8 characters and evenly distributed whitespace of 12 spaces on each side, resulting in center alignment of string “TestText” within the specified width.

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

How does f-string handle space expansion when the inserted string is longer than the specified width?

A

F-strings expand the space to fit the entire string when it is longer than the specified width

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

What is the output of this code? - (3)

A

variable myvar containing the string ‘TestTextVeryLong’ is inserted into the f-string with a specified width of 5 characters

Despite the specified width being only 5 characters, Python expands the space to accommodate the entire string when necessary

So output becomes: 
===TestTextVeryLong===
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the output of this code? - (2)

A

534, the original content was 3 characters long, and the f-string expanded the width to 7 characters by adding 2 spaces on each side to center the content.

=== 534 ===

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

Print your own name, centered in space surrounded by stars (**) like this:

** Alex **

Using f-strings

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

What is the output of the code print(f’==={myvar:^7}===’) where myvar = 500000090? - (2)

A

The output is ===500000090===, which shows the large number 500000090 centered within a 7-character space.

Since the number itself is longer than the specified width, the f-string expands the space to accommodate the entire number, ensuring no truncation occurs.

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

What is the purpose of zero-padding integers in Python (using f-strings with numbers)? - (3)

A

Zero-padding integers involves adding leading zeros to the integer to ensure it fills a specific width.

This adding 0s before the number to fill the space rather than spaces

This is often useful when naming files to make sure that they sort correctly (e.g. if using participant numbers).

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

What is the output of the code print(f’{mynum:03}’) where mynum = 5? - (2)

A

The output is 005, which demonstrates the integer 5 zero-padded to fill a width of 3 characters

Since 5 is 1 character, it adds 3 zeros before to fill the width of 3 characters

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

How can you control the number of decimal places in floating point numbers using f-strings?

A

You can control the number of decimal places in floating point numbers by specifying the desired number of digits after the decimal point in the format specifier, such as {myval:10.4f}

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

What is the default alignment behavior of a numbers (integers, floats) in f-strings?

A

By default, strings are right-centered in the space provided within an f-string.

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

What is the output of
print(f’=={myval:10.4f}==’)
where myval = 10.219? - (3)

A

The output is
== 10.2190==

This displays the floating-point number 10.219 with a total width of 10 characters, including three leading spaces followed by the number with four digits after the decimal point.

The zero at the end is added to fill the specified precision of four decimal places.

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

What is the output of print(f’=={myval:7.4f}==’)

where myval = 10.219? - (2)

A

The output is ==10.2190==. This displays the floating-point number 10.219 with a total width of 7 characters, including the number itself with four digits after the decimal point.

Since the specified width is sufficient to accommodate the entire number, no leading or trailing spaces are added.

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

What is the output of print(f’=={myval:7.2f}==’)

where myval = 10.219? - (3)

A

The output is == 10.22==. This result is achieved because the formatting specifier 7.2f is used, indicating that the number should be displayed with a total width of 7 characters, including two digits after the decimal point.

Python rounds the number 10.219 to 10.22 to meet the specified formatting requirements - width and precision of decimal places

Additionally, two leading spaces are added to ensure that the number is properly aligned within the specified width.

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

What happens if you ask for fewer decimal places in f-strings in Python?

A

Python rounds the numbers to the specified number of decimal places

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

What is the output of the code print(f’==={myvar:10}===’) where myvar = 5? - (2)

A

The output is
=== 5===

This indicates that the output is right-aligned, with 9 spaces added before the number 5 to achieve a total width of 10 characters.

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

We can also use … in f-strings which is useful for dealing with large or small nubmers (e.g., femot-Tesla in MEG)

A

scientific notation

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

What character is used for scientific notation in f-strings?

A

The e formatting character is used for scientific notation in f-strings.

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

How is scientific notation represented using the “e” formatting character? - (2)

A

Scientific notation using the “e” formatting character is expressed as a number multiplied by 10 raised to a power, denoted by “e”.

For example, “1.0e-6” represents 1.0 × 10^(-6).

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

What is the output of the code print(f’==={myval:e}===’)

where myval = 0.000001?

A

The output is “===1.000000e-06===”, which represents the number 0.000001 in scientific notation.

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

How can you control the number of decimal places in scientific notation when using the “e” formatting character in f-string? - (2)

A

You can control the number of decimal places in scientific notation by specifying the desired precision after the colon, similar to using the “f” formatting character.

For example, print(f’==={myval:.1e}===’) will display the number in scientific notation with one decimal place.

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

What happens if the provided number of spaces is not sufficient for the number when using the “e” formatting character?

A

If the provided number of spaces is not sufficient for the number when using the “e” formatting character, extra spaces will be added to accommodate the full representation of the number.

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

What is the purpose of specifying “.1e” in the code print(f’==={myval:.1e}===’)?

A

Specifying “.1e” limits the number of decimal places to one in the scientific notation representation of the number.

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

What is the output of the code print(f’==={myval:.1e}===’) where myval = 0.000001? - (3)

A

The output is ===1.0e-06===.

This notation represents the number 0.000001 in scientific format, where “1.0” denotes the main numerical value, “e” signifies “times ten to the power of”, and “-06” indicates the exponent, signifying that the number is multiplied by 10 to the power of -6.

The “.1” specifier in the f-string limits the number of decimal places to one.

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

What is the output of the code print(f’==={myval:10.1e}===’) where myval = 0.000001? - (4)

A

he total width specified is 10 characters.

The scientific notation 1.0e-06 itself takes up 7 characters (1.0e-06).

To ensure right alignment within the total width of 10 characters, three additional spaces are added before the number.

Therefore, there are three spaces before the number 1.0e-06 to make up the total width of 10 characters.

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

What does ‘d’ mean in f-string formatting?

A

In f-string formatting, ‘d’ is used to specify that the value should be formatted as an integer.

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

What is the purpose of the f-string expression {part_id:03d} in the code - (2)

print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)?

A

The expression {part_id:03d} formats the integer value part_id with leading zeros to make it three characters wide.

For example, if part_id is 1, it will be formatted as ‘P001’.

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

What is the purpose of the f-string expression {num_trials:3d} in the code print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)? - (2)

A

The expression {num_trials:3d} right-aligns the integer value num_trials within a minimum width of three characters.

If the integer has fewer than three digits, it will be padded with spaces on the left.

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

What is the purpose of the f-string expression {rt:8.3f} in the code print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)? - (2)

A

The expression {rt:8.3f} formats the floating-point number rt with a total width of 8 characters, including three decimal places.

It ensures that the number is right-aligned within the specified width.

60
Q

What is output of the code?

A

P001 | 100 | 100.210 |

61
Q

Fix this code so it outputs like this:

P001 | 100 | 100.210 |
| P002 | 150 | 121.542 |
| P003 | 88 | 99.122 |
| P004 | 120 | 145.330 |

A
62
Q

Explain this code - (2)

A

This code creates a table displaying participant information using three lists: part_ids for participant IDs, trial_counts for the number of trials each participant did, and rts for their reaction times.

It iterates over the indices of the part_ids list using a for loop. Within the loop, it prints a formatted table line for each participant, where their ID is zero-padded to three digits, the trial count is right-aligned with three spaces, and the reaction time is displayed with three decimal places, using f-strings for formatting.

63
Q

What is the purpose of the input function in Python? - (3)

A

The input function in Python is used to request information from the user.

It takes a string argument, known as the “prompt,” which is displayed to the user, prompting them to input some data.

Once the user provides input, the input function returns the data entered by the user.

64
Q

What is the data type of the value returned by the input function? - (2)

A

the input() function returns a string data type.

This means that regardless of what the user inputs (whether it’s numbers, letters, or symbols), it will be treated as a string unless explicitly converted to another data type using functions like int(), float(), etc.

65
Q

What is the output of the following code snippet? - (3)

data = input(‘Enter a word: ‘)
print(type(data))
print(data)

A

The output of the code snippet depends on the user input.

When prompted to enter a word, if the user enters “zebra,”

the output will be:
<class ‘str’>
zebra

66
Q

How can you convert user input, which is initially a string, into an integer in Python?

A

ou can convert user input from a string to an integer using the int() function.

67
Q

What is output? if user input is 10

A

Enter a number: 10
‘<class ‘str’>’
10
‘<class ‘int’>’
10
20

68
Q

Explain this code if user input is 10 - (2)

A

The user input is initially of type string (str), but after casting it to an integer using int(), its type becomes int.

When the value is multiplied by 2, the result is 20

69
Q

Exercise

Write a script that prompts user for a name and then a number

Print out name, number and number doubled (times by 2)

xxxxx= input(‘Enter a name:’)
print() # Print the thing you just entered

yyyyyyy = input(‘Enter a number: ‘)

yyyy = int(number)
print(type(……))
print(……)
print(……) # Print the number doubled.

A

name = input(‘Enter a name:’)
print(name) # Print the thing you just entered

number = input(‘Enter a number: ‘)

data = int(number)

print(type(data))

print(‘This is your original number: ‘, data)

print(‘This is your number doubled:’,data*2) # Print the number doubled.

70
Q

What is the output of this code if user input is Gita and number input is 2

A

Enter a name:Gita
Gita
Enter a number: 2
<class ‘int’>
This is your original number: 2
This is your number doubled: 4

71
Q

Write a script which inputs two numbers. The first should be a number to count from, the second a number to count to. Once the user has input the numbers, you should print - using a loop - all of the numbers between the starting and ending number (inclusive; think carefully about this), one per line.

An example run of the program might look like this:

Starting number: 5

Ending number: 10

5
6
7
8
9
10

A
72
Q

What does the following Python code do? - (3)

first_number = int(input(‘Enter a number to start: ‘))
second_number = int(input(‘Enter a number to end: ‘))

for x in range(first_number, second_number + 1):
print(x)

A

The code begins by prompting the user to input two numbers, which are then converted to integers using the int() function.
It then uses a for loop to iterate over the range from first_number to second_number + 1.

The +1 ensures that the range includes the second_number.
Inside the loop, each number in the range is printed on a separate line.

This allows the loop to print all numbers from first_number to second_number, inclusive.

73
Q

How are lists defined in Python? - (2)

A

Lists are defined with square brackets,

for example: a = [1, 2, 3].

74
Q

How are tuples defined in Python? - (2)

A

Tuples are defined with round brackets,

for example: a = (1, 2, 3).

75
Q

What is a dictionary in Python?

A

A dictionary in Python is a collection of key-value pairs, where each key is linked to a corresponding value.

76
Q

How are dictionaries defined in Python? - (2)

A

Dictionaries are defined with curly brackets and key-value pairs,

for example: my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}.

77
Q

Unlike real dictionaries where one word can have many meanings, in Python dictionaries:

Each key can only have a

A

a single value

78
Q

How do we create an empty dictionary in Python?

A

We create an empty dictionary in Python using curly braces {}.

79
Q

What is the type of an empty dictionary in Python?

A

The type of an empty dictionary in Python is dict.

80
Q

How do we check the type of a dictionary variable in Python?

A

We can check the type of a dictionary variable in Python using the type() function.

81
Q

What type of brackets are used for indexing in Python dictionaries?

A

Python uses square brackets [] for indexing in dictionaries.

82
Q

Explain the following Python code - (2)

my_dict = {}

print(my_dict)
print(type(my_dict))

A

This code initializes an empty dictionary named my_dict using curly braces {}.

It then prints the contents of the dictionary, which is an empty dictionary {}, and its type, which is <class ‘dict’>.

83
Q

What is output of this code? - (2)

my_dict = {}

print(my_dict)
print(type(my_dict))

A

{}
<class ‘dict’>

84
Q

How to add items to a dictionary in Python with an example: - (4)

A

Items can be added to a dictionary in Python using square bracket notation.

Specifically, you assign a value to a key within the dictionary using square brackets.

For example:
my_dict = {}
my_dict[‘mykey’] = 20

This code snippet creates an empty dictionary my_dict and then assigns the value 20 to the key ‘mykey’.

85
Q

What is the output of the code below?

my_dict = {}
my_dict[‘mykey’] = 20
my_dict[‘anotherkey’] = 100
my_dict[‘Averylongkeyblahblahblah’] = 1
my_dict[‘Navin R Johnson’] = ‘253.125 Elm St’
print(my_dict)

A

{‘mykey’: 20, ‘anotherkey’: 100, ‘Averylongkeyblahblahblah’: 1, ‘Navin R Johnson’: ‘253.125 Elm St’}

86
Q

Explain the code snippet - (3)

my_dict = {}

my_dict[‘mykey’] = 20
my_dict[‘anotherkey’] = 100
my_dict[‘Averylongkeyblahblahblah’]=1
my_dict[‘Navin R Johnson’]=’253.125 Elm St’

print(my_dict)

A

This code initializes an empty dictionary my_dict and then adds several key-value pairs to it.

Each key is associated with a corresponding value using square bracket notation.

Finally, the dictionary is printed, displaying all the key-value pairs added to it.

87
Q

Explain this code - (2)

my_dict = {}

my_dict[‘mykey’] = 20
my_dict[‘anotherkey’] = 100
my_dict[‘Averylongkeyblahblahblah’] = 1
my_dict[‘Navin R Johnson’] = ‘253.125 Elm St’

print(my_dict)

print(f’There are {len(my_dict)} keys in the dictionary’)

A

This code initializes an empty dictionary my_dict and then adds several key-value pairs to it using square bracket notation.

After printing the dictionary, it also displays the number of keys in the dictionary using the len() function.

88
Q

What will be the output of this code? - (2)

my_dict = {}

my_dict[‘mykey’] = 20
my_dict[‘anotherkey’] = 100
my_dict[‘Averylongkeyblahblahblah’] = 1
my_dict[‘Navin R Johnson’] = ‘253.125 Elm St’

print(my_dict)

print(f’There are {len(my_dict)} keys in the dictionary’)

A

{‘mykey’: 20, ‘anotherkey’: 100, ‘Averylongkeyblahblahblah’: 1, ‘Navin R Johnson’: ‘253.125 Elm St’}

There are 4 keys in the dictionary

89
Q

As explained above, we can only have one instance of a single key in a given dictionary at any one time. So, what happens when we try to add a key more than once?

What happens when we try to add a key more than once in a dictionary in Python?

A

When we try to add a key more than once in a dictionary, the existing value associated with that key is replaced by the new value.

90
Q

Example of we try to add a key more than once in a dictionary, the existing value associated with that key is replaced by the new value.

A
91
Q

What is output of this code? - (2)

A

{‘mykey’: 20}
{‘mykey’: 2000000}

92
Q

Explain this code - (6)

A

In this code, we start with an empty dictionary my_dict.

We add a key-value pair to the dictionary where the key is ‘mykey’ and the value is 20.

When we print the dictionary, it displays {‘mykey’: 20}.

Next, we attempt to add another value to the same key ‘mykey’, this time with the value 2000000.

However, since dictionaries in Python can only have unique keys, the existing value associated with ‘mykey’ is replaced by the new value.

Therefore, when we print the dictionary again, it shows {‘mykey’: 2000000}.

93
Q

How do you extract individual values from a dictionary in Python? - (2)

A

To extract individual values from a dictionary in Python, you use square bracket notation with the key of the desired value.

It is the same index (square bracket) notation used to add entries and also same notation used to extract items in lists

94
Q

Example of extracting values in a dictionary

A
95
Q

What is the output of this code? - (2)

A

20
<class ‘int’>

96
Q

Explain this code snippet - (3)

A

The code initializes an empty dictionary my_dict, then adds a key-value pair where the key is ‘mykey’ and the value is 20.

It extracts the value corresponding to the key ‘mykey’ using square bracket notation which is 20 and assigns it to the variable test_var.

Finally, it prints the value of test_var which is 20 and its type which is <class ‘int’>.

97
Q

What happens if you try to extract a value using a key that does not exist in the dictionary?

A

you will get a KeyError exception.

98
Q

Example of keyerror exception

A
99
Q

How can we extract a value from a dictionary without encountering a KeyError if the key does not exist?

A

We can use the .get() function in Python dictionaries.

100
Q

What does the .get() function return if the specified key does not exist in the dictionary?

A

By default, the .get() function returns None if the specified key does not exist in the dictionary.

101
Q

What is the output of this code? - (3)

A

1000
<class ‘NoneType’>
None

102
Q

What does this following code snippet demonstrate? - (4)

A

This code snippet demonstrates the creation of an empty dictionary my_dict, followed by adding a key-value pair to it which has a key of ‘mykey’ and value of 1000

Then an attempt is made to retrieve value associated with non-existent key ‘mykey_notthere’ using .get() and storing in variable ‘my_val’

Since no default value is provided, the function returns None.

Finally, the type and value of my_value are printed which is <class ‘NoneType’> and value is None

103
Q

Example of dictionary already having stuff in it

A

This requires use of : and , characters

104
Q

How can items be deleted from a dictionary in Python?

A

As with lists, Items can be deleted from a dictionary in Python using either the .pop() or del functions.

105
Q

What does the .pop() function return when used to delete an item from a dictionary?

A

The .pop() function returns the value of the deleted item.

106
Q

What does the del function do when deleting items from a dictionary? - (2)

A

The del function in Python is used to remove an item with a specified key from a dictionary.

It deletes the key-value pair associated with the specified key from the dictionary

107
Q

Both pop and del functions in lists and dictionaries in general

A

deletes the key-value pair associated with the specified key from the dictionary

108
Q

What is the difference between using .pop() and del to delete items from a dictionary?

A

The .pop() function returns the value of the deleted item, while del does not return any value.

109
Q

What does this code snippet do? - (8)

A

This code snippet creates a dictionary called my_new_dict with two key-value pairs: ‘age’: 35 and ‘test_value’: 1000.

It then prints out contents of my_new_dict: {‘age’: 35, ‘test_value’: 1000}

It then demonstrates two methods for deleting items from the dictionary.

First, it uses the pop() function to remove the key ‘age’ from the dictionary my_new_dict .

The value associated with the key ‘age’ (35) is stored in the variable removed_value, which is then printed.

After removal, the dictionary my_new_dict is printed again {‘test_value’: 1000}, showing that the key-value pair ‘age’: 35 has been removed from the dictionary.

Next, it uses the del keyword to delete the key ‘test_value’ from the dictionary called my_new_dict.

Then the updated dictionary my_new_dict is printed which is indeed empty since both key-value pairs have been removed.

110
Q

What is the output of this code? - (4)

A

{‘age’: 35, ‘test_value’: 1000}
35
{‘test_value’: 1000}
{}

111
Q

What is an example of a real-world use of a dictionary?

A

Storing participant IDs linked to their ages, where each participant ID serves as a key and the corresponding age serves as the value.

112
Q

How can you check if a specific key exists in a dictionary in Python? - (2)

A

By using the in keyword

In which ‘key’ is in quotes followed by in keyword which is followed by dictionry name

113
Q

An example of using in keyword in dictionaries

A

For example P1 in ages will return True if P1 is a key in ages

114
Q

What is the output of this code? - (2)

A

P1 is a key? : True
P1000 is a key? : False

115
Q

What does the expression ‘P1000’ in ages return if ages is a dictionary containing keys ‘P1’: 35, ‘P2’: 38, ‘P3’: 21, ‘P4’: 28, ‘P5’: 33?

A

False, because there is no key ‘P1000’ in the ages dictionary.

116
Q

How do you print all the keys in a dictionary in Python? - (2)

A

To print all the keys in a dictionary named ages, you can use the keys() method like this: print(ages.keys()).

This method returns all the keys in the dictionary.

117
Q

Explain this code snippet - (3)

A

This code snippet creates a dictionary called ages with keys representing participant IDs and values representing their ages.

Then, it prints out the keys of the dictionary using the keys() method which gives: dict_keys([‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’])

Finally, it prints the type of the value returned by ages.keys(), which is <class ‘dict_keys’>

118
Q

What is output of this code? - (2)

A

dict_keys([‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’])
<class ‘dict_keys’>

119
Q

Although in this example the keys appear to be in order we entered them that is not guaranteed by Python and may need to

A

sort keys using sorted() function or sort() with Python dictionaries (don’t need to convert to list to sort them)

120
Q

How can you convert dictionary keys/values into a list in Python?

A

You can convert the keys/values into a list by simply ‘casting’ (converting) the return value to the list type using list() function

121
Q

Explain the following code snippet - (6)

A

It retrieves the keys from the dictionary ages using the keys() method.

It converts these keys into a list using the list() function.

It assigns the resulting list to the variable my_keys.

It prints the datatype of my_keys using type() which is <class ‘list’>

It prints the contents of my_keys: [‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’]

It prints the length of my_keys using len() which is 5

122
Q

What is output of this code? - (3)

A

<class ‘list’>
[‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’]
5

123
Q

How do you retrieve just the values from a dictionary in Python?

A

Using the .values() function, which returns all the values in the dictionary

124
Q

In Python dictionaries, you cannot directly access a key by

A

its value will return exception error

125
Q

What does the following Python code snippet do? - (4)

A

Has a dictionary age which has participants’ IDs as keys and their ages as values: ages = {‘P1’: 35, ‘P2’: 38, ‘P3’: 21, ‘P4’: 28, ‘P5’: 33}

This code snippet retrieves all values from the ages dictionary using the .values() function, and prints them: dict_values([35, 38, 21, 28, 33])

It then prints the type of the returned values from age dictionary: <class ‘dict_values’>

Additionally, it casts the values from age dictionary into a list using list() and store into variable called ‘my_vals’ and prints out ‘my_vals’: [35, 38, 21, 28, 33]

126
Q

What is output of this code? - (3)

A

dict_values([35, 38, 21, 28, 33])
<class ‘dict_values’>
[35, 38, 21, 28, 33]

127
Q

Methods sections in human neuroscience papers usually list the mean (average) age of the participants. How might we compute this? We can start with a dictionary of ages as above and compute the mean of the participants’ ages by adding up all the ages and dividing by how many there are

A
128
Q

What is output of this code?

A

Mean age of participants is: 37.0

129
Q

We often want to loop over dictionaries to do something to each

A

key/value pair.

130
Q

There are several ways to loop over dictionaries to do something to each key/value pair

Two ways are - (2)

A

1) loop over keys and using dict[key]
2) .items() iterator

131
Q

Example of looping over dictionaries

First method of loop over keys and using dict[ky]

A
132
Q

What will be output of the code?

A

P1 35
P2 38
P3 21
P4 28
P5 33

133
Q

What is the default behaviour of a dictionary in a for loop?

A

iterate over the keys:

134
Q

How does the provided code iterate over a dictionary and print each key along with its corresponding value? - (3)

A

The code iterates over the keys of the dictionary ages using a for loop.

During each iteration, it accesses the key k and retrieves its corresponding value from the dictionary using dictionary indexing (ages[k]).

Then, it prints both the key and its corresponding value.

135
Q

How can we access both the keys and values of a dictionary during each iteration of a loop without using dictionary indexing? - (2)

A

We can use the .items() iterator, which returns key/value pairs one at a time.

This allows us to access both the key and the value directly within the loop without needing to use the dict[key] syntax.

136
Q

Explain how the given code snippet iterates over a dictionary and prints each key-value pair - (3)

A

The code snippet uses a for loop with the .items() iterator to iterate over the dictionary ages.

During each iteration, the keyThing variable is assigned the key, and the valThing variable is assigned the corresponding value.

These key-value pairs are then printed using the print() function.

137
Q

What is output of the code?

A

P1 35
P2 38
P3 21
P4 28
P5 33

137
Q

What is noteworthy about the .items() method used in the given code snippet? - (2)

A

The .items() method returns key-value pairs from the dictionary, and these pairs are automatically unpacked and assigned to the loop variables keyThing and valThing.

This makes the code more concise and readable,

138
Q
A
139
Q

There are several ways to loop over dictionaries to do something to each key/value pair

Two ways are

1) loop over keys and using dict[key]
2) .items() iterator

Both of the examples achieve the same thing - they just use slightly different syntax. Which one you choose to use will depend on the context. For instance, - (3)

A

f you need to sort the keys so that you work through the dictionary in a specific order, you might use a modification of the first version:

for k in sorted(ages):

This loop would guarantee that we walk through the keys in a sorted order. Also remember that there is nothing special about the variable names k and v in the above examples - as usual you can name the variables (more or less) anything you like.

140
Q

2.4.6 Quick Exercise
You are making a database for your experiment:In the code below you will:

1: Create an empty dictionary which will be used to map IDs to ages.

2: Write a loop which goes around three times and, each time, lets the user input an ID or name and then an age. Each time, add a new entry to the dictionary.

3: Print out the dictionary using the normal print command. Then try printing the dictionary, one item at a time, after sorting the names alphabetically. Try and make this second output look as neat as possible using the formatting rules we discussed in the previous session.

Useful keywords that are used here: input

range

print

print(f””)

sort

for …. in ….

sorted(…)

A
141
Q
A
142
Q

The sorted function in Python sorts the

A

dictionary based on keys not valuees by default

143
Q

Explain this code: - (5)

A

The code begins by defining the number of subjects (numSubjects) as 3 and initializes an empty dictionary called ageDict to store participant IDs and ages.

It then enters a loop that iterates three times (for each subject).

Within this loop:
It prompts the user to input a participant ID (partID) and age (partAge).
It stores the entered ID and age as key-value pairs in the ageDict dictionary.

After collecting all the data, it prints out the contents of the ageDict dictionary.

Following this, the code enters another loop that iterates over the sorted items of the ageDict dictionary. This loop:
Uses the sorted() function to sort the dictionary items by keys.
Iterates over the sorted items using the items() iterator, which returns key-value pairs.
Unpacks each key-value pair (ID and age) from the sorted dictionary items.
Formats and prints each ID and age pair using an f-string, ensuring alignment and spacing for readability.

144
Q
A