Selected topic
Functions
Prefer practical output? Use related tools below while reading.
Example:
python
def greet(name):
"""Prints a personalized greeting"""
print(f"Hello, {name}!")# Call the function with an argument
greet("John") # Output: Hello, John!
greet that takes one input parameter name.print() statement is used to output the greeting."John").Example:
python
# mymodule.py (a simple module)
def add(a, b):
"""Returns the sum of two numbers"""
return a + bx = 5
y = 3
result = add(x, y)
print(result) # Output: 8
mymodule.py containing a function add.add function takes two input parameters and returns their sum.mymodule module using import mymodule.add function from the imported module, passing arguments as needed.mymodule.py, for example) in the same directory as your main program.import mymodule.python
# mycalculator.py (a module)
def add(a, b):
"""Returns the sum of two numbers"""
return a + bdef subtract(a, b):
"""Returns the difference between two numbers"""
return a - b
def multiply(a, b):
"""Returns the product of two numbers"""
return a * b
python
import mycalculator as mc# Define some values
a = 5
b = 3
# Perform calculations using functions from the imported module
result1 = mc.add(a, b)
result2 = mc.subtract(a, b)
print(f"Result 1: {result1}")
print(f"Result 2: {result2}")
# Use another function from the same module
product = mc.multiply(a, b)
print(f"Product of {a} and {b}: {product}")
mymodule (renamed to mc) using import mycalculator as mc.a and b).