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

3.1 - Defining Functions, Errors & Debugging

The document defines functions, discusses types of errors in programs, and demonstrates how to define, call, debug and document functions in Python. It shows syntax errors from incorrect syntax, runtime errors called exceptions from problems during execution, and semantic or logic errors when a program produces incorrect output. It also demonstrates defining functions without arguments, with arguments, returning values, docstrings to document functions, and using the Thonny debugger to step through code line-by-line or expression-by-expression.

Uploaded by

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

3.1 - Defining Functions, Errors & Debugging

The document defines functions, discusses types of errors in programs, and demonstrates how to define, call, debug and document functions in Python. It shows syntax errors from incorrect syntax, runtime errors called exceptions from problems during execution, and semantic or logic errors when a program produces incorrect output. It also demonstrates defining functions without arguments, with arguments, returning values, docstrings to document functions, and using the Thonny debugger to step through code line-by-line or expression-by-expression.

Uploaded by

karlstephan065
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

3.

1 — Defining functions, Errors & Debugging

Types of Errors

Syntax Errors: When syntax is incorrect such as wrong punctuations,


invalid characters, missing quotes or parentheses etc.
Program does not run at all in the case of syntax errors.

1 # The following code has Syntax error due to missing double-quotes:


2 x = 5
3 print("Square of x is)
4 print(x ** 2)

Runtime Errors, also called Exceptions, occur when there is a problem


in the program during execution.
All code executes until an exception occurs.

1 # The following code produces NameError because


2 # variable y was not created before it is used.
3 x = 5
4 print("Value of x is", x)
5 print("Square of x is", y ** 2)
Semantic or Logic errors are said to occur when a program executes
without a problem but does not produce correct output as expected.
Debugging is the process of finding and removing errors in a program.

Using debugging in Thonny for better


understanding order of evaluation

In Thonny, we can use debugging features to understand how expressions


are evaluated:
To show variables and their values, go to menu “View -> Variables”
First, run program in debug mode by clicking the “Debug current
script” button (located next to the “Run current script” button and
looks like a bug)
Then, we have two options:
Run the program line-by-line using “Step over” button next to the
“Debug” button
Run program going inside each expression using “Step into”
button (located next to “Step over” button)
Try the following code in Thonny and use debug:
1 x = 7
2
3 # Increment value of variable x by 1
4 x = x + 1
5
6 #
7 y = x * x + 2 * (x + 1) + max(x + 1, 5)
8
9 # Calling print() with 4 arguments
10 print("x =", x, "y =", y)
11
12
13 message = "Hello"
14
15 # Calling print() with 1 argument
16 print("+" + "-" * (len(message) + 6) + "+")
17
18 # Calling print() with 3 arguments
19 print("+", "-" * (len(message) + 6), "+")
Defining a function

A function is a named block of code that performs a task.


So far we have been using (calling) functions to do specific tasks —
print() , input() , etc.

We can also define/create our own function:

1 def function_name(argument1, argument2, ..., argumentN): # function header


2 # function body
3 statement1
4 statement2
5 .
6 .
7 statementN

def is a Python keyword used to define functions

Notice how statements are indented by spaces, typically 4 spaces. In


Thonny, we can just use tab key once to indent by 4 spaces.
When we define a function using def keyword:

it is not executed.
Only the function name is created, which refers to the code block
inside the function.
When we call a function, the code block inside the function is actually
executed.
Function with no arguments

Such functions always do the same thing each time they are executed.
Output
1 # Function definition
+------------+
2 def display_greeting(): | Welcome! |
3 print("+------------+") +------------+
4 print("| Welcome! |") +------------+
| Welcome! |
5 print("+------------+")
+------------+
6
7 # Function call
8 display_greeting()
9
10 # Call it again
11 display_greeting()
Functions with arguments and return value

A function can return a value using return statement.

1 # Function that evaluates a polynomial


2 def f(x):
3 return x * x - x - 1
4
5 # Equivalently,
6 # def f(x):
7 # result = x * x - x - 1
8 # return result
9
10 # Call the function f
11 y = f(5)
12 print(y) # 19
13
14 # Call again with different argument
15 y = f(10)
16 print(y) # 89
17
18
19 # we can have more than one argument
20 def mean(x, y):
21 return (x + y) / 2
22
23
24 print(mean(3, 4)) # 3.5
25
26 print(mean(f(5), f(10))) # 54.0

Parentheses () are required to call a function. Omitting them is a


common mistake.
When a function is called, correct number of arguments must be
passed. It is an error to pass too many or too few arguments than
what a function definition expects.

Why create our own functions?

Functions allow code re-use; duplication of code can be avoided.


They help organize code into sections, which makes programs easier
to read and understand.
They make programs easier to fix.
Docstrings

A docstring (documentation string) is a multiline (triple-quoted) string


that we write after the header of a function to explain how the function
works.
It is an important part of programming to write such documentation.
You will be expected do so in your assignments.

1 def euclidean_distance(x1, y1, x2, y2):


2 """
3 Computes Euclidean distance between two 2D points.
4
5 Args:
6 x1: x-coordinate of first point (float)
7 y1: y-coordinate of first point (float)
8 x2: x-coordinate of second point (float)
9 y2: y-coordinate of second point (float)
10
11 Returns: the euclidean distance as a float
12 """
13 d = (x1 - x2) ** 2 + (y1 - y2) ** 2
14 return d ** 0.5

You might also like