4.5 Exercises#
Exercise 1: Dot notation and basic methods#
Use at least two methods (e.g., .append()
, .sort()
) on the provided list. Print the list before and after using the methods.
my_list = [3,1,4,6,1,7]
Exercise 2: Everything is an object#
All data types and structures (like integers or lists) in Python are objects.
Print all methods associated with the previously created list.
Are the methods different from the methods associated with dictionaries?
# Exercise 2
Exercise 3: Modules and imports#
Python has a small built-in namespace, which means there is only a limited amount of functions available by default. To access a wide range of functions and tools, we thus need to import additional modules and libraries. Please do the following:
Importing Entire Modules:
Import the entire
math
module.Calculate and print the natural logarithm of 20.
Importing Specific Functions:
Import only the
pow
function from themath
module.Calculate and print 2 raised to the power of 3 (\(2^3\)).
Using Aliases for Modules:
Import the
numpy
module using the aliasnp
.Create a numpy array with the values [1, 4, 9, 16, 25].
Calculate and print the square root of each element in the array using the numpy module.
Hint: The numpy module is the fundamental Python package for scientific computing in Python. It uses arrays to store data. Please refer to the documentation for the third question. Do not worry about the details, we will discuss this package in more detail next week.
# Exercise 3
Exercise 4: Functions#
Write a function classify_reaction_time(rt)
that classifies a given reaction time (in ms) of a psychological experiment and returns the result as a string:
Below 400 ms: “Fast Response”
Between 400 ms and 600 ms: “Normal Response”
Above 600 ms: “Slow Response”
Use flow control statements (if, elif, else) to handle the classification.
Test the function by passing three different response times (fast, normal, slow) to it and printing the result
# Exercise 4
Exercise 5: More functions#
Create a function that takes in the radius of a circle and returns its area.
Run the function by providing a radius and print the resulting area.
# Exercise 5
Exercise 6: Classes#
Functions are nice if you need to perform a specific, isolated computation. However, sometimes it is uesful to create encapsulate objects that have different properties (attributes) and actions (methods). For example, look at the provided code snippet.
An instance of Circle
is created by providing a radius: my_circle = Circle(radius=5)
. This radius is then assigned to the self.radius
attribute of the class. The only method in the class is the calculate_area()
method that (if called) calculates the area of the circle, assigns it to a newly created self.area
attribute.
Please do the following:
In
Circle
, implement a second method that calculates the circumference of the circle. Calculate and ürint the circumference.Implement a new class called
Square
that has a single attribute.side
, and two methods for area and circumference. Calculate and print both.
from math import pi
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
self.area = pi * self.radius**2
# Create an instance of the Circle class and calculate the area and circumference
my_circle = Circle(radius=5)
my_circle.calculate_area()
print(f"The area of the circle is: : {my_circle.area}")
The area of the circle is: : 78.53981633974483
Voluntary Exercise 1: Nested functions#
In this exercise, you will create functions that simulate a participant’s decision-making process during a psychological experiment. The goal is to reinforce defining and using functions, handling parameters, and using control flow.
Creating a Decision Function
Write a function
make_decision(response_time, threshold)
that takes two arguments:response_time
: The time (in milliseconds) it takes for the participant to make a decision (an integer).threshold
: The decision threshold (an integer).
The function should:
Print “Decision Made!” if
response_time
is less than or equal to the threshold.Print “Too Slow! No Decision.” if
response_time
is greater than the threshold.
Simulating a Reaction Time Task
Create a function
simulate_reaction_task(mean_rt, variability)
that simulates a participant’s response time:mean_rt
: The average response time (an integer).variability
: The maximum amount by which the response time can vary (an integer).
The function should:
Use a random number generator (from the
random
module) to create a response time by adding a random value (between-variability
and+variability
) tomean_rt
.Return the generated
response_time
.
Running the Simulation
Create a main function
run_experiment()
that:Sets a
mean_rt
of 500 ms and a variability of 100 ms.Sets a
threshold
of 550 ms.Calls
simulate_reaction_task()
three times to generate three different response times.Calls
make_decision()
for each response time to determine if a decision was made.Prints the response times and the decision outcomes.
# Voluntary Exercise 1
Voluntrary Exercise 2: Classes and inheritance#
In this exercise, you will create a class that simulates a simple neuron. The neuron will allow energy deposits (representing excitatory input), energy reductions (representing inhibitory input), and checking its activation level.
Create the class
Write a class
Neuron
with the following attributes:neuron_name
: The name of the neuron (e.g., “Neuron A”).activation_level
: The current activation level (default is 0).
Implement the following methods:
excite(amount)
: Adds amount to the activation_level (representing excitatory input).inhibit(amount)
: Subtracts amount from the activation_level (representing inhibitory input). If the activation level becomes negative, set it to 0 and print a message indicating that the neuron has reached its inhibitory limit.check_activation()
: Prints the current activation level.
Test the class
Create an instance of
Neuron
for a neuron named “Neuron A” with an initial activation level of 20. Apply an excitatory input of 30, then apply an inhibitory input of 70. Print the final activation level.
# Voluntary Exercise 2
In object oriented programming, classes can inherit attributes or methods from an existing class (base or parent class). This allows the subclass to reuse and extend the functionality of the parent class, adding its own specialized behavior. Have a look at an online tutorial to figure out how this can be implemented.
Create a subclass
InhibitoryNeuron
that inherits from Neuron.Override the
inhibit(amount)
method such that it adds an additional 10% inhibition (e.g., if 50 is passed as the amount, it should inhibit by 55).
Test the
InhibitoryNeuron
class by creating an instance, applying excitation and inhibition, and checking the activation level.
# Voluntary Exercise 2
Voluntary Exercise 3: List comprehensions#
You learned about nested statements in previous sessions. Please carefully read the following code. What is its purpose?
random_stuff = [1, "banana", "apple", 3.14, 7, "hello"]
strings_only = [] # empty list for filtered vaues
# Loop through the list
for elem in random_stuff:
# if the current element is a string...
if isinstance(elem, str):
# ...then append the value to strings_only
strings_only.append(elem)
print(f"Only the string values: {strings_only}")
Only the string values: ['banana', 'apple', 'hello']
Python offers a feature called list comprehension. This allows you to write for-loops in a more compact way. List comprehensions are syntactic sugar, which means they do not add any additional features and are just a way of making the code a bit shorter (and maybe even nicer to read once you get used to them). Take a look at the following example which prints the elements of the random_stuff
list:
p = [print(elem) for elem in random_stuff]
1
banana
apple
3.14
7
hello
Can you implement the previous code block that filters the strings from the list by using a single list comprehension?
# Voluntary Exercise 3