In Python, a module is a file containing Python code that defines functions, classes, and variables, which can be imported and used in other Python programs. Modules allow you to organize code into logical units and facilitate code reuse, modularity, and maintainability.
To create a module, you simply write Python code in a file with a .py extension. You can define functions, classes, and variables in the module file. Here's an example of a simple module named my_module.py:
# my_module.py
def greet(name):
print(f"Hello, {name}!")
def add_numbers(a, b):
return a + b
PI = 3.14159
To use the functions and variables defined in a module, you need to import it into your Python program. There are several ways to import a module:
When you are planning to access most or a significant part of the functionality of a module, you will probably chooce to import the entire module. This gives access to all of the functions, classes, and variables within it. The only downside of this method is that you will be required to use the module name then the function, variable or class to refer to those members of the module. You will see this in the example below (my_module.greet, and so on).
import my_module
my_module.greet("Alice")
print(my_module.add_numbers(5, 7))
print(my_module.PI)
When you only want a small part of a module's functionality, or memory conservation is a concern, you may want to only import the things that you need from a module. This is done using the from keyword. Notice also that in this method, you don't need to use dot notation. Be careful, though - If you have the same name used somewhere else in your code, this will create a conflict called a namespace conflict.
from my_module import greet, PI
greet("Bob")
print(PI)
Variables defined within a module have a module-level scope. This means they are accessible throughout the module. Functions and classes defined in the module can access these variables.
In Python, there is a special variable called __name__ that represents the current module's name. When a module is imported, the __name__ variable is set to the module's name. However, when the module is executed as the main program, the __name__ variable is set to "__main__".
This distinction allows you to have code in a module that runs only when the module is executed as the main program, but not when it is imported as a module.
Example:
from my_module import greet, PI
greet("Bob")
print(PI)# my_module.py
def greet(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
# This code will only run when the module is executed as the main program
greet("Alice")
# Importing a module from a package
import my_package.my_module
my_package.my_module.my_function()
Modules in Python provide a powerful way to organize and reuse code. By understanding their abilities, limitations, variable scope, and common mistakes, you can effectively use and create modules to enhance your Python programs.
The Python Standard Library is a collection of modules that come bundled with Python. It provides a wide range of functionalities to help you perform various tasks without requiring additional installations or dependencies. The Standard Library covers diverse areas such as file handling, network programming, mathematics, string manipulation, and more.
Let's explore some commonly used modules from the Python Standard Library, along with examples of their usage:
import math
print(math.sqrt(25)) # Output: 5.0
print(math.pi) # Output: 3.141592653589793
print(math.sin(math.pi/2)) # Output: 1.0
import random
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
print(random.choice(['apple', 'banana', 'cherry'])) # Output: Random choice from the list
import os
print(os.getcwd()) # Output: Current working directory
print(os.listdir('/path')) # Output: List of files and directories in the given path
import datetime
now = datetime.datetime.now()
print(now) # Output: Current date and time
print(now.year) # Output: Current year
print(now.strftime('%Y-%m-%d %H:%M:%S')) # Output: Formatted date and time
import json
data = '{"name": "John", "age": 30}'
parsed_data = json.loads(data)
print(parsed_data['name']) # Output: John
person = {'name': 'Alice', 'age': 25}
json_data = json.dumps(person)
print(json_data) # Output: {"name": "Alice", "age": 25}
import urllib.request
response = urllib.request.urlopen('https://www.example.com')
html = response.read()
print(html) # Output: HTML content of the webpage
These are just a few examples of the modules available in the Python Standard Library. The Standard Library contains numerous other modules covering areas such as regular expressions (re), file input/output (io), command-line arguments (argparse), and more.
To explore the Standard Library further, refer to the official Python documentation: https://docs.python.org/3/library/
The Python Standard Library is an invaluable resource that provides ready-to-use functionalities for various programming tasks. Understanding and utilizing the Standard Library will greatly enhance your ability to write efficient and powerful Python programs.
The dir() function is a powerful built-in function in Python that returns a sorted list of names in the current scope or the attributes of an object. It allows you to explore the available attributes, methods, and variables associated with an object or module, providing insight into its functionality and usage.
The general syntax for using the dir() function is as follows:
dir([object])
When called without any argument (dir()), it returns a list of names in the current local scope.
When called with an object as an argument (dir(object)), it returns a list of names associated with that object.
x = 5
y = "Hello, World!"
print(dir()) # Output: ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x', 'y']
In this example, the dir() function is called without any argument. It returns a list of names in the current local scope, including the predefined names (__builtins__, __doc__, __loader__, __name__, __package__, __spec__) and the variables x and y defined by the user.
my_list = [1, 2, 3]
print(dir(my_list))
In this example, the dir() function is called with the my_list object as an argument. It returns a list of attributes and methods associated with the list object, such as append(), clear(), count(), extend(), and more.
import math
print(dir(math))
In this example, the dir() function is called with the math module as an argument. It returns a list of names associated with the math module, including mathematical functions like sqrt(), sin(), cos(), constants like pi, and more.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}.")
person = Person("Alice", 25)
print(dir(person))
In this example, the dir() function is called with the person object, which is an instance of the Person class. It returns a list of names associated with the person object, including the name and age attributes and the greet() method.
It's worth noting that the dir() function returns all the available names, including built-in attributes and methods, which may not always be relevant to your specific use case. Therefore, understanding the purpose and functionality of the object or module is crucial for interpreting the results of dir().
The dir() function is a valuable tool for exploring objects, modules, and the current local scope. By utilizing dir(), you can gain insights into the attributes and methods available, helping you effectively work with Python's built-in functionalities and your custom objects.
No terms have been published for this module.
Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.
Skip to the Next QuestionModules are something we’ve already been using throughout this course. As you know, they allow us to easily expand the basic functionality of Python. For this sandbox, we’re going to channel our inner Picasso using a custom module that I’ve created for you.
First, download and install the following file, and put it in your main project directory in PyCharm. You should be able to drag it in directly from your desktop or your “downloads” folder.
Next, create a new Python file in the same folder, and paste in the following code:
import picasso as p
import turtle
t = turtle.Turtle()
p.draw_nose(t)
p.moveTurtle(t,-50,50)
p.draw_left_eye(t)
p.moveTurtle(t,100,0)
p.draw_right_eye(t)
turtle.done()
If you run the code, it should draw a very simple face. Each time, you run it, the face should be slightly different.
If you open the picasso.py module, you’ll see that in addition to the functions we’ve used in our little program, there are more functions, for drawing ears and a mouth as well.
The first part of this sandbox challenge is to add code to your main script to complete the face with ears and a mouth.
The second part of the challenge is a little trickier. See if you can add an additional function to the Picasso module using the existing face parts as a guide. Your new function should draw some funny hair on top of the face. Once you add your function to the module, add a few lines of code to your main code file to call the function and draw the hair.
Take a screenshot of your finished face, and post it to the forum.
for A11, the challenge is to create a custom module that incorporates at least two major pieces of functionality into functions within that module. The size and complexity of your main program should be SIGNIFICANTLY reduced as a result. Use the Rock, Paper, Scissors program code for this assignment.
Your script must conform to the following:
Please submit the complete program as two .py files.