Session 4 - Part 1 Flashcards
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
What are syntax errors in programming?
A syntax error occurs when the structure of the code does not conform to the rules of the programming language, making it invalid and preventing the code from being executed. - error in the way code has been written
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.
Another example of ValueError exception:
If you try to convert a string containing non-numeric characters into an integer using the int() function, like int(“abc”), Python will raise a ValueError because it can’t interpret “abc” as a valid number.
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’.
Whenever you get a traceback from Python, it means that something
unexpected has happened in your program.
The exact line number in your traceback may differ depending on how you have structured your script, but the
message will be similar.
If you are running the script in Spyder, the traceback will be in red. In Colab it will have a
variety of colours.
How should tracebacks be typically read in Python? - (2)
Tracebacks should generally be read from bottom to top.
e.g., Value Error: invalid literal (i.e., thingy) for int() for base 10: ‘ten’
In this traceback, it has given
Python gives us a hint as to both the error (ValueError: invalid literal…) and the line of code in which the error occurred (in fact it gives us both the file and line number as well as the code from the line).
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
What is this error message “Invalid literal for int() with base 10” due to?
Users often provide unexpected inputs, leading to exceptions.
Why write dumb code? (code that is simple and logical) - (2)
- Will make debugging your code easier
- You can always ask AI to make your ‘dumb code’ smarter or more optimised but if you start with ‘complex’ code then it is harder to fix it
To deal with an exception we can use the
try and except keywords
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
Explain this code - (7)
This code initializes the variable start
to data type None
, indicating that no valid value has been chosen yet by the user.
The while loop continues executing as long as start
remains None
, prompting the user for input.
Inside the loop,
the try block utilises input function to get a value from user and convert it into int().
If a ValueError occurs (indicating invalid input), it moves to except block where code inside is executed which is
an error message is printed (Not a number), and the loop continues and goes from the start again.
Once a valid integer is entered (e.g,, 1) returning to the start of the while loop.
Since start is now updated with a valid integer, it is no longer None, and the loop exits at the bottom.”, printing “Thanks!”.
This ensures the user provides a valid integer input before proceeding further.
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.
What is ZeroDivisionError in Python?
What error message would you give for the zerodivision error?
recip = None
while recip is None:
try:
divisor = int(input(‘Enter a number to divide by:’))
recip=1/divisor
except ValueError:
print(“Not a number…”)
except ZeroDivisionError:
print(xxxxxx)
print(f”The reciprocal was {recip:.3f}”)
“Try to add a non-zero number” or “Cannot have divide by zero”
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’.”
You may have a large complex problem to program which can be reduced to a set of smaller problems which you can tackle one at a time, one way to do this is by in programming is - (2)
One way to do this is to write down in short bullet points what you want to do.
Then continue to break down these points until they are all ones that you either understand, or know that you do not know how to do.
Example of :
One way to do this is to write down in short bullet points what you want to do. Then continue to break down these points until they are all ones that you either understand, or know that you do not know how to do.
As an example, we are asked to present 10 auditory stimuli in a random order and measure a reaction time at the onset of the sound.
We might write out something like this:
Build a list of our sounds
Randomise the list of our sounds
For each sound in the randomised list:
Play the sounds
Detect any key-presses during the sound
Work out what the time between the sound onset and the first keypress was
Save out the order of the sounds and the related reaction times to a file
By breaking down this auditory experiment into different elements, we can see how these convert to code by writing a set of comments based on the notes and we can fill in the code where we know it easy or write a TODO note for ourseleves or ask CHATGPT to fill it in
example:
Prepare our list of sounds
##TODO: We might want to read this from a file
listofsounds = [‘1.wav’, ‘2.wav’, ‘3.wav’, ‘4.wav’, ‘5.wav’,
‘6.wav’, ‘7.wav’, ‘8.wav’, ‘9.wav’, ‘10.wav’]
#TODO: We do not yet know how to randomise the order of a list
for sound in listofsounds:
# Play the sound
##TODO: We need to look up how to play a sound
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 concept of chaining funcitons together
Chaining functions involves passing the return value of the intermost function that vecomes an arguement to the next function
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.
What is the output of the code going to be?
print(list(range(5)))
[0,1,2,3,4]
Can functions someitmes return more than one value?
yes
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
Explain the purpose of the code - (4)
my_list = [1, 3, 4]
my_list.append(4)
print(my_list)
print(my_list.count(4))
Firstly, it creates a list my_list with initial values [1, 3, 4],
Then, it appends the value 4 to the end of the list using the append() member function, which is a member function specific to lists.
After that, it prints the modified list my_list using the normal print() function.
Finally, it prints the count of occurrences of the value 4 in the list using the count() member function, another member function specific to lists.
What will the output of this code be? - (2)
my_list = [1, 3, 4]
my_list.append(4)
print(my_list)
print(my_list.count(4))
[1, 3, 4, 4]
2
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.
Explain this code - (4)
a=[1,2,4,6,7,3,4,1,8,99,1]
l=len(a)
a.sort()
print(f”Length of a is {l},Once sorted a is {a}”)
‘a’ is a variable that contains a list of integers
len() function, which is a normal function provided by Python, to calculate the length of the list a. This length is stored in the variable
Then, we call the sort() is a member function (or method) specific to lists in Python. It sorts the elements of the list a in ascending order directly modifying the original list.
Finally, we use the print() function, another normal function provided by Python, to output the results. We print the original length of the list a (stored in l) and the sorted list a.
What is output of this code?
a=[1,2,4,6,7,3,4,1,8,99,1] # Define a list
l=len(a) # Here we use the ‘normal’ function ‘len’
a.sort() # Here we use the ‘member’ function ‘sort’
print(f”Length of a is {l},Once sorted a is {a}”)
Length of a is 11,Once sorted a is [1, 1, 1, 2, 3, 4, 4, 6, 7, 8, 99]
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
There are a large number of modules which come with Python. These include things such as - (2)
os, random, sys, time to do things like interact with the operating system, work with random numbers, do ‘system’-related stuff and work with times and dates.
There are also a large number of external modules – common ones that we will use include things like numpy (Numerical python), scipy (Scientific Python), matplotlib (Plotting library), psychopy (for stimulus presentation) and many more.
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