Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Links | Search | Bio |

Guide to Python (University at Buffalo Version)


Chapter 5: Working With Functions

Python Functions

Python functions provide a way to create a group of statements that perform a certain task and then "call" that function from your Python code.

def factorial(n):
    """
    Calculate the factorial of a given number n.
    
    Parameters:
    n (int): The number to calculate the factorial for.
    
    Returns:
    int: The factorial of the number n.
    """
    if n < 0:
        return "Factorial is not defined for negative numbers."
    elif n == 0 or n == 1:
        return 1
    else:
        result = 1
        for i in range(2, n + 1):
            result *= i
        return result

# Example usage:
number = 5
print(f"The factorial of {number} is {factorial(number)}")
Figure 5-1: A Python Function
The factorial of 5 is 120
Figure 5-2: A Python Function Output

The Python import Statement

Python allows you to have a function in a separate file (called a module), such as functions.py and, using the Python import statement access that function in any Python program.

from functions import printName
 
Figure 5-3: Using import (functions.py)
The factorial of 5 is 120
Figure 5-4: Python import Output

Function Parameters

Python allows you to pass arguments to a function by declaring them as the parameters of the function.

# module functions2.py
def welcome(name):
	print(f"Hello {name}!")
	

# welcome.py from functions2 import welcome welcome("Jim") welcome("D'arcy")
Figure 5-5: Passing Arguments to a Function
Hello Jim!
Hello D'arcy!
Figure 5-6: Passing Arguments to a Function Output

Using Default Function Parameters

Python also allows you to have default values parameters if that parameter is not in the arguments passed to a function by assigning a default value to them as the parameters of the function.

# module functions2.py
def welcome(name  "Default Name"):
	print(f"Hello {name}!")
	

# welcome.py from functions2 import welcome welcome("Jim") welcome("D'arcy") welcome()
Figure 5-7: Using Default Arguments with a Function
Hello Jim!
Hello D'arcy!
Hello Default Name!
Figure 5-8: Using Default Arguments with a Function Output

Using Optional Function Parameters

Python also allows you to have optional parameters if that parameter is not in the arguments passed to a function.

# module functions2.py
def welcome(*name):
	print(f"Hello {name}!")
	

# welcome.py from functions2 import welcome welcome(Jim)
Figure 5-9: Using Optional Arguments with a Function
Hello Jim!
Figure 5-10: Using Optional Arguments with a Function Output

Using the math and cmath Modules

The Python math and cmath modules for performing calculations. The cmath module is used when working with complex numbers. These modules provide many methods.

#math_module.py

import math

# find the square root of a number
num = float(input('Enter a number to find its square root: '))
num_sr = math.sqrt(num)
print(f'The square root of {num} is {num_sr:.2f}.\n')

# Use the math.pi constant to calculate the circumference of a circle
rad = float(input('Enter the radius of the circle: '))
circ = float(2 * math.pi * rad)
print(f'The circumference of a circle with a radius of {rad} is {circ:.2f}.\n')

# use the math.pow to raise a number to a power
num = float(input('Enter a number: '))
pow = float(input(f'Enter a power for {num:.2f}: '))
num_pow = float(math.pow(num, pow))
print(f'The number {num:.2f} raised to the power of {pow:.2f} is: {num_pow:,.2f}.')
Figure 5-11: Using the math Module
Enter a number to find its square root: 65
The square root of 65.0 is 8.06.

Enter the radius of the circle: 89
The circumference of a circle with a radius of 89.0 is 559.20.

Enter a number: 5
Enter a power for 5.00: 9
The number 5.00 raised to the 9.00 power is: 1,953,125.00.
Figure 5-12: Using the math Module Output

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2025 Jim Gerland