Welcome to this comprehensive lesson where we’ll dive into the world of built-in functions and explore essential Python modules. Python provides a rich set of built-in functions that simplify common tasks, and modules extend this functionality for more specialized operations. In this lesson, we’ll explore commonly used functions and take an overview of Python modules, including examples from the math and random modules.

Commonly Used Built-in Functions:

1. len():

text = "Hello, Python!"
length = len(text)

2. print():

name = "Alice"
age = 25
print("Name:", name, "Age:", age)
3. type():

Returns the data type of an object.
Example:

4. input():

user_input = input("Enter your name: ")

5. sum():

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)

Overview of Python Modules – math Module:

6. math.sqrt():

import math

result = math.sqrt(25)

7. math.sin() and math.cos():

import math

angle = math.radians(30)  # Convert degrees to radians
sine_value = math.sin(angle)
cosine_value = math.cos(angle)

Overview of Python Modules – random Module:

8. random.randint():

import random

random_number = random.randint(1, 10)

9. random.choice():

import random

colors = ["red", "blue", "green"]
selected_color = random.choice(colors)

10. random.shuffle(): – Shuffles the elements of a sequence randomly. – Example: “`python import random

  numbers = [1, 2, 3, 4, 5]
  random.shuffle(numbers)
  ```

Example:

Let’s consider an example where we use the math module to calculate the area of a circle and the random module to generate a random number:

# Example Code
import math
import random

# Using the math module
radius = 7
area = math.pi * math.pow(radius, 2)

# Using the random module
random_number = random.randint(1, 100)

print(f"The area of a circle with radius {radius} is {area}.")
print(f"Randomly generated number: {random_number}")

Practice Exercise:

Create a Python script that asks the user to enter two numbers and then uses the math module to calculate and print the square root of the sum of their squares.

# Example Practice Exercise
import math

# Input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Using the math module
result = math.sqrt(math.pow(num1, 2) + math.pow(num2, 2))
print(f"The square root of the sum of their squares is: {result}")

Summary:

In this lesson, we’ve explored commonly used built-in functions in Python and introduced the math and random modules. These modules extend Python’s capabilities for mathematical operations and random number generation. Practice using these functions and modules to enhance your coding skills. Feel free to ask questions in the discussion forum, and