Python Exam 4: Functions, Lambda, and Modules (10 mixed exercises)
Python Exam 4: Functions and Modules
Test your ability to write reusable code with functions and modules.
Exercise 1
Creating a Function
Create a simple function:
- Define a function named `my_function`.
- The function prints "Hello from a function".
- Call the function to run it.
Solution
def my_function():
print("Hello from a function")
my_function()
Exercise 2
Arguments
Pass data to a function:
- Define a function `my_function` that takes an argument `fname`.
- The function prints the name followed by "Refsnes".
- Call it with the name "Emil".
Solution
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
Exercise 3
Arbitrary Arguments (*args)
Handle a variable number of inputs:
- Define a function that accepts `*kids`.
- Print "The youngest child is " followed by the third item (index 2).
- Call it with "Emil", "Tobias", "Linus".
Solution
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Exercise 4
Keyword Arguments (**kwargs)
Handle a dictionary of arguments:
- Define a function that accepts `**kid`.
- Print the last name `kid["lname"]`.
- Call it with `fname="Tobias", lname="Refsnes"`.
Solution
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Exercise 5
Return Values
Return a result from a function:
- Define `my_function(x)` that returns `5 * x`.
- Print the result for input 3.
Solution
def my_function(x):
return 5 * x
print(my_function(3))
Exercise 6
Lambda Functions
Create an anonymous function:
- Create a `lambda` function that takes `a` and adds 10.
- Store it in a variable `x`.
- Print the result of `x(5)`.
Solution
x = lambda a : a + 10
print(x(5))
Exercise 7
Modules
Use an external module:
- Import a module `mymodule` (assume it exists).
- Use it with the alias `mx`.
- Print `mx.person1["age"]`.
Solution
import mymodule as mx
# print(mx.person1["age"])
Exercise 8
Dates
Work with dates:
- Import the `datetime` module.
- Print the current time using `datetime.datetime.now()`.
- Print only the current year.
Solution
import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
Exercise 9
Math
Use math functions:
- Use `min` and `max` to find the smallest and largest numbers in `(5, 10, 25)`.
- Use `abs(-7.25)` to get the absolute value.
- Use `pow(4, 3)` to calculate a power.
Solution
x = min(5, 10, 25)
y = max(5, 10, 25)
z = abs(-7.25)
p = pow(4, 3)
print(x, y, z, p)
Exercise 10
JSON in Python
Convert data:
- Import `json`.
- You have a dictionary `x = {"name": "John", "age": 30}`.
- Convert it to JSON text with `json.dumps(x)`.
- Print the result.
Solution
import json
x = {
"name": "John",
"age": 30,
"city": "New York"
}
y = json.dumps(x)
print(y)