Master Python Functions: The Ultimate Beginner's Guide
A Function in programing is a named sequence of statements that performs a computation. It is a block of code which runs only when it is called. so when you define a function, you specify the name and the sequence of statements. Later, you call the function by name.
CREATING A FUNCTION
def is a keyword that indicates that this is a function definition. In python, a function is defined using the def keyword.
Example:
def my_function():
print("it is a wonderful day”)
my_function()
This type of functions is also called USER DEFINE function, because here the user gives the function a name and a command.
ARGUMENT
The expression in the parentheses is called the argument of the function. The Argument is a value or variable that are passed into the function as input to the function
Example:
def my_function(name):
print(name + "is a wonderful person")
my_function("Grace")
my_function("Bill")
The term PARAMETER and ARGUMENT can mean the same thing in python functions
NUMBERS OF ARGUMENTS
By defaults, a function must be called with the correct number of arguments. Meaning that if your function experts 2 arguments, you have to call the function with 2 Arguments, not more, and not less.
Example:
def my_function(fstname, lstname):
print(fstname + " " + lstname)
my_function("Grace", "Adams")
N/B If you try to call the function with 1 and 3 arguments, you will get an error
Example:
my_function(fstname, lstname):
print(fstname + " " + lstname)
my_function("Grace")
ARBITRARY ARGUMENTS, (*args)
In a case where you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
This will allow the function to receive a tuple of a argument and can access the items accordingly.
Example:
def my_function(*kids):
print("The name of my classmates are:" + kids[2])
my_function("Grace", "Isaac", "Bill")
TYPES OF FUNCTIONS
BUILT-IN FUNCTION
Python provides a number of important built-in functions that we can use without needing to provide the function definition. Python has many built-in functions that you can use directly without importing anything. These functions cover a wide variety of common programming tasks that include performing math operations, working with built-in data types, processing iterables of data, handling input and output in your programs, working with scopes, and more.
Below are examples of built-in functions and their descriptions:
Function | Description |
abs() | Returns the absolute value of a number |
all() | Returns True if all items in an iterable object are true |
any() | Returns True if any item in an iterable object is true |
ascii() | Returns a readable version of an object. Replaces none-ascii characters with escape character |
bin() | Returns the binary version of a number |
bool() | Returns the boolean value of the specified object |
bytearray() | Returns an array of bytes |
bytes() | Returns a bytes object |
callable() | Returns True if the specified object is callable, otherwise False |
chr() | Returns a character from the specified Unicode code. |
classmethod() | Converts a method into a class method |
compile() | Returns the specified source as an object, ready to be executed |
complex() | Returns a complex number |
delattr() | Deletes the specified attribute (property or method) from the specified object |
dict() | Returns a dictionary (Array) |
dir() | Returns a list of the specified object's properties and methods |
divmod() | Returns the quotient and the remainder when argument1 is divided by argument2 |
enumerate() | Takes a collection (e.g. a tuple) and returns it as an enumerate object |
eval() | Evaluates and executes an expression |
exec() | Executes the specified code (or object) |
filter() | Use a filter function to exclude items in an iterable object |
float() | Returns a floating point number |
format() | Formats a specified value |
frozenset() | Returns a frozenset object |
getattr() | Returns the value of the specified attribute (property or method) |
globals() | Returns the current global symbol table as a dictionary |
hasattr() | Returns True if the specified object has the specified attribute (property/method) |
hash() | Returns the hash value of a specified object |
help() | Executes the built-in help system |
hex() | Converts a number into a hexadecimal value |
id() | Returns the id of an object |
input() | Allowing user input |
int() | Returns an integer number |
isinstance() | Returns True if a specified object is an instance of a specified object |
issubclass() | Returns True if a specified class is a subclass of a specified object |
iter() | Returns an iterator object |
len() | Returns the length of an object |
list() | Returns a list |
locals() | Returns an updated dictionary of the current local symbol table |
map() | Returns the specified iterator with the specified function applied to each item |
max() | Returns the largest item in an iterable |
memoryview() | Returns a memory view object |
min() | Returns the smallest item in an iterable |
next() | Returns the next item in an iterable |
object() | Returns a new object |
oct() | Converts a number into an octal |
open() | Opens a file and returns a file object |
ord() | Convert an integer representing the Unicode of the specified character |
pow() | Returns the value of x to the power of y |
print() | Prints to the standard output device |
property() | Gets, sets, deletes a property |
range() | Returns a sequence of numbers, starting from 0 and increments by 1 (by default) |
repr() | Returns a readable version of an object |
reversed() | Returns a reversed iterator |
round() | Rounds a numbers |
set() | Returns a new set object |
setattr() | Sets an attribute (property/method) of an object |
slice() | Returns a slice object |
sorted() | Returns a sorted list |
staticmethod() | Converts a method into a static method |
str() | Returns a string object |
sum() | Sums the items of an iterator |
super() | Returns an object that represents the parent class |
tuple() | Returns a tuple |
type() | Returns the type of an object |
vars() | Returns the dict property of an object |
zip() | Returns an iterator, from two or more iterators |
examples:
max("Hello world")
min("Hello world")
The max
and min
functions give us the largest and smallest values in a list, respectively, The max
function tells us the “largest character” in the string (which turns out to be the letter “w”) and the min
function shows us the smallest character (which turns out to be a space).
int
can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float
converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Finally, str
converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
Why functions?
It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:
Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read, understand, and debug.
Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
Throughout the rest of the book, often we will use a function definition to explain a concept. Part of the skill of creating and using functions is to have a function properly capture an idea such as “find the smallest value in a list of values”. Later we will show you code that finds the smallest in a list of values and we will present it to you as a function named min
which takes a list of values as its argument and returns the smallest value in the list.
Subscribe to my newsletter
Read articles from Esther Undie directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by