Programming using Python
Course Code: DAL1003
Section C
User Defined Functions – Defining, Calling, Types of Functions & Arguments,
pass
Importing Modules – Math Module, Random module etc., Aliasing module
names
Additional – Taking help in Python, Listing all methods, etc..
Online Book: https://automatetheboringstuff.com/#toc
Python - User Defined Functions
Function is a block of code that performs a specific task. It is a reusable piece of code that takes arguments and
returns a value. Function only runs when it is called. Functions are essential in Python programming as they
promote modularity, reusability, and maintainability of code.
Types of Functions in Python
● Built-in Functions: Python has a range of built-in functions, such as print(), int(), len(), and sum(), which are
always available and can be used directly.
● Functions defined in Built-in Modules: Python’s standard library includes modules that define groups of
functions. To use these functions, you need to import the module.
● User-Defined Functions: You can create your own functions using the def keyword. These functions can take
arguments, perform operations, and return values.
Syntax: function is defined using the def keyword
def function_name(parameters):
# function body
return value
where:
function_name is the name given to the function.
parameters is a comma-separated list of variables that will be passed to the function when it’s called.
function body is the code that will be executed when the function is called.
return value is the value that the function will return to the caller.
Python - User Defined Functions - Arguments or Parameters
Information can be passed into functions as arguments or parameters. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want, just separate them with a
comma. Arguments / Parameters are often shortened to args / params in Python.
Functions in Python can take three types of arguments:
1. Positional Arguments: These are passed to the function in the order they are defined in the function signature.
def greet(name, message):
print(f"{message}, {name}!")
greet("Alice", "Hello") # Output: Hello, Alice!
2. Keyword Arguments: These are passed to the function using the keyword=value syntax.
def greet(name, message):
print(f"{message}, {name}!")
greet(message="Good morning", name="Bob") # Output: Good morning, Bob!
# The arguments are passed using the parameter names: message and name, so their order doesn't matter.
Python - User Defined Functions - Arguments or Parameters
3. Default Arguments: Functions can also have default arguments, which are used when no explicit value is passed
to the parameter. Default arguments are specified by assigning a value to the parameter in the function definition.
def greet(name, message="Hello"):
print(message, name)
#when No message value is provided, default value Hello is used.
greet("Alice") # Output: Hello Alice
#when message value is provided, here "Good Morning" value will be used.
greet("Bob", "Good Morning") # Output: Good Morning Bob
Note: Function must be called with the correct number of arguments. Meaning that if your function expects 2
arguments, you have to call the function with 2 arguments, not more, and not less.
Note: Programs that avoid duplication and prevent large functions by using smaller functions are more readable
and maintainable. They're also easier to debug when things aren't working right.
Python - User Defined Functions - return statement
Functions can return values using the return statement. The return value can be a simple value, a complex data
structure, or even another function. If you need to use a value that a function is returning, you can assign the
function output to a variable.
def add(x, y): #To use multiple arguments, you must separate them by using a comma.
return x + y
result = add(2, 3) # result = 5
Note: Only one return statement works in a function (whichever is encountered first, while execution). Also, the
code execution inside the function stops after executing the return statement.
def add(x, y):
return x + y
print(“Hello”) #this code statement won’t be executed
return x - y #this code statement won’t be executed
Note: In Python, if a function doesn't explicitly return a value, it implicitly returns None.
def add(x, y):
print(x + y) #on saving it to a variable,it shows None
Python - User Defined Functions - pass keyword
Function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the
pass statement to avoid getting an error. Even if you add a comment, it will be treated as empty, so, use pass keyword.
def myfunction(): for x in range(): if a > 2:
pass pass pass
# Note: pass keyword can also work with conditional (if-elif-else) and loop statements (for, while).
Python functions help you write modular and reusable code, compute values, and perform
actions based on context. They are reusable blocks of code that perform specific tasks
and can be called as needed. Defined using the def keyword, they can accept inputs
(parameters) and return outputs.
Functions help make code modular, readable, and easier to debug. They support default
values for parameters and can be defined with or without a return value.
Python also supports built-in functions like print(), len(), and sum(), as well as
user-defined functions for custom logic, making functions an essential part of Python
programming.
Python - User Defined Functions - DocString
Docstring is a special kind of comment used to describe what a function, class, or module does. It is placed
right after the function header (inside the function body) and is written using triple quotes (""" """). Docstrings
help make your code more readable and understandable by documenting the purpose, inputs, and outputs of
the function. Docstrings can be accessed using Python's built-in help() function.
def greet(name):
"""
This function greets the person whose name is passed as an argument.
Parameters:
name (str): The name of the person to greet.
# single line DocString
def square(x):
Returns:
"""Returns the square of a number."""
None
return x ** 2
"""
print(f"Hello, {name}!") help(square)
# Using the help() function to access the docstring
help(greet)
Python - User Defined Functions - Practice Questions
1. Write a function called square() that takes a number as an argument and returns the
square of that number.
def square(number):
"""Returns the square of a given number."""
return number ** 2
# Example usage:
result = square(4)
print(result) # Output: 16
2. Write a function to check if a number is even or odd.
def is_even(number):
"""Returns True if the number is even, False if odd."""
return number % 2 == 0
# Example usage:
print(is_even(10)) # Output: True
print(is_even(7)) # Output: False
Python - User Defined Functions - Practice Questions
3. Write a function to calculate the factorial of a number.
4. Write a function that takes two numbers and returns their sum.
5. Write a function to check if a string is a palindrome.
6. Write a function that returns the maximum of three numbers.
7. Write a function to count the number of vowels in a string.
8. Write a function to reverse a string.
9. Write a function to calculate the area of a circle.
10. Write a function to count the number of words in a sentence.
11. Write a function to return the first n Fibonacci numbers.
Python - Modules - ‘import’ keyword
To make use of the functions within a module in your script you will need to import the module with an import statement.
All import statements are made up of the | import | keyword along with the name of the module. In most Python scripts
import statements are declared at the top of the code under any general comments. This is done to ensure they are
executed from the get-go. eg: import math
===========================================================================================
● The import keyword finds and loads a package, a sub-package or a module if they are found in the system using
the import mechanism.
● Once a module is loaded, the name of the imported module is introduced in the current scope where the import
statement is executed.
● Which name gets introduced - name of the actual module or the top-level module…depends on how the import
statement is used.
● Regardless of how the import is used, if a module is not found, Python raises a ModuleNotFound exception.
Python - Modules - ‘from’ keyword
While the import command is very straightforward it lacks efficiency. In many scenarios you may need only a small
portion of the module. To solve this the | from | keyword is born. Below is code written in the Python Programming
Window. It is a very similar code example to above. This demonstrates the syntax when using the | from | keyword. As
you can see this keyword is used in conjunction with an import statement. Also, worth noting you can refer to the new
functions directly by name rather than through the period notation seen before. The code below starts by importing
several functions from specific modules. Then that functionality is demonstrated and printed to the Python IDLE Shell.
eg:
from math import sqrt
Python - Modules - ‘as’ keyword - Aliasing module names
It is possible to modify the names of modules and the name of the functions within Python. This is achieved using the |
as | keyword. The desire may come up for a couple of reasons. Perhaps you have already used the same name for
something else in your program or another imported module has the same name. Or simply it could be as way to save
yourself from writing the function out longhand to save yourself time particularly when your find yourself re-typing the
functions many times.
Code examples of using the | as | keyword can be seen below written in the Python Programming Window. eg.,
import datetime as dt
from math import sqrt as s
Python - Modules - math module
The math module in Python provides a wide variety of mathematical functions, constants,
and utilities to help with mathematical operations. It is a standard library module,
which means you don't need to install it separately—it's available by default in Python.
import math
# Returns the smallest integer greater than or equal to x (i.e., rounds up).
math.ceil(4.2) # Returns 5
# Returns the largest integer less than or equal to x (i.e., rounds down).
math.floor(4.8) # Returns 4
# Returns the factorial of x, which is the product of all positive integers up to x.
math.factorial(5) # Returns 120 (5! = 5 * 4 * 3 * 2 * 1)
# Returns x raised to the power of y (i.e., x ** y).
math.pow(2, 3) # Returns 8.0 (2^3)
# Returns the square root of x.
math.sqrt(16) # Returns 4.0
# other methods: math.pi, math.gcd(a, b), math.lcm(a, b)
Python - Modules - random module
The random module in Python is part of the standard library and provides a variety of
functions for generating random numbers, selecting random elements from sequences,
shuffling data, and more. It's commonly used in simulations, games, cryptography (though
for cryptographic purposes, Python provides a different module called secrets), and
anywhere randomness is required.
import random
# Returns a random floating-point number between 0.0 and 1.0
random.random() # Returns a random float in [0.0, 1.0)
# Returns a random integer N such that a <= N <= b.
random.randint(1, 6) # Simulate rolling a six-sided die
# Returns a randomly selected number from the range start to stop (exclusive). You can
optionally specify a step size.
random.randrange(0, 10, 2) # Returns a random even number between 0 and 9
# Returns randomly selected element from non-empty sequence (list, tuple, string, etc.).
fruits = ['apple', 'banana', 'cherry', 'date']
random.choice(fruits) # Returns a random fruit from the list
Python - Modules - random module
# Returns a list of k unique elements chosen from the population sequence. The elements
are selected without replacement (no duplicates).
random.sample(fruits, 2) # Returns list with 2 randomly selected fruits, no repetition
# Randomly shuffles the elements of a mutable sequence (like a list) in place (i.e., it
modifies the sequence itself).
deck = ['ace', 'king', 'queen', 'jack', '10', '9']
random.shuffle(deck) # Randomly shuffles the deck in place
Python - Modules - statistics module
The statistics module in Python provides a collection of functions for performing
statistical operations on numerical data. It is part of Python's standard library, so
you don’t need to install anything extra to use it. The module includes functions for
calculating measures of central tendency, dispersion, and distribution, along with more
advanced statistical operations.
import statistics
# Returns the arithmetic mean (average) of a list or iterable data.
data = [1, 2, 3, 4, 5]
statistics.mean(data) # Returns 3.0 (the average of 1, 2, 3, 4, 5)
# Returns the median of data. The median is the middle value when the data is sorted. If
the data has an even number of elements, it returns the average of the two middle
values.
data = [1, 2, 3, 4, 5]
statistics.median(data) # Returns 3 (middle value)
data_even = [1, 2, 3, 4]
statistics.median(data_even) # Returns 2.5 (average of 2 and 3)
Python - Modules - statistics module
# Returns the mode of data, which is the most common element in the dataset. If there
are multiple modes, it raises a StatisticsError.
data = [1, 2, 2, 3, 4]
statistics.mode(data) # Returns 2 (most frequent element)
# Returns the standard deviation of data, which measures the spread of the data points
from the mean. The formula used is the sample standard deviation (i.e., dividing by
n-1).
statistics.stdev(data) # Returns 1.58 (sample standard deviation)
# Returns the variance of data, which measures how far each data point is from the mean.
Like stdev, it calculates the sample variance by default.
statistics.variance(data) # Returns 2.5 (sample variance)
# Other methods: statistics.pi, statistics.sum(), statistics.GeometricMean(data)
Taking help in Python
When working with Python, especially in an interactive environment like the Python shell
or an IDE, there are many times when you'll need to look up documentation, explore
objects, or debug your code. Fortunately, Python provides several built-in tools to help
you get quick insights into your code, libraries, and functions.
These tools allow you to interactively inspect objects, retrieve documentation, and
troubleshoot issues without leaving the Python environment.
help(): For detailed documentation on functions, classes, and modules.
Provides an interactive help system for modules, functions, classes, and more.
help(str) # Get documentation for the 'str' class
help(len) # Get documentation for the 'len' function
help() # Starts an interactive help session
dir(): To explore available attributes and methods of an object.
Returns a list of valid attributes (methods, variables, classes) of the object passed.
dir(str) # List all attributes and methods available for strings
dir([]) # List methods available for lists
dir() # List the names in the current namespace (variables, imports, etc.)
Taking help in Python
type(): To check the type of an object and ensure you're working with the right data.
Returns the type of an object (i.e., what class or data-type it is).
type(123) # <class 'int'>
type("hello") # <class 'str'>
type([1, 2, 3]) # <class 'list'>