Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

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? You can use the empty dictionary my_dict provided below to find out.

Exercise 3: Modules and imports

Python has a small built-in namespace, which means there is only a limited number 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:

  1. Importing Entire Modules:

    • Import the entire math module.

    • Calculate and print the natural logarithm of 20.

  2. Importing Specific Functions:

    • Import only the pow function from the math module.

    • Calculate and print 2 raised to the power of 3 (23).

  3. Using Aliases for Modules:

    • Import the math module using the alias m.

    • Use a for loop to calculate and print the square root of each number in the provided numbers list.

Hint: You can find an overview of all functions in the math module in the Python documentation.

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 each of the reaction times in the provided reaction_times list to it and print the results.

Exercise 5: More functions

  1. Create a function that takes in the radius of a circle and returns its area.

  2. Run the function by providing a radius and print the resulting area.

Exercise 6: Classes

Functions are nice if you need to perform a specific, isolated computation. However, sometimes it is useful to create objects that encapsulate 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 and assigns it to a newly created self.area attribute.

Please do the following:

  1. In Circle, implement a second method that calculates the circumference of the circle. Calculate and print the circumference.

  2. Implement a new class called Square that has a single attribute .side, and two methods for area and perimeter. Calculate and print both.

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.

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

  2. 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) to mean_rt.

      • Return the generated response_time.

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

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

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

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.

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

  2. Test the InhibitoryNeuron class by creating an instance, applying excitation and inhibition, and checking the activation level.

Voluntary Exercise 3: List comprehensions

You learned about nested statements in previous sessions. Please carefully read the following code. What is its purpose?

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 creates a new list containing the type of each element of the random_stuff list:

[<class 'int'>, <class 'str'>, <class 'str'>, <class 'float'>, <class 'int'>, <class 'str'>]

Can you implement the previous code block that filters the strings from the list by using a single list comprehension?