0% found this document useful (0 votes)
26 views7 pages

Python Function Basics and Examples

Uploaded by

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

Python Function Basics and Examples

Uploaded by

Farrukh Abbasi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Lab-10
Functions in python

Objectives:
The purpose of this lab is to get you familiar with the functions in Python.

Apparatus:
Hardware Requirement
Personal computer.
Software Requirement
Anaconda, Jupyter Notebook/ Spyder
Theory:
Functions
Functions are useful for breaking up a large program to make it easier to read and
maintain. 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.
They are also useful if find yourself writing the same code at several different
points in your program. You can put that code in a function and call the function whenever you
want to execute that code. You can also use functions to create your own utilities, math
functions, etc.
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.

User Defined Function


Functions are defined with the def statement. The statement ends with a colon, and
the code that is part of the function is indented below the def statement. Here we create a simple
function that just prints something.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

The first two lines define the function. In the last three lines we call the function
twice.
One use for functions is if you are using the same code over and over again in
various parts of your program, you can make your program shorter and easier to understand by
putting the code in a function. For instance, suppose for some reason you need to print a box of
stars at several points in your program.
Put the code into a function, and then whenever you need a box, just call the
function rather than typing several lines of redundant code. Here is the function.

One benefit of this is that if you decide to change the size of the box, you just have
to modify the code in the function, whereas if you had copied and pasted the box-drawing code
everywhere you needed it, you would have to change all of them.

Arguments
We can pass values to functions. Here is an example:

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

When we call the print_hello function with the value 3, that value gets stored in the
variable n. We can then refer to that variable n in our function’s code.
You can pass more than one value to a function:

Returning values
We can write functions that perform calculations and return a result.

Example 1
Here is a simple function that converts temperatures from Celsius to Fahrenheit.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

The return statement is used to send the result of a function’s calculations back to
the caller. Notice that the function itself does not do any printing. The printing is done outside of
the function.
That way, we can do math with the result, like below.

If we had just printed the result in the function instead of returning it, the result
would have been printed to the screen and forgotten about, and we would never be able to do
anything with it.

Example 2
A function can return multiple values as a list.
Say we want to write a function that solves the system of equations ax + b y = e
and c x + d y = f. It turns out that if there is a unique solution, then it is given by x = (de-bf)/(ad -
bc) and y = (a f - ce)/(ad- bc). We need our function to return both the x and y solutions.

Example 3
A return statement by itself can be used to end a function early.

The same effect can be achieved with an if/else statement, but in some cases, using
return can make your code simpler and more readable.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Default arguments and keyword arguments


You can specify a default value for an argument. This makes it optional, and if the
caller decides not to use it, then it takes the default value. Here is an example:

Default arguments need to come at the end of the function definition, after all of
the non-default arguments.

Keyword arguments
A related concept to default arguments is keyword arguments. Say we have the
following function definition:
def fancy_print(text, color, background, style, justify):
Every time you call this function, you have to remember the correct order of the
arguments. Fortunately, Python allows you to name the arguments when calling the function, as
shown below:
fancy_print(text='Hi', color='yellow', background='black', style='bold',
justify='left')
fancy_print(text='Hi', style='bold', justify='left', background='black',
color='yellow')
As we can see, the order of the arguments does not matter when you use keyword
arguments. When defining the function, it would be a good idea to give defaults. For instance,
most of the time, the caller would want left justification, a white background, etc. Using these
values as defaults means the caller does not have to specify every single argument every time
they call the function.

Local variables
Let’s say we have two functions like the ones below that each use a variable i:

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

A problem that could arise here is that when we call func1, we might mess up the
value of I in func2. In a large program it would be a nightmare trying to make sure that we don’t
repeat variable names in different functions, and, fortunately, we don’t have to worry about this.
When a variable is defined inside a function, it is local to that function, which means it
essentially does not exist outside that function. This way each function can define its own
variables and not have to worry about if those variable names are used in other functions.

Global variables
On the other hand, sometimes you actually do want the same variable to be
available to multiple functions. Such a variable is called a global variable. You have to be careful
using global variables, especially in larger programs, but a few global variables used judiciously
are fine in smaller programs. Here is a short example:

The Anonymous Functions


These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
 Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an
expression.
 Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
 Although it appears that lambdas are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is to stack allocation by
passing function, during invocation for performance reasons.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Syntax
The syntax of lambda functions contains only a single statement, which is as
follows:
lambda [arg1 [,arg2,.....argn]]:expression
Following is an example to show how lambda form of function works −

Exercises
1. Write a function called rectangle that takes two integers m and n as arguments and prints
out an mxn box consisting of asterisks. Shown below is the output of rectangle(2,4)
****
****
2. Write a function called add_excitement that takes a list of strings and adds an
exclamation point (!) to the end of each string in the list. The program should modify the
original list and not return anything.
3. Write the same function except that it should not modify the original list and should
instead return a new list.
4. Write a function called sum_digits that is given an integer num and returns the sum of the
digits of num.
5. The digital root of a number n is obtained as follows: Add up the digits n to get a new
number. Add up the digits of that to get another new number. Keep doing this until you
get a number that has only one digit. That number is the digital root.
For example, if n = 45893, we add up the digits to get 4 + 5 + 8 + 9 + 3 = 29. We then
add up the digits of 29 to get 2 + 9 = 11. We then add up the digits of 11 to get 1 + 1 = 2.
Since 2 has only one digit, 2 is our digital root.
Write a function that returns the digital root of an integer n. [Note: there is a shortcut,
where the digital root is equal to n mod 9, but do not use that here.]

IQRA University, North Campus, Karachi

Common questions

Powered by AI

Functions in Python can return multiple values by returning them as a tuple or a list. This can be useful in scenarios where a function is solving equations and needs to return multiple results, such as finding the x and y coordinates from a set of algebraic equations .

Local variables are those defined within a function and can only be accessed within that function, ensuring that their modification does not affect other parts of the program. Global variables are accessible throughout the program but can be risky to use, especially in large programs, as they might lead to unintentional modifications by different parts of the code. Careful management is required when using global variables to prevent unpredictable behavior .

Default arguments allow function parameters to have predefined values, making them optional when the function is called. Keyword arguments enhance flexibility by allowing arguments to be passed out of order by naming them explicitly in the function call. This reduces the burden on the caller to remember argument order and allows the function to be called more clearly and concisely .

User-defined functions in Python are created using the 'def' keyword followed by the function name and parentheses. After the colon, the block of code is indented. These functions can be called by their name followed by parentheses and any necessary arguments. They can encapsulate code to perform specific tasks and can return values to the caller .

A digital root function repeatedly sums the digits of a number until a single digit is obtained. Avoiding the 'n mod 9' shortcut ensures that the function's logic directly aligns with its algorithmic description, which might be essential for educational or illustrative purposes, to demonstrate the understanding of iteration and digit manipulation explicitly .

The following function prints an mxn grid of asterisks: def rectangle(m, n): for _ in range(m): print('*' * n) This function is useful for visual representations in console-based applications or for creating simple ASCII art .

Functions make code easier to read and maintain by breaking up large programs into smaller, reusable blocks. They provide modularity and facilitate code reusability. By using functions, redundant code can be reduced, and updates or changes to the code require updates in only one place, avoiding multiple edits throughout the program .

Returning a calculation result allows the caller to use or manipulate the value further in the program, providing flexibility and autonomy over what to do with the result. Directly printing a result limits its usability to just displaying the output and prevents any further computations or use in program logic .

Lambda functions are advantageous for creating small, one-time use functions without the need for a separate definition using 'def'. They are useful for simple expressions and are often used in places where functions are passed as arguments, such as with the map, filter, and sort functions, because they can be defined inline quickly without cluttering the code with a full function definition .

Lambda functions are limited to a single expression and do not support multiple statements or commands, which can be restrictive for complex logic. They also have their own local namespace and cannot access variables outside their parameters and global namespace, making them less flexible in how they interact with surrounding code. Furthermore, debugging can be more challenging due to their concise nature and lack of name .

You might also like