0% found this document useful (0 votes)
16 views

Python Session 6-7 Functions

The document discusses functions in Python. It covers built-in functions like type(), len(), max(), min() and conversion functions like int(), float(), str(). It discusses defining new functions and how they are called. It also covers mathematical functions in the math module, random number functions in the random module and how to generate random integers and choose random elements from lists. Functions allow for code reusability and modular programming in Python.

Uploaded by

Pallavi Jayram
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Session 6-7 Functions

The document discusses functions in Python. It covers built-in functions like type(), len(), max(), min() and conversion functions like int(), float(), str(). It discusses defining new functions and how they are called. It also covers mathematical functions in the math module, random number functions in the random module and how to generate random integers and choose random elements from lists. Functions allow for code reusability and modular programming in Python.

Uploaded by

Pallavi Jayram
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

VIDYA VIKAS INSTITUTE

Department of Electronics & Communication Engineering OF ENGINEERING &


TECHNOLOGY

Python Application Programing-18EC646


Functions
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

Module 1
• Topic 1: Why should you learn to write programs
• Topic 2: Variables, expressions and statements
• Topic 3: Conditional execution
• Topic 4: Functions
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

Topic 4: Functions
4.1 Function calls
4.2 Built-in functions
4.3 Type conversion functions
4.4 Math functions
4.5 Random numbers
4.6 Adding new functions
4.7 Definitions and uses
4.8 Flow of execution
4.9 Parameters and arguments
4.10 Fruitful functions and void functions
4.11 Why functions?
4.12 Debugging
4.13 Exercises
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.1 Function calls


In the context of programming, a function is a named sequence of statements that performs a
computation. When you define a function, you specify the name and the sequence of statements.
Later, you can “call” the function by name. We have already seen one example of a function call:
>>> type(32)
<class ‘int’>
The name of the function is type. The expression in parentheses is called the
argument of the function. The argument is a value or variable that we are passing
into the function as input to the function. The result, for the type function, is the
type of the argument.
It is common to say that a function “takes” an argument and “returns” a result. The
result is called the return value.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.2 Built-in functions


Python provides a number of important built-in functions that we can use without needing to
provide the function definition.
The creators of Python wrote a set of functions to solve common problems and included them in
Python for us to use.
The max and min functions give us the largest and smallest values in a list, respectively:
>>> max('Hello world')
'w'
>>> min('Hello world')
‘‘
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).
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.2 Built-in functions

Another very common built-in function is the len function which tells us how many
items are in its argument.
If the argument to len is a string, it returns the number of characters in the string.
>>> len('Hello world')
11
These functions are not limited to looking at strings.
They can operate on any set of values.
You should treat the names of built-in functions as reserved words (i.e., avoid
using “max” as a variable name).
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.3 Type conversion functions


Python also provides built-in functions that convert values from one type to another. The int
function takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
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
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.3 Type conversion functions

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'
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.4 Math functions


Python has a math module that provides most of the familiar mathematical functions.
Before we can use the module, we have to import it:
>>> import math
This statement creates a module object named math. If you print the module object, you
get some information about it:
>>> print(math)
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and the name
of the function, separated by a dot (also known as a period). This format is called dot
notation.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.4 Math functions

>>> ratio = signal_power / noise_power


>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The first example computes the logarithm base 10 of the signal-to-noise ratio.
The math module also provides a function called log that computes
logarithms base e.
The second example finds the sine of radians. The name of the variable is a
hint that sin and the other trigonometric functions (cos, tan, etc.) take
arguments in radians.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.4 Math functions

To convert from degrees to radians, divide by 360 and multiply by 2π:


>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.7071067811865476
The expression math.pi gets the variable pi from the math module. The value of this
variable is an approximation of π, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the
square root of two divided by two:
>>> math.sqrt(2) / 2.0 0.
7071067811865476
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.5 Random numbers


The random module provides functions that generate pseudorandom numbers
The function random returns a random(pseudorandom numbers) float between 0.0 and 1.0 (including 0.0 but
not 1.0). Each time you call random, you get the next number in a long series.
To see a sample, run this loop:
import random
for i in range(10):
x = random.random()
print(x)
This program produces the following list of 10 random numbers between 0.0 and up to but not including 1.0.
0.11132867921152356 0.5950949227890241 0.04820265884996877 0.841003109276478
0.997914947094958 0.04842330803368111 0.7416295948208405 0.510535245390327
0.27447040171978143 0.028511805472785867
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.5 Random numbers


Exercise 1: Run the program on your system and see what numbers you get. Run the program more than once and see
what numbers you get.
The random function is only one of many functions that handle random numbers. The function randint takes the
parameters low and high, and returns an integer between low and high (including both).
>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
To choose an element from a sequence at random, you can use choice:
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
The random module also provides functions to generate random values from continuous distributions including Gaussian, exponential, gamma, and a few
more.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.6 Adding new functions


So far, we have only been using the functions that come with Python, but it is also possible to add new
functions.
A function definition specifies the name of a new function and the sequence of statements that execute
when the function is called.
Once we define a function, we can reuse the function over and over throughout our program.
Here is an example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics.
The rules for function names are the same as for variable names: letters, numbers and some punctuation
marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function,
and you should avoid having a variable and a function with the same name.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.6 Adding new functions

The empty parentheses after the name indicate that this function doesn’t take any
arguments.
Later we will build functions that take arguments as their inputs.
The first line of the function definition is called the header; the rest is called the
body. The header has to end with a colon and the body has to be indented.
By convention, the indentation is always four spaces.
The body can contain any number of statements.
>>> print(type(print_lyrics))
<class 'function'>
The value of print_lyrics is a function object, which has type “function”.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.6 Adding new functions


The syntax for calling the new function is the same as for built-in functions:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Once you have defined a function, you can use it inside another function.
For example, to repeat the previous refrain, we could write a function called repeat_lyrics:
def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.7 Definitions and uses


Pulling together the code fragments from the previous section, the whole program looks like this:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
This program contains two function definitions: print_lyrics and repeat_lyrics. Function definitions get
executed just like other statements, but the effect is to create function objects.
The statements inside the function do not get executed until the function is called, and the function
definition generates no output.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.7 Definitions and uses


Exercise 2: Move the last line of this program to the top, so the function call
appears before the definitions. Run the program and see what error message
you get.

Exercise 3: Move the function call back to the bottom and move the definition
of print_lyrics after the definition of repeat_lyrics. What happens when you run
this program?
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.8 Flow of execution


• In order to ensure that a function is defined before its first use, you have to know
the order in which statements are executed, which is called the flow of execution.
• Execution always begins at the first statement of the program. Statements are
executed one at a time, in order from top to bottom.
• Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function is
called.
• A function call is like a deviation in the flow of execution. Instead of going to the
next statement, the flow jumps to the body of the function, executes all the
statements there, and then comes back to pick up where it left off.
• When you read a program, you don’t always want to read from top to bottom.
Sometimes it makes more sense if you follow the flow of execution.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.9 Parameters and arguments


Some of the built-in functions we have seen require arguments. For example,
when you call math.sin you pass a number as an argument. Some functions take
more than one argument: math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called parameters.
Here is an example of a user-defined function that takes an argument:
def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named bruce. When the
function is called, it prints the value of the parameter (whatever it is) twice.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.9 Parameters and arguments


This function works with any value that can be printed.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> import math
>>> print_twice(math.pi)
3.141592653589793
3.141592653589793
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.9 Parameters and arguments


The same rules of composition that apply to built-in functions also apply to user-
defined functions, so we can use any kind of expression as an argument for print_twice:
>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
The argument is evaluated before the function is called, so in the examples the
expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.9 Parameters and arguments


You can also use a variable as an argument:
>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
The name of the variable we pass as an argument (michael) has nothing to do with
the name of the parameter (bruce). It doesn’t matter what the value was called
back home (in the caller); here in print_twice, we call everybody bruce.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.10 Fruitful functions and void functions


Some of the functions we are using, such as the math functions, yield results; for lack of a better name,
I call them fruitful functions. Other functions, like print_twice, perform an action but don’t return a
value. They are called void functions.
When you call a fruitful function, you almost always want to do something with the result; for example,
you might assign it to a variable or use it as part of an expression:
x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python displays the result:
>>> math.sqrt(5)
2.23606797749979
But in a script, if you call a fruitful function and do not store the result of the function in a variable, the
return value vanishes into the mist!
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.10 Fruitful functions and void functions


math.sqrt(5)
This script computes the square root of 5, but since it doesn’t store the result in a variable or display the result, it is
not very useful.
Void functions might display something on the screen or have some other effect, but they don’t have a return value.
If you try to assign the result to a variable, you get a special value called None.
>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None
The value None is not the same as the string “None”. It is a special value that has its own type:
>>> print(type(None))
< class 'NoneType‘>
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.10 Fruitful functions and void functions


To return a result from a function, we use the return statement in our function. For example, we could
make a very simple function called addtwo that adds two numbers together and returns a result.
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
8
When this script executes, the print statement will print out “8” because the addtwo function was called
with 3 and 5 as arguments. Within the function, the parameters a and b were 3 and 5 respectively.
The function computed the sum of the two numbers and placed it in the local function variable named
added. Then it used the return statement to send the computed value back to the calling code as the
function result, which was assigned to the variable x and printed out.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.11 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.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

4.12 Debugging
• If you are using a text editor to write your scripts, you might run into problems with spaces and
tabs. The best way to avoid these problems is to use spaces exclusively (no tabs).
• Most text editors that know about Python do this by default, but some don’t. Tabs and spaces
are usually invisible, which makes them hard to debug, so try to find an editor that manages
indentation for you.
• Also, don’t forget to save your program before you run it. Some development environments do
this automatically, but some don’t. In that case, the program you are looking at in the text
editor is not the same as the program you are running.
• Debugging can take a long time if you keep running the same incorrect program over and over!
• Make sure that the code you are looking at is the code you are running. If you’re not sure, put
something like print("hello") at the beginning of the program and run it again. If you don’t see
hello, you’re not running the right program!
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

Exercises
Exercise 4: What is the purpose of the “def” keyword in Python?
a) It is slang that means “the following code is really cool”
b) It indicates the start of a function
c) It indicates that the following indented section of code is to be
stored for later
d) b and c are both true
e) None of the above
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

Exercises
Exercise 5: What will the following Python program print out?
def fred():
print("Zap")
def jane():
print("ABC")
jane()
fred()
jane()
a) Zap ABC jane fred jane
b) Zap ABC Zap
c) ABC Zap jane
d) ABC Zap ABC
e) Zap Zap Zap
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

Exercises
Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and create a function
called computepay which takes two parameters (hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
hours = input('Enter Hours:')
hours = int(hours)
rate=input('Enter rate:')
rate= float(rate)
def computepay(hours,rate):
pay = hours*rate
return(pay)
pay=computepay(hours,rate)
print(pay)
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

Exercises
Exercise 7: Rewrite the grade program from the Enter score: 0.95
previous chapter using a function called
compute grade that takes a score as its A
parameter and returns a grade as a string. Run
the program repeatedly to test the various Enter score: perfect
different values for input.
Bad score
Score Grade
Enter score: 10.0
>= 0.9 A
Bad score
>= 0.8 B
Enter score: 0.75
>= 0.7 C
C
>= 0.6 D
Enter score: 0.5
< 0.6 F
F
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY

Exercises
score=input('enter the score:') elif score>=0.6:
def score_grade(score): grade="E"
try: elif score<0.6:
score=float(score) grade="F"
grade=[] else:
if score>0.1 and score<1.0: grade="BAD Score"
if score>= 0.9: except:
grade="A" grade="Bad Score"
elif score>=0.8: return grade
grade="B" grade=score_grade(score)
elif score>=0.7: print(grade)
grade="C"

You might also like