Homework assignment #2 - Introduction to Python - 1
Ahoi hoi folks and welcome to homework assignment #2 of the “Python for Psychologists” course, winter term 2024. This homework assignment will be your first venture into the practical use of python and probably also your first time working with jupyter notebooks. Even though we’ve used jupyter notebooks in the seminar sessions you’ll might encounter some problems or unexpected behaviors. Thus, if you encounter any problems along the way, please don’t hesitate to get in touch (via e-mail or the discord server) or check back in the Introduction to Jupyter or the Intro to Python I chapters on the course website.
Some general points:
Throughout the assignment you will be asked to either provide some answers to questions in written form or directly code. Regarding the first, you can just write your answer in the empty markdown cells below the questions. Regarding the second, you can write your code in the empty code cells below the questions and actually run it so that the output (if there’s one) will be included in the notebook. The number and type of cell you need to answer a given questions will be indicated but if you want to use more cells please don’t hesitate to add a few. If you see something like “Type Markdown … or Please provide your solution here
“, you can just click (or double-click) on it to make it a markdown cell. If any of this sounds confusing or unclear you can again consult the Introduction to Jupyter page.
Please don’t forget to save your notebook regularly (maybe every few minutes) either via strg + s on windows and cmd + s on macOS. Once you finished the assignment, pleas save the entire notebook via File -> Save as... and provide the following name FirstNameSurname_pfp_2023_homework_assignment_2 where FirstName should be changed to your first name and Surname to your surname.
The aim of this homework assignment is to go through the things we talked about in the session again and deepen your understanding of them. This will entail the following parts:
1. Characteristics of the python programming language
2. Modules
3. Variables & data types
4. Outro/Q&A
You should be able to answer all of the following questions given the content included in the respective sections on the website, as well as the things covered in during the session. If you feel like some of the things asked here were actually not (sufficiently) covered during the session, please don’t hesitate to let me know ASAP and we’ll figure that out. Otherwise you of course are welcome to train your “google muscles”, just keep in mind that code directly copied from the internet should include sufficient credits (i.e. include links to the respective website as a comment in code/markdown cells). And remember that there is always more than one correct answer in programming.
However, after this way too long intro, I wish you a great time and hope this will feel less like an assignment and more like a fun add on to the session. Again: learning new things takes time and programming is by no means an exception to that. Thus don’t worry if you have to look back and fourth between the assignment and the materials: we all start somewhere and you putting in the effort is already fantastic. You got this!
Homework assignment #2#
1. Characteristics of the python programming language#
During the session we talked about Python being a widely used/very flexible, high-level, general-purpose, dynamic programming language but what does this mean again? Please provide some points regarding each of these characteristics below, preferably in your own words. You can just write your answer in the markdown cells below the questions.
What is meant by widely used?
Please provide your solution here
What is meant by high-level?
Please provide your solution here
What is meant by general-purpose?
Please provide your solution here
What is meant by dynamic?
Please provide your solution here
2. Modules#
We started our endeavors in python via talking about modules as they are crucial to basically anything we want to do. What is a module again and what role do they have within the python ecosystem? You can just write your answer in the markdown cell below.
Please provide your solution here
Lets assume you want to run a few basic statistical analyses on a behavioral dataset using the following python modules: numpy, scipy & pandas. How would you import these modules in their entirety?
# Please write your solution here
Would it also be possible to import these modules given certain access names, so that it’s easier to refer to them and access their functions? If so, could you show how one would do that for each of the three modules mentioned above?
Note: The common custom access names for these modules are np, sp and pd. You can see the pattern here
# Please write your solution here
While having access to the entire module is cool we learned that we will actually only use certain submodules/functions most of the time. Based on our analyses we know that we will need the "min", "max" and "mean" functions from numpy, the "DataFrame" function from pandas and the "stats" package from scipy. How would you do this? (Remember that Python is case-senstive and that you can usually use tab-complete to short-cut writing out most keywords, folks!)
# Please write your solution here
You may have noticed that the above lines contain links to the documentation of each module. This is meant to stress a very important point: python is not only great because it’s open-source and has an incredible community, it’s modules/libraries also usually have fantastics documentation that explain many details of the module, including background, installation, functions, examples, etc. . It’s a great starting point for working with a new module and/or function, always freely available to you!
Before we utilize the imported functions we want to make sure how they work and what they do. Is there any option in python and/or jupyter notebooks to get some information or help regarding a function? If there is, how would you do this for the modules at hand?
# Please write your solution here
Bonus: try searching for the functions you imported in the respective documentation or docs of the module.
That being said, what would be the result if we try to use a module/function we did not import yet? Can you provide a brief explanation (in the markdown cell below) and proof your answer with an example (in the code cell below)?
# Please write your solution here
3. Variables & data types#
The final part of the session introduced more core concepts and building blocks of the python programming language, specifically assignments (the operator, not homework, hehe), variables and data types. Could you briefly describe what a variable actually is?
Please provide your solution here
Amazing, thanks! Now that we know what a variable is we need to talk about how we declare them via assignments. If you’d want to create two variables group_1 and group_2 with the respective values "control" and "target", how would you do that?
# Please write your solution here
Oh, this assignment operator looks like something we all saw in our math classes. Could you briefly explain the difference between variables in coding and math using the meaning of the operator used above? (Again, if you for example do not remember what an operatoris in the python language, feel free to look that up.)
Please provide your solution here
Speaking of which: what happens when you try to refer to an variable that has not been declared yet? Can you provide a brief explanation and proof your answer with an example?
Please provide your solution here
# Please write your solution here
Talking about assignments, operators and variables, can we actually use literally “anything” as a variable name or are there certain limitations? If so, can you name what these limitations would be and why these exist?
Please provide your solution here
Talking about variables what is the most common way to name a variable in Python?
snake_case
CamelCase
SMTH_LIKE_THIS
SmThLiKe_ThAT
Following up on this, we also talked about different basic data types we might encounter in python. Could you maybe list the most common ones we talked about during the session and what they entail?
Please provide your solution here
Ah right, those were the ones we checked out! Is there potentially a way to find out what type a given variable has? Can you demonstrate how you would find out the data type of our variables group_1 and group_2?
# Please write your solution here
Could you please declare variables n_students, n_laptops, course_year and fun_factor these new values: twenty (in int), twenty-one (in float), 2024 (in str) and true (boolean)?
Please print each variable using print() and also print each type of variable
Note: you can print multiple instances using , - print(var1, var2, type(var1))
# Please write your solution here
Assign to n_students value of n_laptops. Damn, did we just overwrite our variable initial values? How does this work in python? What type now is n_students?
# Please write your solution here
You are a 🧙♂️ wizard in a mystical land, and you have three magical ingredients: a Golden Apple (integer), a Mana Elixir (float), and a Mysterious Scroll (string). You need to use Mysterious Scroll by assigning it new value “Used Swap Scroll” and swap the values of Golden Apple and Mana Elixir.
Note you CAN’T in this task just assign new values to golden_apple and mana_elixir. Like golden_apple = 2.5 or crystal_elixir = 5
# Step 1: Assign magical ingredients
golden_apple = 5 # Integer: Number of Golden Apples
mana_elixir = 2.5 # Float: Amount of Mana Elixir
mysterious_scroll = "Swap Scroll" # String: Contents of the Mysterious Scroll
# Step 2: Print original ingredients
print("🧙♂️ Before the Magical Swap:")
print(f"📜 Mysterious Scroll: '{mysterious_scroll}'")
print(f"✨ Golden Apples: {golden_apple}")
print(f"💧 Mana Elixir: {mana_elixir} liters")
# Step 3: Use the scroll and perform the magical swap
# Please write your solution here
# Step 4: Print resulting ingredients
print("\n🎉 After the Magical Swap:")
print(f"📜 Mysterious Scroll (updated): '{mysterious_scroll}'")
print(f"✨ Golden Apples (now Elixir): {golden_apple} liters")
print(f"💧 Mana Elixir (now Apples): {mana_elixir}")
Create a program where a 🧙♂️ wizard transforms an integer (the number of magical artifacts) through the steps of converting it to a float, then to a string, and finally using a boolean to check if the transformation was successful.
# Step 1: Assign the initial value
num_artifacts = 7 # Integer: Number of magical artifacts
# Step 2: Print the original number of artifacts
print("🔮 Before Transformation:")
print(f"The wizard has {num_artifacts} magical artifacts.")
# Step 3: Transform to float
artifact_strength = # Convert to float
print(f"✨ After the spell of transformation, the artifact strength is: {artifact_strength} (float)")
# Step 4: Transform to string
artifact_description = # Convert to string
print(f"📜 The artifact description is: '{artifact_description}'")
# Step 5: Check with boolean
is_magic = # Check if the description contains "magic"
print(f"🧙♂️ Is the description magical? {is_magic}")
# Step 6: Check the type of num_artifacts, artifact_strength, artifact_description and is_magic
Create a program where a 🧙♂️ wizard calculates the strength of his potions using the math module. In the enchanted forest, a wizard brews potions to enhance his magical powers. To determine the strength of his potions, he uses a special formula that involves calculating the square root of the total number of ingredients he has multiplied by pi number.
🧙♂️ wizard is old and have not enough memory, please only import functions which will help to calculate potion_strength
num_ingredients = 25 # Integer: Total number of ingredients
print("🧙♂️ Before Potion Brewing:")
print(f"The wizard has {num_ingredients} magical ingredients.")
# Please write your solution here
potion_strength =
print(f"✨ The strength of the potion is: {potion_strength:.2f}")
print(f"📜 With a strength of {potion_strength:.2f}, the potion is ready for casting!")
4. Outro#
Welcome to the end, you did, great job!
Please remember to save the notebook as described in the beginning and send it to Peer via e-mail. If you have questions, encountered problems and/or errors, please use the cell to outline things further. The same holds true for any type of feedback!
Thanks for going through this assignment, we hope you found it useful and informative. Feedback on your work can also by provided and is just one e-mail or discord message away!