Python Track · Part 3 of 9

Python Functions and Modules

Python
Functions
Define and call Python functions, pass arguments, return values, and import modules and libraries such as math.
Author

Gujuri Alekha

Published

Oct 20, 2024

3.1 Defining and Calling Functions

Defining a Function : A function in Python is a reusable block of code that performs a specific task. To define a function, you use the def keyword followed by the function name and a pair of parentheses.

Calling a Function : Once a function is defined, you can call it by using its name followed by parentheses, passing any required arguments (if any).

Show code
# define function
def greet(name):
    print(f"Hello, {name}!")

# calling function

greet("Gujuri Alekha")
Hello, Gujuri Alekha!

3.2 Function Arguments and Return Values

Function Arguments: Functions can accept input values called arguments or parameters. These values are passed into the function when it’s called and can be used inside the function.

Return Values : Functions can also return values using the return statement. A function can return one or multiple values.

Show code
# Function Arguments and Return Values
def add(x, y):
    result = x + y
    return result

# call the function
sum_result = add(8, 5)
print(f"Sum of {x} & {y} is : {sum_result}")
Sum of 5 & 5 is : 13

3.3 Importing Modules and Libraries

  • Python allows you to organize your code into modules and libraries to make it more manageable. A module is a Python file containing functions, variables, and classes, while a library is a collection of modules.
  • You can import modules or specific functions/classes from modules using the ’ import ’ statement.
Show code
# Importing the entire math module
import math
result = math.sqrt(16)
print(f"square root of {16} is  : {result}")

# Importing only the sqrt function from math
from math import sqrt
Result = sqrt(49)
print(f"square root of {49} is  : {Result}")
square root of 16 is  : 4.0
square root of 49 is  : 7.0

Citation

BibTeX citation:
@online{alekha2024,
  author = {Alekha, Gujuri},
  title = {Python {Functions} and {Modules}},
  date = {2024-10-20},
  url = {https://gujurialekha.github.io/blog/python/03-python-functions-and-modules.html},
  langid = {en}
}