0
0
Pythonprogramming~20 mins

Creating custom modules in Python - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom Module Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of importing and using a custom module function
Consider you have a file named mymath.py with this content:
def add(a, b):
    return a + b

What will be the output of this code?
import mymath
print(mymath.add(3, 4))
Python
import mymath
print(mymath.add(3, 4))
A7
B34
CTypeError
DNameError
Attempts:
2 left
💡 Hint
Remember that the function add returns the sum of two numbers.
Predict Output
intermediate
2:00remaining
Output when importing a module with a syntax error
Given a file mymodule.py with this content:
def greet(name):
    print(f"Hello, {name}!")

if True
    print("This line has a syntax error")

What happens when you run this code?
import mymodule
mymodule.greet("Alice")
Python
import mymodule
mymodule.greet("Alice")
AHello, Alice!
BSyntaxError
CNameError
DIndentationError
Attempts:
2 left
💡 Hint
Check the if statement syntax in the module.
🔧 Debug
advanced
2:00remaining
Why does this custom module import fail?
You have a file calculator.py with:
def multiply(x, y):
    return x * y

And this code in another file:
from Calculator import multiply
print(multiply(2, 3))

What is the cause of the error when running this code?
Python
from Calculator import multiply
print(multiply(2, 3))
ANameError because multiply is not defined
BTypeError because multiply is not a function
CSyntaxError because import statement is wrong
DModuleNotFoundError because module name is case-sensitive
Attempts:
2 left
💡 Hint
Python module names are case-sensitive and must match the file name exactly.
📝 Syntax
advanced
2:00remaining
Which import statement correctly imports all functions from a custom module?
You have a module tools.py with several functions.
Which option correctly imports all functions so you can call them directly without prefix?
Aimport tools.*
Bfrom tools import all
Cfrom tools import *
Dimport * from tools
Attempts:
2 left
💡 Hint
The syntax for importing all names from a module uses 'from module import *'.
🚀 Application
expert
2:00remaining
What is the output of this custom module usage with __name__ check?
Given a file greetings.py with:
def say_hello():
    print("Hello from greetings")

if __name__ == "__main__":
    say_hello()

And this code in another file:
import greetings
print("Imported greetings module")

What will be printed when running the second file?
Python
import greetings
print("Imported greetings module")
AImported greetings module
B
Hello from greetings
Imported greetings module
CNo output
DNameError
Attempts:
2 left
💡 Hint
Code inside 'if __name__ == "__main__"' runs only when the module is executed directly.