Learn about programming Functions in Python

Learn about programming Functions in Python: What are Functions? Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save time.

Also functions are a key way to define interfaces so programmers can share their code.

How do you write functions in Python?

As we have seen on previous tutorials, Python makes use of blocks.

A block is an area of the code written in the format of:

block_head:
    1st block line
    2nd block line
    ...

Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, …) Block keywords you already know are “if”, “for”, and “while”.

Functions in Python are defined using the block keyword “def”, followed by the function’s name as the block’s name. For example:

def my_function():
    print("Hello From My Function!")

Functions may also receive arguments (variables passed from the caller to the function). For example:

def my_function_with_args(username, greeting):
    print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))

Functions may return a value to the caller, using the keyword- return’. For example:

def sum_two_numbers(a, b):
    return a + b

How do you call functions in Python?

Simply write the function’s name followed by (), placing any required arguments within the brackets. For example, let us call the functions written above (in the previous example):

# Define our 3 functions
def my_function():
    print("Hello From My Function!")

def my_function_with_args(username, greeting):
    print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))

def sum_two_numbers(a, b):
    return a + b

# print(a simple greeting)
my_function()

#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")

# after this line x will hold the value 3!
x = sum_two_numbers(1,2)

Trinket.io on-line Python compiler

Exercise

In this exercise you’ll use an existing function, and while adding your own to create a fully functional program.

1) Add a function named list_benefits() that returns the following list of strings: “More organized code”, “More readable code”, “Easier code reuse”, “Allowing programmers to share and connect code together”.

2) Add a function named build_sentence(info) which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string is a benefit of functions!”

3) Run and see all the functions work together! Good luck.

# This function returns a list of strings as defined above. This is the answer code
# try coding this on your own below with the online compiler, use this answer code
# as a guide to solve the exercise. remember your only cheating yourself.
def list_benefits():
    return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"

# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
    return "%s is a benefit of functions!" % benefit


def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print(build_sentence(benefit))

name_the_benefits_of_functions()

Trinket.io on-line Python compiler

Note: If you run the above-unfinished code you will get the following (similar) error(s) in Python:

Traceback (most recent call last):
File “script.py”, line 14, in
name_the_benefits_of_functions()
File “script.py”, line 11, in name_the_benefits_of_functions
for benefit in list_of_benefits:
TypeError: ‘NoneType’ object is not iterable

OR

 

TypeError: ‘NoneType’ object is not iterable on line 11 in main.py

Related Videos:

MiltonMarketing.com Related Videos.

Related Posts:

Learn Modules and Packages in Python programming

What is Python?

Introduction to Python Programming Language

Python Basic Operators

Learn Python Lists

Learn Python Variables and Types

Comparing Python to other languages

Learn Code Introspection Python Programming

Python Basic String Operations

Learn about Numpy Arrays in Python programming

 

Connected through code, Choose Your Platform!

About the Author: Bernard Aybout

In the land of bytes and bits, a father of three sits, With a heart for tech and coding kits, in IT he never quits. At Magna's door, he took his stance, in Canada's wide expanse, At Karmax Heavy Stamping - Cosma's dance, he gave his career a chance. With a passion deep for teaching code, to the young minds he showed, The path where digital seeds are sowed, in critical thinking mode. But alas, not all was bright and fair, at Magna's lair, oh despair, Harassment, intimidation, a chilling air, made the workplace hard to bear. Management's maze and morale's dip, made our hero's spirit flip, In a demoralizing grip, his well-being began to slip. So he bid adieu to Magna's scene, from the division not so serene, Yet in tech, his interest keen, continues to inspire and convene.