Exam Revision Flashcards
What will this code give you?
%cd /
%pwd
%ls
%ls - lt
- (3)
%pwd = given /
%ls - lists all contents of current working directory (from bin@ to cuda-keyring)
%ls-lt (output starting from total 100) - lists all contents of current working directory by working out file size and sorts them by date
What does the ‘%history’ command do in Colab notebooks?
The ‘%history’ command in Colab notebooks displays a history of codes and commands written
What does the ‘%magic’ command do in Colab notebooks?
The ‘%magic’ command in Colab notebooks provides information and documentation about available commands and their functionalities.
List all the special commands used in Colab notebooks - (7)
‘%cd’,
‘%pwd’, ‘
%ls’,
‘%ls -lt’,
‘%history’,
‘%magic’.
&mkdir
What does the ‘%mkdir’ command do
It creates a new directory within the current working directory.
Quick Exercise
Practice typing commands in the code window below and run them.
Check what your present working directory is and make a note of it (this might be your home directory on the system on which you are working)
Change to another directory to home
Check where your present working directory
Produce a new directory called test
List contents in test
Change current working directory to test
%pwd
Output: /content/sample_data
%cd /home (root then place we want to go)
Output: /home
%pwd - check where we are
Output: ‘/home’
%mkdir test
No output
%ls
Output: test/
%cd test
Output: /home/test
Identify the issue in the following Python code:
print(“Hello World!)
The issue in the code is the absence of a closing double quote, resulting in an “unterminated string literal” error - indicating that the provided string is not properly terminated with a closing double quote - syntax error
Explain the purpose of the +
operator in the given Python code - (2)
print(“Hello” + “World”).
The +
operator is used for string concatenation in the provided Python code.
It combines the strings “Hello” and “World” into a single string, “HelloWorld”.
What does the following code snippet do? - (3)
b = 10
print(b)
del(b)
print(b)
The code snippet assigns the value 10 to the variable b and prints it.
Then, it deletes the variable b using the del keyword.
Attempting to print b after it has been deleted will result in a NameError because the variable no longer exists.
Explain the behavior of type(float(3)) in Python.
The expression type(float(3)) converts the integer value 3 to a float and then determines its data type using the type() function.
Describe the outcome of int(3.25) in Python.
The expression int(3.25) converts the floating point number 3.25 to an integer, resulting in the value 3.
What is the result of int(3.999) in Python?
The expression int(3.999) converts the floating point number 3.999 to an integer, resulting in the value 3, as the conversion truncates the decimal part.
What arithmetic operations can be performed on numbers in Python?
Arithmetic operations such as addition (+), subtraction (-), multiplication (*), division (/), integer division (//), exponentiation (**), and remainder (%) can be performed on numbers in Python
What happens when executing print(3.0 + 3) in Python? - (3)
When running print(3.0 + 3), Python adds a floating point number (3.0) and an integer (3).
Python automatically converts the integer to a floating point number before performing the addition.
Forces the numbers to be same data type before performing addition.
Adding float to integer it will make it
float
If you keep everything the same datatype when doing arithmetic operations in print statement e.g., print(3 + 2) it will remain the
same data type - integer in this case
If you mix data types when doing arithmetic operations in print statement e.g., print(3.0 + 2) it will
typically become floating point values
What is the output of print(3.0 * 2) in Python?
The output is 6.0.
What is the output of print(3 * 2) in Python?
The output is 6.
Explain the behavior of print(3.0 ** 3) in Python.
It computes the result of raising 3.0 to the power of 3, which equals 27.0.
What does the expression print(9.0 ** 0.5) compute in Python?
It computes the square root of 9.0, which equals 3.0.
How does the power operator () behave in Python? - (2)
The power operator () can be used to compute both “normal” power values, such as squaring, and roots.
For example, raising a number to 1/2 (0.5) computes the square root.
How does division work in Python? - (2)
In Python, division is performed using the / operator.
It automatically converts integers to floating-point numbers ‘where necessary’.
What is the result of print(3 / 2) in Python?
The expression print(3 / 2) evaluates to 1.5 because it performs floating-point division, resulting in a floating-point number.
What does the // operator do in Python?
The // operator in Python performs integer division, discarding any fractional part and returning the integer result.
What is the result of print(3//2) in Python?
The expression print(3//2) evaluates to 1 because it performs integer division, resulting in an integer quotient - has not rounded it (chopped off decimal part)
What does the % (modulus) operator do in Python?
The % operator in Python returns the remainder of the division of the first number by the second number.
What is the result of print(8 % 3) in Python?
The expression print(8 % 3) evaluates to 2 because when 8 is divided by 3, the remainder is 2.
The ‘/’ allows integers to turn into
floating point numbers ‘where necessary’ (in other words if answer is not an integer)
The ‘//’ does not allow
integers to turn to floating point numbers ‘where necessary’ (in other words if answer is not an integer)
When using the integer division operator on floating point numbers, the division will be performed as if numbers were integer but result will be - (2)
floating point
e.g., print(3.0//2) in Python outputs the result of dividing 3.0 by 2 using integer division, resulting in 1.0.
What happens when you try to add a string and an integer in Python
print(3 + “dlfkjdofd”),? - (2)
When you try to add a string and an integer in Python, you get a exception (error) TypeError because Python does not support adding different types together.
In the given example, print(3 + “dlfkjdofd”), Python raises an exception because you cannot concatenate a string and an integer directly.
What type of error do you encounter when trying to add a string and an integer in Python?
When trying to add a string and an integer in Python, you encounter a TypeError.
What are collections of data in Python?
Collections of data in Python are structures designed to store multiple pieces of information.
What are the different types of collections of data in Python? - (3)
- Lists
- Tuples
- Dictionaries
What are lists - (2)?
A list is a collection of data that is ordered and changeable.
It allows you to store multiple items in a single variable.
What is the main difference between a list and a dictionary in Python?
The main difference between a list and a dictionary in Python is that a list is ordered and accessed by index, while a dictionary is unordered and accessed by key.
How are elements accessed in a list compared to a dictionary in Python?
In a list, elements are accessed by their index position, starting from 0. In a dictionary, elements are accessed by their key.
What are member functions in Python? - (2)
Member functions are built-in functions specific to a data structure that allow operations to be performed on that data.
They are called using the syntax: dataStructure.functionName(argument1, …).
What is the purpose of the append() member function in Python lists?
The append() member function adds a single value to the end of a list.
We can use append() many times to add many
elements to a list
What happens when you append a list to another list in Python?
When you append a list to another list using the append() member function, the entire second list becomes a single element of the first list.
What will be the output of print(my_main_list) after appending my_other_list to it?
my_main_list = [1, 2, 3]
my_other_list = [10, 20]
my_main_list.append(my_other_list)
- (2)
The output of print(my_main_list) will include my_other_list as a single element within my_main_list, preserving its structure
Output: [1, 2, 3, [10, 20]] and 4
What is the difference between using .append() and .extend() to add elements from one list to another in Python? - (2)
When using .append(), the entire second list is added as a single element to the first list.
In contrast, when using .extend(), each element of the second list is added individually to the first list.
What does it mean for Python to be a 0-indexed language?
In Python, being a 0-indexed language means that the first element in any sequence, including lists, is referred to as the “zeroth” element, and indexing starts from 0 rather than 1.
How do you access individual elements of a list in Python?
Individual elements of a list in Python are accessed using square brackets [], with the index of the desired element inside the brackets.
What does the code my_new_list[2] = ‘Hello’ do?
my_new_list = [‘ant’, ‘bear’, 10, 20]
print(my_new_list)
my_new_list[2] = ‘Hello’
print(my_new_list)
The code my_new_list[2] = ‘Hello’ replaces the third element in the list my_new_list with the string ‘Hello’.
The square bracket indexing syntax in lists can also be used to modify
an element in a list
note that Python wraps
indexing around with negative numbers.
How can you access elements from the end of a list in Python? - (2)
In Python, you can access elements from the end of a list using positive indices or by using negative indices.
For example, -1 refers to the last element, -2 refers to the second-to-last element, and so on.
What is the output of the code snippet provided?
print(my_new_list[-1]) do? - (2)
my_new_list = [‘ant’, ‘bear’, 10, 20]
print(my_new_list[-1])
print(my_new_list[-2])
20
10
What does the indexing notation [start:stop] in Python lists mean? - (2)
The indexing notation [start:stop] in Python lists is used to extract multiple elements from a list.
It specifies a range of indices from the start index (inclusive) to the stop index (exclusive), and returns a sublist containing the elements within that range.
The indexing notation for extracting multiple elements of list uses a
colon ‘:’
The indexing notation for extracting multiple elements of list uses a colon and its pattern is
[start:stop]
as Python is 0-indexed and end-points are exclusive bold text, the element
which has the last number will not be included
Explain the output of the given code snippet.
my_new_list = [‘ant’, ‘bear’, 10, 20]
Extract 1:3, meaning elements 1 and 2. Print the data and the length
print(my_new_list[1:3])
print(len(my_new_list[1:3]))
print(type(my_new_list[1:3]))
The code extracts elements at index 1 and 2 from my_new_list, prints the extracted elements ([‘bear’, 10]), their length (2), and their data type (<class ‘list’>).
Flashcard 3:
Missing start parameter in list slicing
my_new_list = [‘ant’, ‘bear’, 10, 20]
If we miss out the start parameter, the beginning of the list is presumed
print(my_new_list[:2]) # assumes start parameter is 0
Explain the output of the given code snippet – (2)
The code slices my_new_list from the beginning up to index 2 (exclusive), effectively extracting elements at index 0 and 1.
It prints [‘ant’, ‘bear’], assuming the start parameter as 0 when not explicitly provided.
Missing stop parameter in list slicing
my_new_list = [‘ant’, ‘bear’, 10, 20]
If we miss out the stop parameter, the end of the list is presumed
print(my_new_list[2:]) # assuming going right at end, 0 , 1, 10, 20
Describe the output of the given code snippet. - (2)
The code slices my_new_list from index 2 to the end, effectively extracting elements starting from index 2 to the end of the list.
It prints [10, 20], assuming the stop parameter is at the end of the list when it’s not explicitly provided.
Using the same number as start and stop in list slicing - (2)
python
Copy code
my_new_list = [‘ant’, ‘bear’, 10, 20]
If we use the same number as start and stop, we end up with an empty list
print(my_new_list[1:1]) # ‘[]’
What is the output of the given code snippet and why?
The code attempts to slice my_new_list from index 1 to index 1, resulting in an empty list [].
This happens because when the start and stop parameters are the same, no elements are included in the slice.
Assigning sliced data to a variable
my_new_list = [‘ant’, ‘bear’, 10, 20]
Extract 0:2, meaning elements 0 and 1. Put in a variable
my_data = my_new_list[0:2]
print(my_data)
What does the given code snippet do? - (2)
The code extracts elements at index 0 and 1 from my_new_list and assigns them to a new variable my_data.
It then prints the content of my_data, which would be [‘ant’, ‘bear’]
What does step parameter indicate in list slicing? [start:stop:step] - (2)
The step parameter in list slicing indicates the increment between each index when extracting elements from a list.
It allows for skipping elements based on the specified step size.
animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]
Extract every other item starting at index 1 and finishing at index 5
print(animals[1:5:2]) # start at 1 and finish at 5, exclude 5, go in steps of 2
Describe the output of the given code snippet.
The code extracts every other item from index 1 to index 5 (exclusive) in the animals list and prints the result: [‘bear’, ‘deer’].
animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]
We can miss out the start index and get everything from the start of the list
print(animals[:5:2])
What does the code snippet do, and what is its output? - (2)
The code slices animals from the beginning (0
-assumed) up to index 5 (exclusive) in steps of 2, effectively extracting every other item from the start of the list.
It prints the result: [‘ant’, ‘cat’, ‘elk’].
animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]
We can miss out the stop index and get everything to the end of the list
print(animals[1::2])
Question: Explain the output of the given code snippet. - (2)
he code slices animals from index 1 to the end of the list in steps of 2, effectively extracting every other item starting from index 1.
It prints the result: [‘bear’, ‘deer’, ‘frog’, ‘horse’].
animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]
We can even miss out the start and stop indices
print(animals[::2])
What does the code snippet do, and what is its output? - (2)
The code slices animals from the beginning to the end of the list in steps of 2, effectively extracting every other item from the list.
It prints the result: [‘ant’, ‘cat’, ‘elk’, ‘goose’].
animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]
And we can use any step we like, including negative numbers
print(animals[::-1]) # printing animals in reverse order
Describe the output of the given code snippet.
The code prints animals list in reverse order by slicing it with a step of -1: [‘horse’, ‘goose’, ‘frog’, ‘elk’, ‘deer’, ‘cat’, ‘bear’, ‘ant’].
Describe what the given code snippet does - (2)
my_special_number=[‘1’,’5’,’2’,’7’,’9’,’2’,’3’,’8’,’8’]
numbers_requested=my_special_number[0:8:3] # or write it as [0::3] or [::3], same output, or write in reverse do ‘[::-1]’
print(numbers_requested)
The code extracts every third number from the list my_special_number, starting with the first number, and prints the result: [‘1’, ‘7’, ‘3’].
my_special_number can be written as as [0::3] or [::3],
Some banks ask for a small subset of your ‘special number’ for verification purpose. Change the code below so that it prints out every third number starting with the first one.
my_special_number=[‘1’,’5’,’2’,’7’,’9’,’2’,’3’,’8’,’8’]
numbers_requested=my_special_number[xxxxx]
print(numbers_requested)
my_special_number=[‘1’,’5’,’2’,’7’,’9’,’2’,’3’,’8’,’8’]
numbers_requested=my_special_number[0:8:3] # or write it as [0::3] or [::3], same output,
print(numbers_requested)
What are the two main ways of removing elements of a list? - (2)
- Pop
- Del statement
Explain the functionality of the .pop() method when removing items from a list - (2)
The .pop() method in Python removes and returns the element at the specified index from a list.
It modifies the original list by removing the element and optionally allows you to storing the removed element in another variable.
Describe the purpose of the del statement when removing items from a list - (2)
The del statement in Python is used to remove an item or slice from a list by specifying its index.
It directly modifies the original list by deleting the specified item, and it does not return the removed item as .pop() does.
Describe what the given code snippet does using the .pop() method - (3)
my_list = [10, 20, 30, 40, 50]
print(my_list)
thing_removed = my_list.pop(2) #stores thing deleted which is 30
print(thing_removed) # prints out 30
print(my_list) # prints out list with ‘30’ deleted
The code removes the element at index 2 from the list my_list using the .pop() method.
It stores the removed element in the variable thing_removed which is ‘30’ and prints it.
Then, it prints the updated list (my_list) without the removed element ‘[10,20,40,50]’
Describe what the given code snippet does using the del statement - (2)
my_list = [10, 20, 30, 40, 50]
del my_list[0] #or use del statement to delete first element of list ‘10’
print(my_list) #prints new list with 10 removed
The code uses the del statement to remove the element at index 0 from the list my_list, which is ‘10’.
It then prints the updated list of my_list without the removed element: ‘[20,30,40,50]’
Question: Explain the functionality of the sorted function when sorting a list - (2)
The sorted function in Python returns a new list containing the elements of the original list sorted in ascending order.
It does not modify the original list, instead, it creates a new sorted list.
Describe the purpose of the .sort() method when sorting a list.
he .sort() method in Python sorts the elements of a list in ascending order in-place, meaning it directly modifies the original list.
It does not return a new list but instead sorts the elements within the original list itself.
Describe what the given code snippet does using the sorted function - (3)
my_num_list = [50, 40, 10, 20]
my_sorted_list = sorted(my_num_list)
print(my_sorted_list)
print(my_num_list)
The code snippet sorts the list my_num_list using the sorted function and stores the sorted result in the variable my_sorted_list which is [10,20,40,50]
It then prints both the sorted list of [10,20,40,50] and the original list [50,40,10,20]
The original list remains unchanged after sorting.
Describe what the given code snippet does using the .sort() method - (3)
my_num_list = [50, 40, 10, 20]
my_num_list.sort()
print(my_num_list)
The code snippet sorts the list my_num_list in-place using the .sort() method which is [10,20,40,50]
It directly modifies the original list, sorting it in ascending order.
Then, it prints the sorted list which is [10,20,40,50]
How would you define a tuple? - (2)
A tuple is an ordered collection of elements, similar to a list.
However, tuples are immutable, meaning their contents cannot be changed after creation.
What are the similarities and differences between tuples and lists? - (4)
Both tuples and lists can store multiple elements and can be indexed and sliced.
However, tuples are immutable meaning you can’t add or remove items to/from a tuple, while lists are mutable.
Tuples are typically used for fixed collections of data, while lists are used for collections that may need to be modified.
Differences between tuples and lists are tuples are defined using ‘()’ whereas lists use ‘[]’
We can create an empty tule using
round brackets ‘()’
What is the output of the given code snippet? - (4)
a = ()
Printing the type and content of the tuple
print(type(a))
print(a)
The output will display the type of the variable a, which is tuple, and an empty tuple ().
<class ‘tuple’>
()
The problem with creating an empty tuple is that
they cannot be changed - this therefore means that it will remain empty forever!
More commonly, we would create a tuple with
existing content:
What is the output of the given code snippet?
Creating a tuple with existing content
a = (1, 2, 3)
Printing the tuple
print(a)
The output will display the tuple (1, 2, 3) containing the numbers 1, 2, and 3.
With tuples you can perform tuple operations like - (2)
extract items from tuple e.g., my_tuple[1]
and count length of type using len()
What is the output of this code below?
Accessing an item in a tuple and getting its length
my_tuple = (5, 10, 15)
print(my_tuple[1]) # Accessing the second item in the tuple
print(len(my_tuple)) # Getting the length of the tuple
10
3
What happens when you attempt to modify an item in a tuple?
Modifying an item in a tuple will raise a TypeError exception since tuples are immutable and do not support item assignment.
What is output of this code?
Attempting to modify an item in a tuple (will raise a TypeError exception)
my_tuple = (5, 10, 15)
my_tuple[0] = 100 # This will raise a TypeError exception
TypeError: ‘tuple’ object does not support item assignment
if you have a tuple which you need to modify, you can cast it to (turn it into) a list and back again. This does not modify
the first tuple, but creates a new one with new content:
What is output of this code?
my_orig_tuple = (1, 2, 3, 4)
my_tmp_list = list(my_orig_tuple)
my_tmp_list[0] = 100
my_new_tuple = tuple(my_tmp_list)
print(my_orig_tuple)
print(my_new_tuple)
(1, 2, 3, 4)
(100, 2, 3, 4)
What does the provided code snippet do? - (2)
my_orig_tuple = (1, 2, 3, 4)
my_tmp_list = list(my_orig_tuple)
my_tmp_list[0] = 100
my_new_tuple = tuple(my_tmp_list)
print(my_orig_tuple)
print(my_new_tuple)
The code snippet converts the original tuple my_orig_tuple into a list my_tmp_list, modifies the first element of the list to 100, and then converts the modified list back into a tuple my_new_tuple.
It finally prints both the original and modified tuples.
What is the purpose of loops in programming?
Loops in programming are used to automate repetitive tasks, making coding more efficient and reducing manual effort
Examples of using lops to repeat simple operations that would be useful like
making lots of stimuli for an experiment or analyzing lots of different datasets.
Explain general structure of for loop - (4)
LOOPVARIABLE (which can be named whatever you want) will be set to the first item in LIST_OF_THINGS_TO_ITERATE_OVER.
The code which is indented (just a comment in this case) will then run.
Once all of the code which is indented has been run, the loop will go back to the top, LOOPVARIABLE will be set to the second item in LIST_OF_THINGS_TO_ITERATE_OVER and all of the indented code will run again.
This will repeat for each element in LIST_OF_THINGS_TO_ITERATE_OVER.
Describe this code -(4)
for t in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(“Hello!”)
print(“Hello”,t)
In the given code snippet, the for loop iterates over each element in the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
During each iteration, the loop variable ‘t’ takes on the value of the current element in the list.
Within the loop, the first print statement prints “Hello!” for each iteration, resulting in the message being printed 10 times.
The second print statement includes the value of ‘t’, causing “Hello” to be printed along with the current value of ‘t’ for each iteration, producing output where “Hello” is printed 10 times followed by “Hello” and the numbers 1 through 10 respectively.
What is the output of this code?
for t in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(“Hello!”)
print(“Hello”,t)
Hello!
Hello 1
Hello!
Hello 2
Hello!
Hello 3
Hello!
Hello 4
Hello!
Hello 5
Hello!
Hello 6
Hello!
Hello 7
Hello!
Hello 8
Hello!
Hello 9
Hello!
Hello 10
To ident code inside loop you can either use
4 spaces or tab
Create a for loop that produces 1-10
Output of this code and explain - (4):
Meaning:
print(x,x**2) is idented within for loop so we print each element in a list followed by itself squared:
In print(x.5) is not idented within for loop and identation is different from print(x,x2) so left the for loop
print(x,x**.5) square root the last element of the list (‘x’) which is 40 and prints “Done”
Output:
10 100
20 400
30 900
40 1600
6.324555320336759
Done
Explain this code and give its output:
Meaning:
The loop iterates over each element in the list my_list.
For each iteration, it prints “Hello”.
It computes the square of the current element (x) and stores it in y.
It then prints both the current element (x) and its square (y).
Output:
Hello
10 100
Hello
20 400
Hello
30 900
Hello
40 1600
You can run any code you want inside of a loop. One thing which you should not do however, is to - (2)
delete an item in a list whilst you are looping over the list.
This will cause hard to find problems in your code and almost certainly not do what you want
Write a code that has a list 10-100 stored in my_list = [] var
For loop that loops over that list and prints out value of x and its x squared and its square root on each iteration
What is output of the code?
What is nested for loops? - (3)
situation where one for loop is contained within another for loop.
This means that one loop runs inside another loop.
Each time the outer loop runs once, the inner loop can potentially run multiple times, depending on its own iteration behavior.
For nested for loops it is
important to follow the indentation carefully reading this code.
What is range() in Python? - (2)
built-in function used to generate a sequence of numbers.
It’s commonly used in loops to iterate over a specific range of numbers.
3 ways to use/call range() function - (3)
- range(stop)
- range(start,stop)
- range(start,stop,setp)
What is range(stop)
This generates a sequence of numbers starting from 0 up to (but not including) the specified stop value.
What is range(start,stop)?
This generates a sequence of numbers starting from start up to (but not including) the stop value.
What is range(start,stop,step) - (2)
This generates a sequence of numbers starting from start up to (but not including) the stop value, with a specified step size between each number.
The step parameter is optional and defaults to 1 if not provided
In python, all stop-style parameters are exclusive; i.e. - (3)
they are not included in the list which is returned.
This means that if we ask for range(0, 4), we will get the numbers 0, 1, 2, 3.
Forgetting how this works is a common source of bugs.
What will this output give you?
x = range(5)
print(type(x))
print(x)
<class ‘range’>
range(0, 5)
print the generator
What will this code give you?
x = list(range(5))
print(type(x))
print(x)
0 it is convert to list and print
<class ‘list’>
[0, 1, 2, 3, 4]
What will this code give you?
x = list(range(1, 500))
print(x)
[1, 2, 3, 4, 5, …., 499]
The step parameter in range… - (2)
sets the increment or decrement.
Setting this to be negative lets us count backwards.
What will these code give? - (3)
[1, 3]
[5, 4, 3, 2, 1]
[4, 3, 2, 1, 0]
range function generates a sequence of integer numbers within a specified range.
If you want to use floating point numbers then
use the arange function from the numpy module – we will cover this in a future session.
Sample exam questions
Q1.1
name = ‘Alice”
# What is wrong with this line of code? - (3)
The quotes do not match.
Either use all single quotes or all double quotes.
For example, name=’Alice’
Q1.2
age = ‘23’
print(age + 2)
# Why does this code raise an error? - (2)
age is a string variable but you are adding an integer to it.
Variable types have to match when doing arithmetic
Q1.3
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits[3] = ‘orange’
# What is incorrect with this code? - (2)
The list only has 3 entries but you are trying to access the fourth one.
Python indexing starts at zero.
Q1.4
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)
# What will this print, and why might it confuse a beginner? - (2)
This will concatenate the lists: [1,2,3,4,5,6]
You might be expecting it to add them element by element [5,7,9], or even include list2 as a member of list 1 [1,2,3,[4,5,6]]
Q1.5
my_tuple = (1, 2, 3)
my_tuple[1] = 4
# What concept does this example illustrate, and what is the mistake? - (3)
You cannot change tuples once you make them.
Here you are trying to alter the second element in the tupe.
You can’t.
Q1.6
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(num)
# Identify and correct the mistake in this loop - (2)
The variable ‘num’ is not defined. That line should read
print(number)
for i in range(5):
print(“Number is: “, i)
# What will be the output of this loop, and what common misunderstanding might this clarify? - (2)
0,1,2,3,4
It will demonstrate that python ranges are zero indexed and exclusive (they start at zero and do not include the last number)
for i in range(3):
for j in range(2):
print(i, j)
# What will be the output of this nested loop, and what concept does it illustrate? - (3)
0 0
0 1
1 0
1 1
2 0
2 1
Ranges start at zero and exclude the highest element. Also loop blocks are defined by indentation.
And nested loops are evaluated from the deepest loop out.
name = “John”
greeting = “Hello, name!”
print(greeting)
# Why doesn’t this code snippet print “Hello, John!”? - (3)
The variable ‘name’ and the word ‘name’ inside the string are different things.
You could write
print(“Hello”,name)
To get the right answer.
def multiply(x, y):
return x * y
print(multiply(2))
# What error will this code produce and why?
function looks like it takes two arguments (x and y) but you are only providing one argument when you call it (2)
%pwd
%cd ..
%ls
# Explain what each of these ‘magic’ / or ‘shell’ commands does - (3)
pwd = print the working directory
cd = change directory (in this case to the one above)
ls = list the contents of the current directory
my_string = “Hello, World!”
print(my_string[-1])
What will be printed when executing this code, and what concept does it illustrate? - (2)
The code will print the last character of the string, which is “!”.
This illustrates the concept of negative indexing in Python, where -1 refers to the last element, -2 refers to the second last, and so on.
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
What output will this code produce, and why? - (3)
The code will print [3, 4].
This is because slicing with the notation [start:stop] returns a sublist containing elements from index start up to (but not including) index stop.
In this case, it extracts elements at indices 2 and 3 from my_list.
my_list = [1, 2, 3, 4, 5]
my_list[1:4] = [8, 9, 10]
print(my_list)
What will the final contents of my_list be after executing this code? - (2)
The final contents of my_list will be [1, 8, 9, 10, 5].
This code replaces elements at indices 1, 2, and 3 in my_list with the elements [8, 9, 10], resulting in the modified list.
my_list = [‘apple’, ‘banana’, ‘cherry’]
print(my_list[::-1])
What will be printed when running this code, and what is the purpose of the slicing notation used? - (2)
The code will print [‘cherry’, ‘banana’, ‘apple’], which is the reversed version of my_list.
The slicing notation [start:stop:step] with step as -1 is used to reverse the order of elements in the list.
What is a modern and preferred method for combining data and strings for output formatting in Python, beside using commas?
Using f-strings, which provide a more elegant and concise way to format output by embedding variables directly into strings.
What does f-strings stand for in Python?
An f-string, short for “formatted string literal,”
How do you create an f-string in Python?
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.
What happens when an f-string is evaluated in Python?
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.
Explain this code - (4)
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.
Example of adding multiple variables in f-string in Python
How can you force a value to occupy a certain amount of space using f-strings in Python? -
By adding a colon followed by the desired width after the variable name inside curly braces {} in the f-string.
What would be output of this code?
Q: Explain the purpose of the following f-string
myvar = ‘Test’
print(f’==={myvar:20}===’): - (3)
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 to change allignment of variable in f-string?
You can change the alignment by adding a character before the width number inside curly braces {} in the f-string:
What is the default alignment behavior of a string in f-strings?
By default, strings are left-centered in the space provided within an f-string.
What is the output of the following f-string?
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.
What is the output of the following f-string?
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.
What is output of the following f-string? - (2)
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 does f-string handle space expansion when the inserted string is longer than the specified width?
F-strings expand the space to fit the entire string when it is longer than the specified width
What is the output of this code? - (3)
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===
What is the output of the code print(f’==={myvar:^7}===’) where myvar = 500000090? - (2)
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.
What is the purpose of zero-padding integers in Python (using f-strings with numbers)? - (3)
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).
What is the output of the code print(f’{mynum:03}’) where mynum = 5? - (2)
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 can you control the number of decimal places in floating point numbers using f-strings?
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}
What is the output of
print(f’=={myval:10.4f}==’)
where myval = 10.219? - (3)
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.
What is the output of print(f’=={myval:7.2f}==’)
where myval = 10.219? - (3)
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.
What happens if you ask for fewer decimal places in f-strings in Python?
Python rounds the numbers to the specified number of decimal places
What character is used for scientific notation in f-strings?
The e formatting character is used for scientific notation in f-strings.
How is scientific notation represented using the “e” formatting character? - (2)
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).
What is the output of the code print(f’==={myval:e}===’)
where myval = 0.000001?
The output is “===1.000000e-06===”, which represents the number 0.000001 in scientific notation.
How can you control the number of decimal places in scientific notation when using the “e” formatting character in f-string? - (2)
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.
What happens if the provided number of spaces is not sufficient for the number when using the “e” formatting character?
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.
What is the purpose of specifying “.1e” in the code print(f’==={myval:.1e}===’)?
Specifying “.1e” limits the number of decimal places to one in the scientific notation representation of the number.
What is the output of the code print(f’==={myval:.1e}===’) where myval = 0.000001? - (3)
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.
What is the output of the code print(f’==={myval:10.1e}===’) where myval = 0.000001? - (4)
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.
What does ‘d’ mean in f-string formatting?
In f-string formatting, ‘d’ is used to specify that the value should be formatted as an integer.
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} |’)?
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’.
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)
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.
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)
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.
What is output of the code?
P001 | 100 | 100.210 |
Explain this code - (2)
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.
What is the purpose of the input function in Python? - (3)
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.
What is the data type of the value returned by the input function? - (2)
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.
What is the output of the following code snippet? - (3)
data = input(‘Enter a word: ‘)
print(type(data))
print(data)
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
What is output? if user input is 10
Enter a number: 10
‘<class ‘str’>’
10
‘<class ‘int’>’
10
20
Explain this code if user input is 10 - (2)
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
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
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)
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.
What is a dictionary in Python?
A dictionary in Python is a collection of key-value pairs, where each key is linked to a corresponding value.
How are dictionaries defined in Python? - (2)
Dictionaries are defined with curly brackets and key-value pairs,
for example: my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}.
Unlike real dictionaries where one word can have many meanings, in Python dictionaries:
Each key can only have a
a single value
How do we create an empty dictionary in Python?
We create an empty dictionary in Python using curly braces {}.
What is the type of an empty dictionary in Python?
The type of an empty dictionary in Python is dict.
What type of brackets are used for indexing in Python dictionaries?
Python uses square brackets [] for indexing in dictionaries.
Explain the following Python code - (2)
my_dict = {}
print(my_dict)
print(type(my_dict))
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’>.
What is output of this code? - (2)
my_dict = {}
print(my_dict)
print(type(my_dict))
{}
<class ‘dict’>
How to add items to a dictionary in Python with an example: - (4)
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’.
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)
{‘mykey’: 20, ‘anotherkey’: 100, ‘Averylongkeyblahblahblah’: 1, ‘Navin R Johnson’: ‘253.125 Elm St’}
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’)
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.
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’)
{‘mykey’: 20, ‘anotherkey’: 100, ‘Averylongkeyblahblahblah’: 1, ‘Navin R Johnson’: ‘253.125 Elm St’}
There are 4 keys in the dictionary
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?
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.
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.
What is output of this code? - (2)
{‘mykey’: 20}
{‘mykey’: 2000000}
Explain this code - (6)
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}.
How do you extract individual values from a dictionary in Python? - (2)
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
Example of extracting values in a dictionary
What is the output of this code? - (2)
20
<class ‘int’>
Explain this code snippet - (3)
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’>.
What happens if you try to extract a value using a key that does not exist in the dictionary?
you will get a KeyError exception.
Example of keyerror exception
How can we extract a value from a dictionary without encountering a KeyError if the key does not exist?
We can use the .get() function in Python dictionaries.
What does the .get() function return if the specified key does not exist in the dictionary?
By default, the .get() function returns None if the specified key does not exist in the dictionary.
What is the output of this code? - (3)
1000
<class ‘NoneType’>
None
What does this following code snippet demonstrate? - (4)
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
Example of dictionary already having stuff in it
This requires use of : and , characters
How can items be deleted from a dictionary in Python?
As with lists, Items can be deleted from a dictionary in Python using either the .pop() or del functions.
What does the .pop() function return when used to delete an item from a dictionary?
The .pop() function returns the value of the deleted item.
What does the del function do when deleting items from a dictionary? - (2)
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
Both pop and del functions in lists and dictionaries in general
deletes the key-value pair associated with the specified key from the dictionary
What is the difference between using .pop() and del to delete items from a dictionary?
The .pop() function returns the value of the deleted item, while del does not return any value.
What does this code snippet do? - (8)
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.
What is the output of this code? - (4)
{‘age’: 35, ‘test_value’: 1000}
35
{‘test_value’: 1000}
{}
How can you check if a specific key exists in a dictionary in Python? - (2)
By using the in keyword
In which ‘key’ is in quotes followed by in keyword which is followed by dictionry name
An example of using in keyword in dictionaries
For example P1 in ages will return True if P1 is a key in ages
What is the output of this code? - (2)
P1 is a key? : True
P1000 is a key? : False
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?
False, because there is no key ‘P1000’ in the ages dictionary.
How do you print all the keys in a dictionary in Python? - (2)
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.
Explain this code snippet - (3)
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’>
What is output of this code? - (2)
dict_keys([‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’])
<class ‘dict_keys’>
Although in this example the keys appear to be in order we entered them that is not guaranteed by Python and may need to
sort keys using sorted() function or sort() with Python dictionaries (don’t need to convert to list to sort them)
How can you convert dictionary keys/values into a list in Python?
You can convert the keys/values into a list by simply ‘casting’ (converting) the return value to the list type using list() function
Explain the following code snippet - (6)
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
What is output of this code? - (3)
<class ‘list’>
[‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’]
5
How do you retrieve just the values from a dictionary in Python?
Using the .values() function, which returns all the values in the dictionary
In Python dictionaries, you cannot directly access a key by
its value will return exception error
What does the following Python code snippet do? - (4)
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]
What is output of this code? - (3)
dict_values([35, 38, 21, 28, 33])
<class ‘dict_values’>
[35, 38, 21, 28, 33]
What is output of this code?
Mean age of participants is: 37.0
There are several ways to loop over dictionaries to do something to each key/value pair
Two ways are - (2)
1) loop over keys and using dict[key]
2) .items() iterator
Example of looping over dictionaries
First method of loop over keys and using dict[ky]
What will be output of the code?
P1 35
P2 38
P3 21
P4 28
P5 33
What is the default behaviour of a dictionary in a for loop?
iterate over the keys:
How does the provided code iterate over a dictionary and print each key along with its corresponding value? - (3)
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.
How can we access both the keys and values of a dictionary during each iteration of a loop without using dictionary indexing? - (2)
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.
Explain how the given code snippet iterates over a dictionary and prints each key-value pair - (3)
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.
What is output of the code?
P1 35
P2 38
P3 21
P4 28
P5 33
What is noteworthy about the .items() method used in the given code snippet? - (2)
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,
The sorted function in Python sorts the
dictionary based on keys not valuees by default
Explain this code: - (5)
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.
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
‘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.
‘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.
‘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 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
As with for loops, blocks of statements which are inside an if need to be
indented
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)
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
‘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!
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!”.
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 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 t why a certain condition fails to find b in the dictionary e.
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
What is the output?
Question 1: String Formatting Issue
What is problem with code?
Use {} not [] to embed variables in f-strings
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)
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.
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)
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):
Question 4: Conditional Statement Syntax Error
Identify the syntax error in the conditional statements.
The last ‘else’ is missing a colon
else:
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)
‘is’ is usually used for lists or dictionaries or strings. For numbers, just use == instead
if (x>3) and (y==10):
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)
It is evaluated when the countdown gets to zero.
It tells the program what to do when the countdown is not 3,2,1…
Question 7: Rounding and mixing Data Types in F-String
How would you make this f-print statement round to the nearest integer? - (2)
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}”)
name = “Emily”
age = 35
print(“My name is “ + name + “ and I am “ + age + “ years old.”)
What is the problem with this code? - (4)
The problem with this code is that the variable age is of integer type, and it cannot be directly concatenated with strings using the + operator.
To fix this, you should convert the age variable to a string using the str() function before concatenating it with other strings.
Here is corrected answer:
name = “Emily”
age = 35
print(“My name is “ + name + “ and I am “ + str(age) + “ years old.”)
numbers = [1, 2, 3, 4, 5]
print(numbers[6])
**Identify the error in the code and suggest a solution to avoid this error - (8)
Identify the error:
The error in the code is an “IndexError,” specifically stating that the index is out of range.
This means that the index 6 is beyond the bounds of the list numbers, which has indices ranging from 0 to 4.
Solution:
To avoid this error, ensure that the index used to access elements from the list is within the bounds of the list.
In this case, you should use an index that is valid for the given list.
For example, if you want to access the last element of the list, you can use index 4, not 6 e.g,, print(numbers[4])
Alternatively, you can handle such errors using try-except blocks to gracefully manage situations where an invalid index is used
Example of using try block for this example:
numbers = [1, 2, 3, 4, 5]
print(numbers[6])
def greet(name, message):
print(“Hello “ + name)
print(message)
greet(“Alex”)
Identify the syntax error in the function call and suggest a solution. - (5)
The syntax error occurs in the function call greet("Alex")
.
The function definition ‘greet()’ expects two arguments (name
and message
), but only one argument (name
) is provided in the function call.
This results in a TypeError.
To fix this error, provide both name
and message
arguments in the function call, matching the expected arguments in the function definition.
Example solution:
greet(“Alex”, “Good morning!”)
Explain why the loop does not sum the numbers correctly and suggest a fix - (6)
total = 0
i = 1
while i <= 5:
total += i
print(“Total is:”, total)
The loop does not sum the numbers correctly because the loop control variable ‘i’ is never incremented inside the loop.
As a result, the loop condition while i <= 5
always remains true, leading to an infinite loop.
Consequently, the program keeps adding the same value of ‘i’ to ‘total’ repeatedly without progressing to the next number in the sequence.
To fix this issue, you should increment the value of ‘i’ inside the loop to ensure that it progresses through the numbers from 1 to 5.
By incrementing ‘i’, the loop iterates through each number in the sequence and correctly accumulates the sum of these numbers in ‘total’.
Example solution:
total = 0
i = 1
while i <= 5:
total += i
i += 1 # Increment ‘i’ inside the loop
print(“Total is:”, total)
What does ‘total+= i’ mean?
total = 0
i = 1
while i <= 5:
total += i
print(“Total is:”, total)
total += i is equivalent to total = total + i, which means the value of i is added to the current value of total, and the updated value is stored back in total.
my_list = [1, 2, 3, 4,]
print(my_list)
Identify the syntax error in the list initialization and suggest a fix - (2)
The trailing comma after the last element is unnecessary.
Remove it to avoid syntax errors.
Explain the following Python code - (2)
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.strip())
This code removes leading and trailing whitespace characters (such as spaces, tabs, and newline characters) from the string stored in the variable my_string.
The strip() method is used to perform this operation, and the resulting string with whitespace removed is printed to the console.
Explain the following Python code and how it combines string methods - (4)
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.strip().lower())
This code demonstrates the combination of string methods in Python.
First, the strip() method is applied to my_string to remove leading and trailing whitespace characters.
Then, the lower() method is applied to the resulting string, converting all characters to lowercase.
The combined effect of these methods is that the string is stripped of whitespace and converted to lowercase before being printed to the console.
Explain the meaning of the following string assignment (i.e., (i.e., “string assignment” refers to the process of assigning a string value to a variable) - (3)
my_string=”\n hello world \t”
In the given string assignment, my_string, the escape sequences \n and \t are used.
\n represents a newline character, causing the text “hello world” to start on a new line.
\t represents a tab character, adding tab spaces (equivalent to multiple spaces) before the text “hello world”.
Why might using a series of if statements to check for variations in capitalization or leading whitespace be considered clunky? - (2)
e.g.,
if (inputWord==’pencil’) or (inputWord==’PENCIL’) or (inputWord==’Pencil’) or (inputWord=…..
Using a series of if statements to check for variations in capitalization or leading whitespace can be considered clunky because it requires writing repetitive code and becomes cumbersome to maintain, especially if the password changes.
Also you may not think of all the variations people can type pencil
Let’s imagine we have a password system for school district
Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).
Second way -Turning any user input to lower case and check against ‘pencil’ - produce this code - target string is ‘pencil’
target_string = ‘pencil’
user_input = input(‘Login with user password: ‘)
user_input = user_input.lower()
if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)
Explain the following Python code - (6)
target_string = ‘pencil’
user_input = input(‘Login with user password: ‘)
user_input = user_input.lower()
if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)
This code prompts the user to enter a password and compares it with a target password stored in lower case.
Firstly, the target password ‘pencil’ is stored as all lower-case characters in variable ‘target_string’
Then, the user is prompted to input their password.
The user_input.lower() function converts the user’s input to lower case, ensuring that the comparison is not case-sensitive.
If the user’s input matches the target password, ‘Welcome to the Seattle Public School District DATANET’ is printed; otherwise, ‘Password denied’ is printed.
This approach ensures that the password comparison ignores variations in capitalization and provides a robust password validation mechanism.
Explain the functionality of the split string member function .spilt() in Python.
The split string member function is designed to take a string and split it into a list of strings
What is the default behaviour of .spilt() string member function?
By default, it splits the string on any whitespace characters (such as spaces, tabs, or newlines/carriage-return characters),
Explain the functionality of the provided Python code - (10)
dat = ‘The cat sat on the mat’
res = dat.split()
print(type(res))
print(res)
print(len(res))
The provided code utilizes the split() method to split the string “The cat sat on the mat” into individual words.
It initializes a string variable dat with the value ‘The cat sat on the mat’.
The split() method is applied to dat, splitting the string into individual words based on whitespace characters.
The resulting list is stored in the variable res.
It prints the type of res (which confirms it’s a list), the contents of res (the individual words), and the length of res (the number of words in the original string).
Output:
<class ‘list’>
[‘The’, ‘cat’, ‘sat’, ‘on’, ‘the’, ‘mat’]
6
You can see that it takes the string “The cat sat on the mat” and breaks it apart into 6 strings - one for each part of the string between each space character.
The length of the resulting list is 6, corresponding to the number of words in the original string.
Explain how to change the character on which the split method splits a string in Python,
To change the character on which the split method splits a string, you can pass a desired ‘separator’ character as an argument to the method.
Example of change the character on which spilt spilts the string by passing our desired ‘seprator; character as an arguement - (2)
if we have a string which is separated by commas:
dat = ‘Person,Condition,RT’
res = dat.split(‘,’)
print(res)
Explain:
In this example, the string dat is split into individual parts at each comma character, and the resulting list is printed:
Output:
[‘Person’, ‘Condition’, ‘RT’]
Modify this code below to spilt on a different character like ‘o’:
dat = ‘Person,Condition,RT’
res = dat.split(‘,’)
print(res)
dat = ‘Person,Condition,RT’
res = dat.split(‘o’)
print(res)
What is output of this code:
dat = ‘Person,Condition,RT’
res = dat.split(‘o’)
print(res)
[‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]
Explain this code - (5)
dat = ‘Person,Condition,RT’
res = dat.split(‘o’)
print(res)
The string ‘Person,Condition,RT’ is stored in the variable dat.
The split(‘o’) method is applied to dat, splitting the string at each occurrence of the letter ‘o’.
The resulting list is stored in the variable res.
It prints the content of res, which contains the parts of the string split at each occurrence of ‘o’.
So output would be: [‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]
Explain the concept of “white-space” in Python and what it refers to - (2)
In Python, “white-space” refers to characters such as tabs, spaces, and newline/carriage-return characters.
These characters are used to format code or data files and are typically invisible when displayed.
What does “carriage return” mean in the context of datafiles? - (2)
n data files, “carriage return” indicates the end of a line in a datafile.
In Python, it is represented by the special symbol \n, which is interpreted as a “newline” character.
Example of using \n
What i the output of this code?
print(“Hello\nWorld”)
Hello
World
Explain this code and its output - (3)
print(“Hello\nWorld”)
The string “Hello\nWorld” is passed to the print() function.
You have inserted a newline in between the two words, so they get printed on different lines such as:
Output
Hello
World
What is a tab character in Python? - (2)
A tab character in Python, represented as \t, is a special type of whitespace character used to align text by moving the cursor to the next tab stop at a fixed interval.
It is commonly used for indentation and formatting purposes in documents, code, or data files.
What is output of code going to be?
print(“This\tis\tindented”)
This is indented
Explain the functionality of the provided Python code - (6)
my_string = ‘Country\t,GDP\t,Happiness\t,Authoritarianism\t\n\r’
string_list = my_string.split(“,”)
for thisString in string_list:
cleanString = thisString.strip()
print(cleanString)
This code initializes a string my_string containing tab-separated values (with commas as delimiters) and newline/carriage return characters.
The string is then split into a list of strings using the split() method with a comma delimiter.
Each element in the resulting list retains the tab characters (\t).
The for loop iterates over each element in string_list, and the strip() method is applied to remove any leading or trailing whitespace, including the tab characters, from each element.
Finally, it prints each cleaned string:
Country
GDP
Happiness
Authoritarianism
What is output of this code?
my_string = ‘Country\t,GDP\t,Happiness\t,Authoritarianism\t\n\r’
string_list = my_string.split(“,”)
for thisString in string_list:
cleanString = thisString.strip()
print(cleanString)
Country
GDP
Happiness
Authoritarianism
A full pathname for a file on a computer consists of a.. together these elements uniquelty identifiy - (2)
directory (or folder) and a filename, which must be unique within the directory.
Together, these elements uniquely identify the location of the file within the file system.
Explain the concepts of absolute and relative paths in computing
An absolute path provides the complete address of a file or directory starting from the root directory, whereas a relative path specifies the location of a file relative to the current working directory.
Provide an example of an absolute path in computing - (2)
An example of an absolute path in computing is
/home/user/documents/my_file.txt.
This path specifies the complete address of the file my_file.txt, starting from the root directory (/) and including all intermediate directories (home, user, documents).
Give an example of a relative path in computing - (3)
An example of a relative path in computing is data/my_data.csv.
This path specifies the location of the file my_data.csv relative to the current working directory.
It indicates that the file is located within a directory named data within the current working directory.
If a filename does not have a full directory component (i.e. it does not start with / or C: on Windows), it is said to be
relative.
Why is understanding absolute and relative paths important? - (2)
so that you understand where your program will look for files (when you are reading data in) and write files out (when you save data, figures etc out).
Understanding absolute and relative paths is important for determining where files will be located or saved when working with programs.
Explain the rationale behind using os.getcwd() in Python scripts. than %cwd? - (2)
os.getcwd() is preferred in Python scripts for retrieving the current working directory due to its portability and consistency across different environments.
Unlike %cwd, which is specific to Colab and may not work in other environments, os.getcwd() is a standard Python library function that works reliably across various platforms
What function can you use within a Python script to find the current working directory? - (2)
Within a Python script, you can use the os.getcwd() function to find the current working directory.
This function returns a string representing the current directory path.
How can you change the current working directory within a Python script? - (2)
You can change the current working directory within a Python script using the os.chdir(dirname) function, where dirname is a string containing the directory path to which you wish to change.
Before using os.getcwd() or os.chdir(dirname) and os.listdir(), we have to import module called
os
What does module os provide?
provides functions for interacting with the operating system.
Explain this code:
import os
print(os.getcwd()) - (3)
The code snippet imports the os module in Python, which provides functions for interacting with the operating system.
It then uses the os.getcwd() function to retrieve the current working directory.
The output of os.getcwd() will be the current directory in which the Python script is being executed.
Explain the functionality of os.listdir().
os.listdir() is a function in Python’s os module that returns contents , by default, of the current working directory
Why is it good to use abolsute file path names?
One reason is that if your programme crashes while you are in a different directory you might not be in the place you expect when you restart it.
If, when you are reading data, you are getting errors such as “No such file or directory”, it is probably because you are using a - (2)
relative file path and are not in the correct directory.
Or you have just typed the filename wrong.
What is the function used for joining parts of a file path together?
The function used for joining parts of a file path together is os.path.join.
Why is joining parts of a file together using os.path.join() useful?
This is particularly useful if we want to open many files from the same directory
In os.path.join () we can simply
pass it as many components of the path as we have, and it will join them in the correct manner.
Explain what does code does - (4)
from os.path import join
my_dir = ‘/content/sample_data/’
my_file = ‘mnist_test.csv’
my_filename = join(my_dir, my_file)
print(my_filename)
The code snippet demonstrates the usage of the join function from the os.path module which joins together directory and file names, creating full file paths (with separators appropriate to the file system you are on).
then defines a directory path (my_dir) and a file name (my_file).
Using os.path.join, it joins the directory path and file name to create a full file path to store in variable (my_filename).
It then prints my_filename which will be: /content/sample_data/mnist_test.csv
os.path.join() can also take a
string instead of a variable
What does the provided code snippet do? - (2)
my_filename2 = join(my_dir, ‘california_housing_test.csv’)
print(my_filename2)
The code snippet combines a directory path (my_dir) with a filename (‘california_housing_test.csv’) to create a full file path (my_filename2).
The resulting file path is then printed.
What is the output of this code?
my_filename2 = join(my_dir, ‘california_housing_test.csv’)
print(my_filename2)
/content/sample_data/california_housing_test.csv
You can also pass multiple individual dictionaries to to the join
function e.g,
print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))
What does this code do? - (3)
from os.path import join
my_dir = ‘alex’
print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))
The code snippet showcases the usage of the join function from the os.path module to create a full directory path by joining together multiple individual directory names.
Starting from the root directory /home, it sequentially adds each directory name (‘alex’, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’) along with the filename ‘file.txt’.
The resulting full directory path is then printe
What is output of this code?
from os.path import join
my_dir = ‘alex’
print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))
/home/alex/ynic/presentations/teaching/pin/file.txt
What is the output of this code?
from os.path import join
base_path=’/home/pin/my_data/’
nSubjects=10 # Because what if we collect more subjects? All we have to do is change this
b=10
a=f’My favourite number is {b} ‘
print(a)
for thisSub in range(1,nSubjects+1): # The +1 is to make sure we go from 1 to 10 inclusive
fileName = f”S{thisSub:02}.txt”
print(join(base_path,fileName))
/home/pin/my_data/S01.txt
/home/pin/my_data/S02.txt
/home/pin/my_data/S03.txt
/home/pin/my_data/S04.txt
/home/pin/my_data/S05.txt
/home/pin/my_data/S06.txt
/home/pin/my_data/S07.txt
/home/pin/my_data/S08.txt
/home/pin/my_data/S09.txt
/home/pin/my_data/S10.txt
Comma-separated value (CSV) files are - (2)
plain-text files (meaning you can open them in a normal text editor and look at the data) where data items are separated by commas and where new sets of fields are placed on different lines (by means of a new-line character).
They are easy to understand.
Example of CSV files
Wade,Alex,49
Smith,Joe,21
Doe,Jane, 23
West,Mae,29
CSV files are common and can be
exported from spreadsheet software and are easy to read and write in just about all programming languages.
What does the CSV module in Python facilitate? - (2)
The CSV module in Python facilitates the reading and writing of data from and to CSV (Comma-Separated Value) files.
It provides functions specifically designed to handle CSV file operations efficiently.
How to import CSV module in python?
Type:
import csv
What are the 3 modules that have in built CSV readers?
- Pandas
- Numpy
- Python CSV module
Explain this code - (6) that opens the entire CSV file
import csv
: Imports the CSV module, allowing us to work with CSV files.
- ##
with open('/content/sample_data/california_housing_test.csv', 'r') as csvfile:
: Opens the CSV file in read mode (‘r’). The file path is provided in absolute format. -
reader = csv.reader(csvfile, delimiter=',')
: Creates a CSV reader object namedreader
. - The
delimiter=','
argument specifies that fields in the CSV file are separated by commas. -
for row in reader:
: Iterates through each row in the CSV file -
print(', '.join(row))
: Joins the items in the current row with commas and prints them
What is PANDAS?
a Python module designed for reading in and processing data tables, it introduces a new data type called DataFrame
Pandas is the most common and easiest way to
load in and process .CSV files
Example of reading in csv folder in pandas:
How about the average?
Explain this code - (3):
import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)
housingTable.latitude
averageLatitude=housingTable.latitude.mean()
print(f’Mean latitude={averageLatitude:3.3f}’)
This Python code imports the Pandas library as ‘pd’ and reads a CSV file named ‘california_housing_test.csv’ located in the ‘/content/sample_data/’ directory.
The data from the CSV file is loaded into a Pandas DataFrame named ‘housingTable’.
Then, it calculates the mean latitude from the ‘latitude’ column of the DataFrame using the mean() function and prints it with 3 minium width (of entire string) and to 3 DP
You can also convert dataframe (pandas) to something you are comfortable with like - (3)
a list
e.g., import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)
housingList = housingTable.values.tolist()
How about the average?
Explain what this code does - (6)
import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)
housingTable.latitude
print(f’Mean lat: {housingTable.latitude.mean():3.3f}’)
housingList = housingTable.values.tolist()
latitude=housingTable[‘latitude’].tolist()
The code imports the Pandas library under the alias pd.
It reads a CSV file named california_housing_test.csv located in the specified path /content/sample_data/ into a Pandas DataFrame named housingTable.
It accesses the latitude column of the housingTable DataFrame.
It calculates the mean of the latitude column using the mean() method and prints it with prints it with 3 minium width (entire string) and to three decimal places.
It converts the DataFrame housingTable into a list of lists using the values.tolist() method and stores it in housingList.
It extracts all values from the latitude column of the housingTable DataFrame and converts them into a list stored in the variable latitude.
import pandas as pd
data = pd.read_csv(“/content/sample_data/california_housing_test.csv”)
print(data.head())
This code aims to read a CSV file using pandas.
What is the purpose of the head() method, and why is it used in this context? - (2)
The purpose of the head() method in pandas is to display the first few rows of the DataFrame.
It provides a quick overview of the data structure and its contents, helping users understand the data better.
Q1:
import pandas as pd
df = pd.read_csv(“content/sample_data/california_housing_test.csv”)
print(df.head())
Something is wrong with the following code. Explain what is wrong - and why.
The path name is missing a leading slash to indicate that it starts at the root.
To convert from celsius to fahrenheit you multiply by 9/5 and add 32. What is wrong with the following code? How might you fix it?
Note - there are two potential issues here - try to make the conversion as accurate as possible. - (2)
First, the list is made of strings but you are trying to multiply them by a number.
Second, you append ‘C’ not ‘F’ to the list so you never store the Fahrenheit value –> So, The code indeed appends the original Celsius value (C) to the list instead of the calculated Fahrenheit value (F), so it doesn’t store the converted Fahrenheit temperatures.
Password hell. What is the matter with this code?
The input statement is not in the loop so if you get it wrong once, you enter an infinite loop.
s = “Python_Data_Science”
words = s.split(‘-‘)
print(words)
I’m trying to split the string ‘s’ into individual words. What is going wrong?
It’s splitting on a hyphen (-) but the string has underscores in it (_)
Q3.5
I’m trying to read in a file using the Python csv reader. I think I almost have it but it doesn’t quite work…
Can you see what is wrong?
You should parse each row in csv_reader. csv_file does not exist
Broadly, what are the two types of errors in programming? - (2)
- Errors that stop you running the code (‘syntax errors’) - These are often easy to spot. These days the editor will usually show you where they are.
- Errors that happen while you are running the code - These are the ones that keep you up at night. Some of them crash the programme. That is good! The other ones just do the wrong thing but don’t throw an error. That is bad! -runtime errors
Provide an example of syntax error - (2)
print(‘Welcome to the programming course!)
Unterminated string literal
Example of an error that only pops up when you are running your code - (3)
myNum = int(input(‘Enter a number’))
Giving input as string instead of a number
Running this code will produce an ValueError exeception as Python does not know what ‘ten’ is
What is ValueError exception in Python?
A ValueError exception occurs in Python when a function expects a certain type of input, such as a string or a number, but the actual value provided is not valid or appropriate for that type.
What is an exception?
An error that occurs while the code is running.
What does a traceback in Python indicate? - (2)
traceback in Python indicates that an exception has occurred during the program’s execution.
It provides information about where the exception happened in the code, often marked by a little arrow or a message like ‘An error occurred on line xx’.
The exact line number in your traceback may differ depending on how you have structured your script, but the
message will be similar.
What does the error message “Invalid literal for int() with base 10” mean? - (2)
This error message indicates that Python attempted to convert a string into an integer (of base 10 – normal decimal numbers), but the string doesn’t resemble a number.
This is not something which can be done, so Python raises an ValueError exception
Describe in more detail about the try and except blocks
try means that we will attempt the code within the block and, if an exception is found, we will move to the except block (or blocks).
Describe the purpose of the try-except block in the provided example - (2)
The try-except block attempts to convert user input into an integer.
If a ValueError exception occurs (if the input is not a number), the except block handles it by printing a message and the exception itself (e is returned as the exception)
What is the output of this code - if input is ‘hi’
Note when an exception is caught and handled using a try-except block, we do not get a - (2)
Note that we no longer get a full traceback.
Instead, it executes the code in the except block, which typically includes a message and the error message itself (ValueError exception) and the programme stops but critically it does not crash.
How to extend this code in which we should just ask again until the user gives us something sensible.
You can use try and except blocks if you suspect code may
crash
What is output of the code if i my input is hi then hi then 9?
How can you handle multiple potential errors using except blocks in Python?
You can handle multiple potential errors by including multiple except blocks, each corresponding to a specific type of error.
Explain this code - (8)
This code prompts the user to input a number to calculate its reciprocal. It begins by setting recip
to None
, indicating that no valid reciprocal has been calculated yet.
The while
loop continues until a valid reciprocal is calculated.
Within the loop, the try
block attempts to convert the user input into an integer and calculate the reciprocal.
If the user provides a non-integer input (e.g., a string), a ValueError
is raised, and the program prints “Please enter a valid integer.” The program then re-prompts the user for input.
If the user attempts to divide by zero, a ZeroDivisionError
is raised, and the program prints “Cannot divide by zero. Please enter a non-zero number.”
Only when the user provides a valid integer input will the code proceed to attempt the calculation of the reciprocal.
Once a valid non-zero integer is entered, the reciprocal is calculated, and the loop exits.
Finally, the calculated reciprocal is displayed with three decimal places using f-string formatting.
What is output of the code if i give 0,0 then ten?
Explain what happens to the code when i give 0 as input? - (5)
You input 0 when prompted.
The program attempts to calculate the reciprocal, which is 1 divided by the input number (0).
Division by zero occurs, triggering the ZeroDivisionError.
The program executes the corresponding except ZeroDivisionError block, printing “Cannot divide by zero. Please enter a non-zero number.”
The loop continues, prompting you to input another number.
Until you input a non-zero number, the program will keep repeating this process, not proceeding to calculate the reciprocal until valid input is provided.
Explain what happens to the code if give ‘ten’ (as string) as user input? - (6)
You input ‘ten’ when prompted.
The program attempts to convert the input into an integer using int(‘ten’).
Since ‘ten’ cannot be converted into an integer, a ValueError occurs.
The program executes the corresponding except ValueError block, printing “Please enter a valid integer.”
The loop continues, prompting you to input another number.
Until you input a valid integer, the program will keep repeating this process, not proceeding to calculate the reciprocal until valid input is provided.
What happens if the try block fails in the provided code?
If the try block fails, the variable recip will remain as ‘None’, as indicated by the comment: “# Here is the place where we try to get an input. Note that if it fails, start will stay as ‘None’.”
What are functions? - (3)
Functions are bits of code that take arguments (parameters), perform operations with them, and optionally return values.
unctions allow code to be written and reused cleanly.
Once a function is defined for a specific task, it can be used multiple times throughout the program.
Can funcions be changed together?
Yes e.g.,, print(list(range(5)))
Explain the code (example of chaining functions together):
print(list(range(5))) - (3)
In the example given, the return value from the range() function is passed to list() which casts the return value from range() into a list.
Subsequently, the resulting list is passed as an argument to the print() function, which then prints the list.
In each case, the return value from the innermost function becomes the argument to the next function.
Functions in Python can return multiple values either as a
tuple (single variable) or break them out into separate variables:
Provide an example of a function that returns multiple values.
divmod() function,
What does divmod () function return?
returns the integer division of a number as well as its modulus (remaineder) when an integer is divided by another integer
For example,
whatt would divmod (5,2) return?
we will get the numbers 2 (integer division), remainder 1.
For divmod(5, 2), we will get the numbers 2 (integer division), remainder 1. We can either - (2)
take these return values into a single variable as a tupe
or expand the values out into multiple variables
Example of just printing the return value of divmod
print(divmod(5, 2))
Example of sttoring the return value of divmod(5,2) into a single variable
Code:
ret = divmod(5,2)
print(“ret is “, ret)
Output
ret is (2,1)
Example of storing return value of divmod(5,2) into 2 variables:
Code:
d,r = divmod(5,2)
print(“d is:”, d)
print(“r is:”, r)
Output
d is : 2
r is: 1
Describe the purpose of the code: d, r = divmod(5, 2) - (2)
The function returns a tuple containing two values: the he integer division (quotient) and the remainder from integer division of integer 5 divided by integer 2 which is 2,1
These returned values are directly assigned to the variables d and r, respectively, and then printed.
Explain what the following code does: ret = divmod(5, 2). - (2)
his code calls the divmod() function with arguments 5 and 2, which returns a tuple containing the quotient (integer division) and the remainder of dividing 5 by 2.
Returns these two values into a tuple and then stored into variable called ‘ret’
What are the two types of functions? - (2)
- ‘Standalone’ functions
- ‘Member’ functions
What are ‘standalone’ functions?
functions that take all of their arguments in the parameters.
Example of ‘standalone’ functions
range, type and print.
What are ‘Member’ functions, and why are they called that?
Member’ functions are functions that are “bound” to a specific object.
Why are ‘member’ functions called ‘member’ functions? - (2)
They are called ‘Member’ functions because they are part of the object (i.e., variable) on which they are called,
e.g., or instance, .append() is automatically part of any list variable which you create
How can you see all the member functions of an object in Python?
You can use the dir() function, passing the object (i.e., variable) as an argument.
Explain the purpose of the code:
my_var = [1, 2, 3]
print(dir(my_var)).
This code initializes a list variable my_var with values [1, 2, 3], and then uses the dir() function to display all the member functions associated with the list object my_var
Explain the output of this code - what do underscores
my_var = [1, 2, 3]
print(dir(my_var))
In addition to the ‘private methods’ (indicated with underscores - we are not supposed to use them), we can see our old friend append - along with other methods which we talked about including index and pop.
Structure of member funciton
VARIABLENAME.FUNCTIONAME()
TThe idea of a member function is tha it will affect the variable it is a part of so append will
cause the list to have additional items added to it
What is the difference between normal and member functions? - (4)
When you call normal functions don’t need to specifcy the data structure - They are called by specifying the function name followed by parentheses and passing arguments inside the parentheses.
With member funcions, you mustt provide the data structure and they operate on the data contained within that object.
n Python, for example, when we call append() on a list (my_list.append(4)), append() is a member function because it operates specifically on the list object my_list and modifies it directly.
However, when we call print(my_list), print() is a normal function because it’s a built-in function that is not associated with any specific object.
Many Python editors will help you out by ‘prompting’ you with possible member functions when you are writing code. For example, after defining a = [1,2,3,4….1]
writing a. , Colab will provide a little ‘menu’ of all the member functions (purple boxes) avaliable to you - can do this instead of using dir
Python has a concept of collections of functions which are called
modules
Describe the purpose of the random module in Python - (2)
The random module in Python is part of the standard library and provides functions for working with random numbers.
It offers various functionalities for generating random numbers, shuffling sequences, and many more
Explain the process of importing modules in Python and accessing their content - (2)
To use a module in Python, you first need to import it using the import keyword.
In environments like Spyder, iPython3, and Colab, after importing a module, you can type the module name followed by a dot (.) and then press the tab key (or wait) to get a list of available content within that module.
What does this code do? - (2)
import random
print(dir(random))
First, the random module is imported using the import keyword
Then, the dir() function is used on random module to list all its associated functions and is outputted using print()
Output of this code
import random
print(dir(random)
is shuffle one of the functions in random module?
Yes
What is the shuffle function in random module used?
This function is used to randomise the order of a list -
Why is shuffle important? - (2)
We do this in experiments quite a bit:
For example, when putting stimuli on a screen it’s often important to randomise the order so that the subject can’t tell what is coming next
Explain the code snippet - (5)
After importing the random module, a list a containing integers [1, 2, 3, 4] is defined. T
The original order of the list is printed using the print() function.
Next, the shuffle() function is called on the list a, which randomizes the order of its elements in the list.
The shuffled list is printed using the print() function to display the new order.
Finally, the shuffle() function is called again on the same list a, further randomizing its order of elements in that list, and the shuffled list is printed once more.
What would be the possible output of this code snippet?
How to produce a list storing in variable a from values 0 to 100 inclusive.
a = list(range(101)
We call the function as random.shuffle because we
imported the shuffle module using import random and the function is “inside” the module.
Describe the purpose and behavior of the randint() function in the random module - (3)
he randint() function in the random module generates a random integer between two specified numbers.
It takes two arguments representing the lower and upper bounds of the range, inclusively.
When called, randint() returns a random integer within this range.
Explain how random.randint() is used to generate random integers between 1 and 5 inclusively in the provided code snippet - (3)
In the code snippet, the random.randint() function is called multiple times, each time with arguments (1, 5).
This specifies the range from which the random integer should be generated, starting from 1 and ending at 5, inclusive.
Therefore, each call to random.randint(1, 5) produces a random integer between 1 and 5, with the possibility of including both endpoints.
While both shuffle() and randint() are functions in the random module, they serve different purposes. - (2)
shuffle() rearranges the elements of a list in a random order, effectively shuffling its contents.
randint() generates a single random integer within a specified range, inclusive of both endpoints.
Describe how to create a loop to generate 100 random numbers between 1 and 10 using Python - (4)
To achieve this, import the random module.
Then, utilize a for loop to iterate 100 times using the range() function.
Within the loop, call random.randint(1, 10) to generate a random integer between 1 and 10 on each iteration and store into variable random_num
Print each generated number to output console by printing random_num
How to import numpy?
Using the same method as before we did with random
What is numpy module in Python?
a module for processing numbers.
To avoid some typing, we can use a feature in Python ‘as’ keyword which allows us to rename the module as we imprt it:
import numpy as np # This is always how people name numpy when they import it.
print(dir(np))
Describe the advantages of using aliases when importing modules in Python. - (2)
Importing modules with aliases, such as import numpy as np, offers several benefits.
It reduces typing effort, enhances code readability by shortening module names, and promotes cleaner code appearance.
By using the import MODULE as SHORTNAME variant, we
import numpy in exactly the same way as before, but we make its contents available as np.SOMETHING instead of numpy.SOMETHING.
Importing numpy as ‘np’ has also become the common
convention in most scientific code.
We should note that modules can have modules within them - (2)
e.g.,
Numpy module has a random module called numpy.random
Distinct from main Python random module and has different functions inside it e.g,:
What does as keyword do in Python?
It’s commonly used in import statements to provide an alternative name for a module or to shorten the module name for brevity and readability.
Explain this code - (2)
The code imports the NumPy library as np (using ‘as’ keyword) and then prints the contents of the numpy.random submodule using the dir() function.
This allows users to explore the available functions and attributes within the numpy.random submodule.
One other form of import which you may come across is used if you only want a - (2)
few functions or classes from a module and would rather that they have short names
e.g., from numpy import zeros, ones
Explain the code snippet - (3)
This code snippet imports the zeros and ones functions from the numpy module.
The print(type(zeros)) line confirms that the zeros function has been imported, displaying its type as <class ‘function’>.
Finally, print(zeros(10)) calls the zeros function to create an array of size 10 filled with zeros, which is then printed to the console.
What is the output of this code?
What do the zeros and ones functions do?
These functions, imported from the numpy module, create arrays filled with zeros and ones respectively.
Produce a code that prints out of one-dimensional array of ones with size 10 - (2)
from numpy import zeros, ones
print(ones(10))
What is going to be the output of this code?
from numpy import zeros, ones
print(ones(10))
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
Explain the code snippet. - (3)
he code imports the zeros and ones functions from the NumPy module.
Then, it prints a 1-D array of ones with length 10 using ones(10).
Additionally, it prints a 2-D array of ones with dimensions 10x10 using ones((10,10)).
Arrays can be
1D or 2D or 3D
What is output of this code snippet?
When we import it in this way:
e.g., from numpy import zeros, ones
we just use the names that we import without any module name prefixing.
When do I import things? - (2)
Import modules **at the top of your script, not halfway through it.
Putting imports at the top of your script allows the reader to get an idea of what sort of functionality will be used and is considered good practice.
What would print(ones((10,10,10))) print to output console/terminal? - (2)
be a 3D array filled with ones, with dimensions 10x10x10. Each element of the array would be a 1.
10 lots of these: (image)
You can also produce your own functions using
def
What is the syntax for defining a function in Python? - (2)
In Python, the syntax for defining a function involves using the def keyword followed by the function name and parentheses containing any parameters.
The body of the function is indented and contains the code to be executed.
Explain this code - (5)
defines a function named printNTimes that takes two parameters: my_string, which represents the string to be printed, and n, which represents the number of times the string should be printed.
Inside the function, a for loop iterates over the range from 0 to n-1.
During each iteration, the value of my_string is printed to the console.
So, when you call this function with a string and a number n, it will print the string n times.
However, this function been defined but have not called printNTimes function so there is no output
What is the output of this code?
(Nothing)
Why is the output nothing when you run the code? - (3)
No output appears because the function printNTimes is defined but not called with specific arguments.
To execute its instructions, you need to call the function with a string (my_string) and a number (n).
e.g., printNTimes(‘hello world’ ,9)
This function takes two arguements (my_string, n) which you must supply otherwise
the function will fail- TypeError
What happens when you try to call the function printNTimes() without any arguments?
Calling the function printNTimes() without providing the required arguments (my_string and n) will result in a TypeError because the function expects two arguments but none were provided.
What is the output if we call function printNTimes: printNTimes (‘:)’,5)
Def functions are useful for
doing things again and again without replicating code for
Functions do things (i.e., execute tasks/code) and they also (usually) ‘return’
one or more values
Example of def function returning values
Explain the code and its output - (3)
def square(x):
y=x*x
return(y)
answer=square(5)
print(answer)
The square function takes an argument x and calculates the square of this input number.
It stores the result in the variable y and returns it. In the code snippet, square(5) is called, computing the square of 5, resulting in 25.
This value is stored in the variable answer, which is then printed, producing the output: 25.
What does the code print(‘#’*n) accomplish, given n=100?
It prints 100 hashtags in a row.
Explain the purpose of the def function: def print_underline(inputString,underlineCharacter)
This function, print_underline, takes two arguments: inputString and underlineCharacter.
It calculates the length of inputString using the len() function and stores it in the variable stringLength.
Then, it prints inputString, followed by an underline made of underlineCharacter repeated for the length of inputString.
Finally, it returns the length of the inputString
What would be output if print_underline was given inputString as ‘Hello World’ and underlineCharacter of ‘#’ and then:
my_value = print_underline(‘Hello World’, ‘#’)
print(f’Length is {my_value}’)
Hello World
###########
Length is 11
For larger scale data analysis (usually with neuroimagning data) we can use pre-existing modules and core tool for this in Python is
numpy
Numpy works with
large blocks of numbers called ‘matrices’ (or sometimes ‘arrays’)
Matrices are often rectangular blocks that are
stored as rows x columns
Matrices are often rectangular blocks that are stored as rows x columns.
For instance:
3 rows by 2 columns so it would have shape (3, 2).
The order of the dimensions of matrices is always
(rows, columns).
For most of the time we will be working with 2D matrices, however numpy will cope with any number of dimension from
(from 1D up to any number of dimensions).
Matrices are usually two-dimensional whereas arrays can be
have any number of dimensions
when performing addition, subtraction, multiplication, or division on matrices, they must be of
he same size, meaning they must have the same number of rows and columns.