Functions and Modules
In this section, you will learn about functions and modules in Python. Functions allow you to organize code into reusable blocks, while modules are files that contain Python code and can be imported into other programs. We will cover topics such as defining and calling functions, function arguments, return statements, creating and using modules, and using built-in and third-party modules.
Defining and Calling Functions
You can define a function in Python using the `def` keyword. Here’s an example:
def greet(): print("Hello, world!") greet() # Output: Hello, world!
Function Arguments
Functions can accept arguments, allowing you to pass values into the function. Here’s an example of a function with arguments:
def greet(name): print("Hello, " + name + "!") greet("Alice") # Output: Hello, Alice!
Return Statements
A function can return a value using the `return` statement. Here’s an example:
def add_numbers(a, b): return a + b result = add_numbers(3, 5) print(result) # Output: 8
Creating and Using Modules
Modules are files containing Python code that can be imported into other programs. You can create your own modules and use them in different scripts. Here’s an example:
module.py: def greet(name): print("Hello, " + name + "!") main.py: import module module.greet("Alice") # Output: Hello, Alice!
Using Built-in and Third-Party Modules
Python provides a wide range of built-in modules that you can use in your programs. Additionally, there are numerous third-party modules available that extend Python’s functionality. Here’s an example of using a built-in module and a third-party module:
Built-in module: import random number = random.randint(1, 10) print(number) # Output: a random number between 1 and 10 Third-party module: import requests response = requests.get("https://www.example.com") print(response.status_code) # Output: 200 (success)