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))