Skip to content

Advanced Python · Week 6

Modules and Scope

Step 1 of 5

Exercise 1: Introduction to Modules

Welcome to Python 2, Lesson 6! Today, we'll learn about modules in Python. Modules are files containing Python code that can be imported and used in other Python programs.

What are Modules?

Modules are reusable pieces of code that can be imported into your Python programs. They help organize and structure your code, making it easier to maintain and reuse.

Python comes with many built-in modules that you can use right away. Let's start by importing and using the 'math' module:

import math # Using the sqrt function from the math module result = math.sqrt(16) print(f"The square root of 16 is: {result}") # Using the pi constant from the math module circumference = 2 * math.pi * 5 print(f"The circumference of a circle with radius 5 is: {circumference:.2f}")

Now it's your turn! Import the 'random' module and use it to generate random numbers:

  1. Import the 'random' module
  2. Generate a random integer between 1 and 10 (inclusive) using random.randint()
  3. Generate a random float between 0 and 1 using random.random()
  4. Print both results
Starter code
# Import the random module and generate random numbers here

Write your code here