Session 4 - Part 1 Flashcards

1
Q

Broadly, what are the two types of errors in programming? - (2)

A
  1. 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.
  2. 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Provide an example of syntax error - (2)

A

print(‘Welcome to the programming course!)

Unterminated string literal

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

What are syntax errors in programming?

A

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

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

Example of an error that only pops up when you are running your code - (3)

A

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

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

What is ValueError exception in Python?

A

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.

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

Another example of ValueError exception:

A

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.

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

What is an exception?

A

An error that occurs while the code is running.

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

What does a traceback in Python indicate? - (2)

A

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

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

Whenever you get a traceback from Python, it means that something

A

unexpected has happened in your program.

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

The exact line number in your traceback may differ depending on how you have structured your script, but the

A

message will be similar.

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

If you are running the script in Spyder, the traceback will be in red. In Colab it will have a

A

variety of colours.

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

How should tracebacks be typically read in Python? - (2)

A

Tracebacks should generally be read from bottom to top.

e.g., Value Error: invalid literal (i.e., thingy) for int() for base 10: ‘ten’

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

In this traceback, it has given

A

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

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

What does the error message “Invalid literal for int() with base 10” mean? - (2)

A

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

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

What is this error message “Invalid literal for int() with base 10” due to?

A

Users often provide unexpected inputs, leading to exceptions.

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

Why write dumb code? (code that is simple and logical) - (2)

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

To deal with an exception we can use the

A

try and except keywords

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

Describe in more detail about the try and except blocks

A

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

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

Describe the purpose of the try-except block in the provided example - (2)

A

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)

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

What is the output of this code - if input is ‘hi’

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

Note when an exception is caught and handled using a try-except block, we do not get a - (2)

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How to extend this code in which we should just ask again until the user gives us something sensible.

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

You can use try and except blocks if you suspect code may

A

crash

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

Explain this code - (7)

A

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.

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

What is output of the code if i my input is hi then hi then 9?

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

How can you handle multiple potential errors using except blocks in Python?

A

You can handle multiple potential errors by including multiple except blocks, each corresponding to a specific type of error.

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

What is ZeroDivisionError in Python?

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

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

A

“Try to add a non-zero number” or “Cannot have divide by zero”

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

Explain this code - (8)

A

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.

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

What is output of the code if i give 0,0 then ten?

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

Explain what happens to the code when i give 0 as input? - (5)

A

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.

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

Explain what happens to the code if give ‘ten’ (as string) as user input? - (6)

A

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.

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

What happens if the try block fails in the provided code?

A

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

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

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)

A

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.

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

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.

A

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

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

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:

A

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

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

What are functions? - (3)

A

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.

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

Can funcions be changed together?

A

Yes e.g.,, print(list(range(5)))

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

Explain the concept of chaining funcitons together

A

Chaining functions involves passing the return value of the intermost function that vecomes an arguement to the next function

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

Explain the code (example of chaining functions together):

print(list(range(5))) - (3)

A

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.

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

What is the output of the code going to be?

print(list(range(5)))

A

[0,1,2,3,4]

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

Can functions someitmes return more than one value?

A

yes

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

Functions in Python can return multiple values either as a

A

tuple (single variable) or break them out into separate variables:

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

Provide an example of a function that returns multiple values.

A

divmod() function,

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

What does divmod () function return?

A

returns the integer division of a number as well as its modulus (remaineder) when an integer is divided by another integer

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

For example,

whatt would divmod (5,2) return?

A

we will get the numbers 2 (integer division), remainder 1.

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

For divmod(5, 2), we will get the numbers 2 (integer division), remainder 1. We can either - (2)

A

take these return values into a single variable as a tupe

or expand the values out into multiple variables

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

Example of just printing the return value of divmod

A

print(divmod(5, 2))

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

Example of sttoring the return value of divmod(5,2) into a single variable

A

Code:

ret = divmod(5,2)
print(“ret is “, ret)

Output
ret is (2,1)

50
Q

Example of storing return value of divmod(5,2) into 2 variables:

A

Code:

d,r = divmod(5,2)
print(“d is:”, d)
print(“r is:”, r)

Output
d is : 2
r is: 1

51
Q

Describe the purpose of the code: d, r = divmod(5, 2) - (2)

A

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.

52
Q

Explain what the following code does: ret = divmod(5, 2). - (2)

A

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’

53
Q

What are the two types of functions? - (2)

A
  1. ‘Standalone’ functions
  2. ‘Member’ functions
54
Q

What are ‘standalone’ functions?

A

functions that take all of their arguments in the parameters.

55
Q

Example of ‘standalone’ functions

A

range, type and print.

56
Q

What are ‘Member’ functions, and why are they called that?

A

Member’ functions are functions that are “bound” to a specific object.

57
Q

Why are ‘member’ functions called ‘member’ functions? - (2)

A

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

58
Q

How can you see all the member functions of an object in Python?

A

You can use the dir() function, passing the object (i.e., variable) as an argument.

59
Q

Explain the purpose of the code:
my_var = [1, 2, 3]
print(dir(my_var)).

A

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

60
Q

Explain the output of this code - what do underscores

my_var = [1, 2, 3]

print(dir(my_var))

A

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.

61
Q

Structure of member funciton

A

VARIABLENAME.FUNCTIONAME()

62
Q

TThe idea of a member function is tha it will affect the variable it is a part of so append will

A

cause the list to have additional items added to it

63
Q

Explain the purpose of the code - (4)

my_list = [1, 3, 4]

my_list.append(4)

print(my_list)

print(my_list.count(4))

A

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.

64
Q

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

A

[1, 3, 4, 4]
2

65
Q

What is the difference between normal and member functions? - (4)

A

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.

66
Q

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

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

67
Q

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

A

Length of a is 11,Once sorted a is [1, 1, 1, 2, 3, 4, 4, 6, 7, 8, 99]

68
Q

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]

A

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

69
Q

Python has a concept of collections of functions which are called

A

modules

70
Q

There are a large number of modules which come with Python. These include things such as - (2)

A

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.

71
Q

Describe the purpose of the random module in Python - (2)

A

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

72
Q

Explain the process of importing modules in Python and accessing their content - (2)

A

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.

73
Q

What does this code do? - (2)

import random

print(dir(random))

A

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

74
Q

Output of this code

import random
print(dir(random)

A
75
Q

is shuffle one of the functions in random module?

A

Yes

76
Q

What is the shuffle function in random module used?

A

This function is used to randomise the order of a list -

77
Q

Why is shuffle important? - (2)

A

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

78
Q

Explain the code snippet - (5)

A

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.

79
Q

What would be the possible output of this code snippet?

A
80
Q

How to produce a list storing in variable a from values 0 to 100 inclusive.

A

a = list(range(101)

81
Q

We call the function as random.shuffle because we

A

imported the shuffle module using import random and the function is “inside” the module.

82
Q

Describe the purpose and behavior of the randint() function in the random module - (3)

A

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.

83
Q

Explain how random.randint() is used to generate random integers between 1 and 5 inclusively in the provided code snippet - (3)

A

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.

84
Q

While both shuffle() and randint() are functions in the random module, they serve different purposes. - (2)

A

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.

85
Q

Describe how to create a loop to generate 100 random numbers between 1 and 10 using Python - (4)

A

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

86
Q

How to import numpy?

A

Using the same method as before we did with random

87
Q

What is numpy module in Python?

A

a module for processing numbers.

88
Q

To avoid some typing, we can use a feature in Python ‘as’ keyword which allows us to rename the module as we imprt it:

A

import numpy as np # This is always how people name numpy when they import it.

print(dir(np))

89
Q

Describe the advantages of using aliases when importing modules in Python. - (2)

A

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.

90
Q

By using the import MODULE as SHORTNAME variant, we

A

import numpy in exactly the same way as before, but we make its contents available as np.SOMETHING instead of numpy.SOMETHING.

91
Q

Importing numpy as ‘np’ has also become the common

A

convention in most scientific code.

92
Q

We should note that modules can have modules within them - (2)

e.g.,

A

Numpy module has a random module called numpy.random

Distinct from main Python random module and has different functions inside it e.g,:

93
Q

What does as keyword do in Python?

A

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.

94
Q

Explain this code - (2)

A

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.

95
Q

One other form of import which you may come across is used if you only want a - (2)

A

few functions or classes from a module and would rather that they have short names

e.g., from numpy import zeros, ones

96
Q

Explain the code snippet - (3)

A

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.

97
Q

What is the output of this code?

A
98
Q

What do the zeros and ones functions do?

A

These functions, imported from the numpy module, create arrays filled with zeros and ones respectively.

99
Q

Produce a code that prints out of one-dimensional array of ones with size 10 - (2)

A

from numpy import zeros, ones

print(ones(10))

100
Q

What is going to be the output of this code?

from numpy import zeros, ones

print(ones(10))

A

[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

101
Q

Explain the code snippet. - (3)

A

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

102
Q

Arrays can be

A

1D or 2D or 3D

103
Q

What is output of this code snippet?

A
104
Q

When we import it in this way:

e.g., from numpy import zeros, ones

A

we just use the names that we import without any module name prefixing.

105
Q

When do I import things? - (2)

A

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.

106
Q

What would print(ones((10,10,10))) print to output console/terminal? - (2)

A

be a 3D array filled with ones, with dimensions 10x10x10. Each element of the array would be a 1.

10 lots of these: (image)

107
Q

You can also produce your own functions using

A

def

108
Q

What is the syntax for defining a function in Python? - (2)

A

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.

109
Q

Explain this code - (5)

A

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

110
Q

What is the output of this code?

A

(Nothing)

111
Q

Why is the output nothing when you run the code? - (3)

A

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)

112
Q

This function takes two arguements (my_string, n) which you must supply otherwise

A

the function will fail- TypeError

113
Q

What happens when you try to call the function printNTimes() without any arguments?

A

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.

114
Q

What is the output if we call function printNTimes: printNTimes (‘:)’,5)

A
115
Q

Def functions are useful for

A

doing things again and again without replicating code for

116
Q

Functions do things (i.e., execute tasks/code) and they also (usually) ‘return’

A

one or more values

117
Q

Example of def function returning values

A
118
Q

Explain the code and its output - (3)

def square(x):
y=x*x
return(y)

answer=square(5)
print(answer)

A

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.

119
Q

What does the code print(‘#’*n) accomplish, given n=100?

A

It prints 100 hashtags in a row.

120
Q

Explain the purpose of the def function: def print_underline(inputString,underlineCharacter)

A

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

121
Q

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

A

Hello World
###########
Length is 11