Lec 4
Lec 4
Lec 4
>>>
L3 Introduction to Python - 2
Defining Functions in Python
>>> def hello():
print("Hello")
print("Computers are Fun")
>>>
• The first line tells Python we are defining a new function
called “hello”.
• The following lines are indented to show that they are part
of the hello function. Indent must be uniform
• The blank line (hit enter/return twice) on shell lets Python
know the definition is finished.
L3 Introduction to Python - 3
Executing, or Invoking, a Function
>>> def hello():
print("Hello")
print("Computers are Fun")
>>>
L3 Introduction to Python - 4
Problems with scripts (files without functions)
In the scripts we have seen, the entire script consists of just one
“block” of statements, executed in order – but this can become
unmanageable when your script is thousands of lines long,
contained in just one file.
You may want to use previously written code in other programs.
But cutting and pasting bits of code can create inadvertent variable
name clashes.
Scripts are not as flexible as we would like.
How to address this?
A general problem solving technique is to break down complex
problems into smaller, more manageable tasks: divide and conquer
Functions help us to avoid those problems
L3 Introduction to Python - 5
Functions as black box
L3 Introduction to Python - 6
Functions can take Inputs (Parameters)
• Functions can have changeable parts called parameters
that are placed between the brackets.
• The function “hello” did not need any parameters.
• Here is another function that has one parameter.
>>>
L3 Introduction to Python - 7
Invoking a Function that has parameter(s)
>>> greet()
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
greet()
TypeError: greet() takes exactly 1 argument (0 given)
L3 Introduction to Python - 8
Passing Parameters to Functions
>>> greet("Terry")
Hello Terry
How are you?
>>> greet("Paula")
Hello Paula
How are you?
>>>
L3 Introduction to Python - 9
Why You need to Use Functions
• Define once, use many times
– Replace repeated code sections with a parameterized
function
• Aids problem decomposition
– Even if code is used just once, helps break problem
into smaller, manageable pieces
– Like sections and paragraphs in a paper, or chapters
and paragraphs in a story
• Defining code as functions allows independent
testing/validation of code
L3 Introduction to Python - 10
Functions in a file
• When we exit the Python interpreter, all functions that
we defined will cease to exist.
• How about writing them in a file and saving it.
– Saves a LOT of retyping
• A programming environment is designed to help
programmers write programs and usually include
automatic indenting, highlighting, etc.
L3 Introduction to Python - 11
Creating a Module File
# File: cel2fah.py
# A simple program is illustrating Celsius to Fahrenheit conversion
def c2f():
print("This program converts Celsius into Fahrenheit")
cel = float(input("Enter temperature in Celsius: "))
fah = 9/5*cel+32
print("The temperature in Fahrenheit is:",fah)
print("End of the program.")
c2f()
L3 Introduction to Python - 12
cel2fah.py using Thonny IDE
L3 Introduction to Python - 14
Inside a Python Program
# File: cel2fah.py
# A simple program is illustrating Celsius to Fahrenheit
conversion
• Lines that start with # are called comments.
• Comments can begin in the middle of lines, too
• Intended for human readers and ignored by Python
– Important, so you or other maintainers of that code
know what you were intending
– Helps maintainability
• Python skips text from # to end of line
L3 Introduction to Python - 15
Inside a Python Program
def c2f():
L3 Introduction to Python - 16
Inside a Python Program
print(" This program converts Celsius into Fahrenheit")
L3 Introduction to Python - 17
Inside a Python Program
cel = float(input("Enter temperature in Celsius: "))
• cel is an example of a variable
• A variable is used to assign a name to a memory location
so that a value can be stored there and later retrieved.
• Variables come into existence when first assigned to
• The quoted text is displayed. The user enters a number
(which is text, i.e., just numerical letters).
• The function float converts the string, e.g., “0.5”, into
the number 0.5, which is then stored in cel.
• Note function call within function call (inner one called
first)
L3 Introduction to Python - 18
Inside a Python Program
fah = 9/5 * cel + 32
• This is called an assignment statement
• The part on the right-hand side (RHS) of the = is a
mathematical expression
• *, + and / are used to indicate multiplication, addition
and division respectively
• Once the value on the RHS is computed, it is stored back
into (assigned) into fah
print("The temperature in Fahrenheit is:",fah)
L3 Introduction to Python - 19
Indenting your Python programs
# File: cel2fah.py
# A simple program is illustrating Celsius to Fahrenheit conversion
def c2f():
print("This program converts Celsius into Fahrenheit")
cel = float(input("Enter temperature in Celsius: "))
fah = 9/5*cel+32
print("The temperature in Fahrenheit is:",fah)
print("End of the program.")
L3 Introduction to Python - 20
Inside a Python Program
c2f()
L3 Introduction to Python - 21
Executing a Python Program from a File
• You can run a program in a file any time you want
using one of the following methods:
1. Using Thonny, the easiest way is to click the green
forward arrow or select Run from the Run Module
2. On the command line (windows) or terminal (Mac
OS), enter python ./cel2fah.py (./ generally
not be need if path variable has been specified)
- Paths are where system looks for files and
programs
3. You can also double click the .py file in Windows to
run it “Option 2 and 3 will work if you have installed Python for the your
computer/laptop, which means that you download and install Python directly
from the official Python website (https://www.python.org) or through your
operating system's package manager (e.g., apt-get on Ubuntu, Homebrew on
macOS). This installs the Python interpreter and related tools globally on your
L3 Introduction to Python - 22 computer, making Python accessible from the command line or any terminal on
your system.”
Importing a module
>>> import cel2fah Note: No .py suffix!
This program converts Celsius into Fahrenheit
Enter temperature in Celsius: 0
The temperature in Fahrenheit is: 32.0
End of the program.
>>>
• This tells Python interpreter to load the file cel2fah.py
into the main memory.
• Since the last statement of cel2fah.py is c2f() the
function will get executed upon importing the file.
• Importing modules very common (particularly library
modules – huge range, performing many useful functions)
L3 Introduction to Python - 23
Importing a Module
• When Python imports a module, it executes each line.
– The def causes Python to create the function c2f:
– c2f() call at the end executes the function
• Upon first import, Python creates a companion file with
.pyc extension. This is an intermediate file containing
the byte code used by the interpreter.
• Modules need to be imported in a session only once.
L3 Introduction to Python - 24
Modules and Functions
L3 Introduction to Python - 25
Summary
• Python is an interpreted language. We can execute
commands directly in a shell or write a Python file.
L3 Introduction to Python - 26