0% found this document useful (0 votes)
7 views6 pages

Lab 10

Uploaded by

Arsalan Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views6 pages

Lab 10

Uploaded by

Arsalan Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Programming Fundamentals (CT-153) Practical Workbook

LAB # 10
OBJECTIVE
Implement functions in Python and , also find that using functions makes your
programs easier to write, read, test, and fix. In this lab you’ll also learn ways to pass
information to functions.

THEORY
Functions:

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

A function is a block of organized, reusable code that is used to perform a single,


related action. Functions provide better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but
you can also create your own functions. These functions are called user-defined
functions.

Defining a Function:
You can define functions to provide the required functionality. Here are simple rules
to define a function in Python.
• Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).

• Any input parameters or arguments should be placed within these


parentheses. You can also define parameters inside these parentheses.

• The first statement of a function can be an optional statement - the


documentation string of the function or docstring.

• The code block within every function starts with a colon (:) and is indented.

• The statement return [expression] exits a function, optionally passing back


an expression to the caller. A return statement with no arguments is the
same as return None.

Syntax:
def functionname( parameters ):
“””code in the function”””

1
Programming Fundamentals (CT-153) Practical Workbook

function_suite
return [expression](value to return to the main program)

Example#01:

✓ This example shows the simplest structure of a function. The line at 1 uses
the keyword def to inform Python that you’re defining a function. This is the
function definition, which tells Python the name of the function and, if
applicable, what kind of information the function needs to do its job. The
parentheses hold that information. In this case, the name of the function is
greet_user (), and it needs no information to do its job, so its parentheses are
empty. (Even so, the parentheses are required.) Finally, the definition ends in
a colon.
✓ Any indented lines that follow def greet_user (): make up the body of the
function. The text at line 2 is a comment called a docstring, which describes
what the function does. Docstrings are enclosed in triple quotes, which
Python looks for when it generates documentation for the functions in your
programs.
✓ The line print ("Hello!") is the only line of actual code in the body of this
function, so greet_user () has just one job: print ("Hello!"). When you want to
use this function, you call it. A function call tells Python to execute the code
in the function. To call a function, you write the name of the function,
followed by any necessary information in parentheses, as shown at x.
Because no information is needed here, calling our function is as simple as
entering greet_user (). As expected, it prints Hello!:

Output:

Example#02: Passing Information to the Function

Output:

2
Programming Fundamentals (CT-153) Practical Workbook

Calling a Function:
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt. Following is the example
to call printme() function

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print (str)
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Arguments:
An argument is a piece of information that is passed from a function call to a
function. When we call the function, we place the value we want the function to
work with in parentheses.
You can call a function by using the following types of formal arguments:

• Required arguments

• Keyword arguments

• Default arguments

Required Arguments:
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with
the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise
it gives a syntax error as follows –

# Function definition is here


def printme( str ):
"This prints a passed string into this function" print str
return;

# Now you can call printme function


printme()

3
Programming Fundamentals (CT-153) Practical Workbook

When the above code is executed, it produces the following result:

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Output:

Keyword Arguments:
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters.

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50

4
Programming Fundamentals (CT-153) Practical Workbook

Default Arguments:
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea
on default arguments, it prints default age if it is not passed –

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50
Name: miki
Age 35

Arbitrary Arguments:
If 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 way the function will
receive a tuple of arguments, and can access the items accordingly:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Passing a List as an Argument:


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]


my_function(fruits)

5
Programming Fundamentals (CT-153) Practical Workbook

Lab Exercise:

1. Write a function called check_armstrong() that accepts one parameter as


number. The function should return value whether the entered number is an
Armstrong number or not.

You might also like