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

Chapters 4(2)

This document is a comprehensive guide on defining and using functions in Python programming, covering topics such as creating functions, variable scope, global variables, and function parameters. It includes examples of function definitions, calling functions, and the use of modules to organize related functions. Additionally, it explains concepts like default values and keyword parameters to enhance function usability and readability.

Uploaded by

akdas.busra12
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)
4 views

Chapters 4(2)

This document is a comprehensive guide on defining and using functions in Python programming, covering topics such as creating functions, variable scope, global variables, and function parameters. It includes examples of function definitions, calling functions, and the use of modules to organize related functions. Additionally, it explains concepts like default values and keyword parameters to enhance function usability and readability.

Uploaded by

akdas.busra12
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/ 16

Python Programming

The source book of this course is illustrated below

The University of Turkish Aeronautical Associaiton


Computer Eng. dept.
2020-2021

Dr. Eng. Abdullatif BABA Fourth Chapter


(2)
Python Programming
Functions
Defining Functions

Now we turn to creating our own functions. As an example, let’s write a function to
calculate the area of a circle. Recall that a circle’s area is pi times its radius squared.
Here is a Python function that does this calculation:

import math
def area (radius): # function header (def followed by a space, and then the name of the function)
""" Returns the area of a circle After the function name comes the function parameter list.
with the given radius. This is a list of variable names that label the input to the
function. In our example we have a single input (radius).
For example: Finally a function header ends with a colon (:).
>>> area(5.5)
95.033177771091246
""" #function body. The code in this block is allowed to use the variables from the
return math.pi * radius ** 2 function header.
#Finally, the function returns a value using the return keyword. When a return statement is executed, Python jumps out of the
function and back to the point in the program where it was called.

Save this function inside a Python file (area.py would be a good name); then load it
into the IDLE editor and run it by pressing F5. If everything is typed correctly, a
prompt should appear and nothing else; a function is not executed until you call it.
Python Programming
Functions
Defining Functions

To call it, just type the name of the function, with the radius in brackets:

>>> area(1)

3.1415926535897931

>>> area(5.5)

95.033177771091246

>>> 2 * (area(3) + area(4))

157.07963267948966

Notice:
• The area function can be called just like any other function, the difference being that you have written the function
and so you have control over what it does and how it works.
• As with variable names, a function name must be one or more characters long and consist of letters, numbers, or the
underscore (_) character. The first character of the name cannot be a number.
Python Programming
Functions
Defining Functions

import math Python doc strings tend to follow a standard


def area (radius): formatting convention. Triple quotes are used
""" Returns the area of a circle to mark the beginning and end of the doc
with the given radius. string.
For example: Just as with built-in functions, you can easily
>>> area(5.5) access the doc strings for your own functions,
95.033177771091246 like this:
"""
return math.pi * radius ** 2 >>> print(area .__doc__)
Returns the area of a circle
with the given radius.
For example:
>>> area(5.5)
95.033177771091246

IDLE automatically reads the function doc


string and pops it up as an automatic tool tip.
Python Programming
Functions
Defining Functions

A function is not required to have an explicit return statement.


If you don’t put a return anywhere in a function, Python treats the function as if it ended
with this line: return None
The special value None is used to indicate that the function is not meant to be returning a
useful value

# hello.py
def say_hello_to(name):
""" Prints a hello message.
"""
cap_name = name.capitalize()
print('Hello ' + cap_name + ', how are you?')
Python Programming
Functions
Variable Scope
The scope of a variable is where in a program it is accessible, or visible.
import math
def dist(x, y, a, b):
s = (x - a) ** 2 + (y - b) ** 2
return math.sqrt(s)
def rect_area(x, y, a, b):
width = abs(x - a)
height = abs(y - b)
return width * height
Any variable assigned for the first time within a function is called a local variable.
The function dist has one local variable, s, while rect_area has two local variables, width and height.
The parameters of a function are also considered local. Thus dist has a total of five local variables—
x, y, a, b, and s; rect_area has a total of six.
Notice that variables x, y, a, and b appear in both functions, but they generally label different values.
Importantly, local variables are usable only within the function they are local to. No code outside of the
function can access its local variables. When a function ends, its local variables are automatically deleted.
Python Programming
Functions
Global variables
Variables declared outside of any function are called global variables, and they are readable
anywhere by any function or code within the program.

# global_error.py
name = 'Jack'
def say_hello():
print('Hello ' + name + '!')
def change_name(new_name):
name = new_name

The variable name is a global variable because it is not declared inside any function.
The say_hello() function reads the value of name and prints it to the screen as you would expect:
>>> say_hello()
Hello Jack!
However, things don’t work as expected when you call change_name:
>>> change_name('Piper')
>>> say_hello()
Hello Jack!
Nothing changed—name still labels the value 'Jack'. The problem is that Python treated name inside
the change_name function as being a local variable, and so ignored the global name variable.
Python Programming
Functions
Global variables
To access the global variable, you must use the global statement:

# global_correct.py
name = 'Jack'
def say_hello():
print('Hello ' + name + '!')
def change_name(new_name):
global name
name = new_name

This makes all the difference. Both functions now work as expected:
>>> say_hello()
Hello Jack!
>>> change_name('Piper')
>>> say_hello()
Hello Piper!
Python Programming
Functions
Using a main Function

It is usually a good idea to use at least one function in any Python program you write: main()
A main() function is, by convention, assumed to be the starting point of your program.

# password2.py
def main():
pwd = input('What is the password? ')
if pwd == 'apple':
print('Logging on ...')
else:
print('Incorrect password.')
print('All done!')

Notice that all the code is indented underneath the main function header.
When you run password2.py in IDLE, nothing happens—only the prompt appears. You must
type main() to execute the code within in it.
The advantage of using a main function is that it is now easier to rerun programs and pass in input
values.
Python Programming
Functions
Using a main Function

main() is entirely optional, and used only as a helpful convention.

# password3.py
def password(pwd):
if pwd == 'apple':
print('Logging on ...')
else:
print('Incorrect password.')
print('All done!')

>>> password('apple')
Logging on ...
All done!
Python Programming
Functions
Function Parameters

Parameters pass data into a function, and Python has several kinds of parameters.

Python passes parameters to a function using a technique known as pass by


reference. This means that when you pass parameters, the function refers to
the original passed values using new names.
# reference.py
def add(a, b):
return a + b
>>> x, y = 3, 4
>>> add(x, y)
7
>>> add(3,4)
7
After you set x and y in the first line, X is pointing to 3 and y is pointing to 4 .
Now when add(x, y) is called, Python creates two new variables, a and b, that refer to the values of x and y .
Notice that the values are not copied: They are simply given new names that the function uses to refer to them.
Pass by Value
Some programming languages, such as C++, can pass parameters using pass by value. When a parameter is passed by value, a copy of it is
made and passed to the function. If the value being passed is large, the copying can take up a lot of time and memory. Python does not
support pass by value.
Python Programming
Functions
Default values

It’s often useful to include a default value with a parameter.


For example, here we have given the greeting parameter a default value of 'Hello':

# greetings.py
def greet(name, greeting = 'Hello'):
print(greeting, name + '!')

>>> greet('Bob')
Hello Bob!
>>> greet('Bob', 'Good morning')
Good morning Bob!

An important detail about default parameters is that they are evaluated only once, the first time they are
called. In complicated programs, this can sometimes be the source of subtle bugs, so it is useful to keep
this fact in mind.
Python Programming
Functions
Keyword parameters
Keyword parameters have two big benefits.
• First, they make the parameter values clear, and thus help to make your programs easier
to read.
• Second, the order in which you call keyword parameters does not matter.
# shopping.py
def shop(where = 'store', what = 'pasta', howmuch = '10 pounds'):
print('I want you to go to the', where)
print('and buy', howmuch, 'of', what + '.')

>>> shop()
I want you to go to the store
and buy 10 pounds of pasta.
>>> shop(what = 'towels')
I want you to go to the store
and buy 10 pounds of towels.
>>> shop(howmuch = 'a ton', what = 'towels')
I want you to go to the store
and buy a ton of towels.
>>> shop(howmuch = 'a ton', what = 'towels', where = 'bakery')
I want you to go to the bakery
and buy a ton of towels.
Python Programming
Functions
To create a Python module
A module is collection of related functions and variables.
# shapes.py
>>> rectangle(4,4)
CHAR = '*'
"""A collection of functions ****
for printing basic shapes. ****
"" ****
def rectangle(height, width): ****
""" Prints a rectangle. """ >>> square(2)
for row in range(height): **
for col in range(width):
**
print(CHAR, end = '')
print() >>> triangle(4)
*
def square(side): **
""" Prints a square. """ ***
rectangle(side, side) ****
def triangle(height):
""" Prints a right triangle. """
for row in range(height):
for col in range(1, row + 2):
print(CHAR, end = '') A module is a toolbox of helpful functions that you can use when
print() writing other programs. Thus a module usually does not have
a main() function.
Python Programming
Functions
To create a Python module
The names within a module are visible outside the module only when you use
an import statement. To use a module, you simply import it. For example:
>>> import shapes
>>> dir(shapes)
['CHAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'rectangle', 'square', 'triangle']
>>> print(shapes.__doc__)
A collection of functions
for printing basic shapes.
>>> shapes.CHAR
'*'
>>> print(shapes.rectangle.__doc__)
Prints a rectangle.

You can also import everything at once:


>>> from shapes import *
>>> rectangle(3, 8)
********
********
********
Python Programming
Functions
To create a Python module
A very useful fact about modules is that they form namespaces. A namespace is essentially a
set of unique variable and function names.

Suppose having two modules: sales.py and bills.py


Suppose they work independently, but they both contain a function called save_file(fname)

So; the full name of the first function is sales.save_file(fname)


While, the full name of the second function is bills.save_file(fname)

Thus modules support independent development, by preventing name clashes.


Even if you are not working with other programmers, name clashes can be an annoying
problem in your own programs, especially as they get larger and more complex.
Of course, you can still run into name clashes as follows:
>>> from sales import *
>>> from bills import *
These kinds of import statements essentially dump everything from each module into the
current namespace, overwriting anything with the same name as they go

You might also like