2.2 — Function calls, Defining functions, Types of Errors

Function calls

Function take zero or more input values, perform an action or computation, and return the result value.

Input values passed to a function are called arguments.

A Function Call is an expression that looks like below:

function_name(argument1, argument2, …, argumentN)

How do we say it? — function “takes” argument(s) and “returns” a result. The result is also called the return value.

The number of arguments required by a function depends on how that function is defined.

Following are some built-in functions available in Python:

1# min() function takes 2 or more numbers and returns the minimum
2x = min(1, -4, 6)
3print(x) # -4
4
5# abs() function takes a number and returns absolute value of the number
6y = abs(-6)
7print(y) # 6
8
9# Gives an error if we do not give exactly one number
10z = abs(-1, 4)
11# TypeError: abs() takes exactly one argument (2 given)

Expressions vs Statements

An Expression is any valid combination of values, variables, operators, function calls.

When executed, it always evaluates to a single object.

1x = 3
2y = 4
3z = x ** 2 + y ** 2 # this expression evaluates to an int object
4print(z) # 25
5
6s = "hello"
7s2 = s * len(s) # this expression evaluates to str value
8print(s2) # hellohellohellohellohello

A statement is one or more lines of code that performs a task but does not evaluate to any value.

So, statements cannot be used as a part of an expression.

1>>> x = 123 # Does not evaluate to anything so nothing shows below
2>>> x # This is an trivially an expression
3123
4>>> 10 + (x = 123) # Trying to use assignment statement in an expression
5 10 + (x = 123)
6 ^
7SyntaxError: invalid syntax

Function composition

Function composition is calling a function with the result(s) of another function(s).

It is a very useful thing to do especially when we do not need to store intermediate results.

Using intermediate variables
1x = -5
2y = -8
3a = abs(x)
4b = abs(y)
5z = min(a, b)
6print(x, y, z)
Using composition
1x = -5
2y = -8
3z = min(abs(x), abs(y))
4print(x, y, z)

Check 2.2 (B) — Built-in Functions on Ed Lessons.

1num = 1.5e3
2city = "New York City"
3year = 2023
4print(num, city, year)

First, the arguments of print() are evaluated as:

1print(1500.0, "New York City", 2023)

Then, print() function is executed, which would display:

1500.0 New York City 2023

(Highlighted in red are spaces added by print())

1x1 = 1.5
2y1 = 2
3
4print("Point:", "(", x1, ",", y1, ")")

First, the arguments of print() are evaluated as:

1print("Point:", "(", 1.5, ",", 2, ")")

Then, print() function is executed, which would display:

Point: ( 1.5 , 2 )

(Highlighted in red are spaces added by print())

1x1 = 1.5
2y1 = 2
3
4point1 = "(" + str(x1) + ", " + str(y1) + ")"
5print("Point:", point1)

First, the arguments of print() are evaluated as:

1print("Point:", "(1.5, 2)")

Then, print() function is executed, which would display:

Point: (1.5, 2)

(Highlighted in red are spaces added by print())

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.

Defining a function that takes no arguments

Such functions always do the same thing each time they are executed.

1# Function definition
2def display_greeting():
3 print("+------------+")
4 print("| Welcome! |")
5 print("+------------+")
6
7# Function call
8display_greeting()
9
10# Call it again
11display_greeting()
Output
+------------+
|  Welcome!  |
+------------+
+------------+
|  Welcome!  |
+------------+

Functions with arguments and return value

A function can return a value using return statement.

1def f(x):
2 result = x * x - x - 1
3 return result
4 # OR: return x * x - x - 1
5
6# Call the function f
7y = f(5)
8print(y) # 19
9
10# Call again
11y = f(10)
12print(y) # 89
1# two parameters
2def mean(x, y):
3 return (x + y) / 2
4
5
6print(mean(3, 4)) # 3.5

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.

Creating a function — general form/syntax

1def function_name(param1, param2, ..., paramN): # 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.

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.

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

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:
2x = 5
3print("Square of x is)
4print(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.
3x = 5
4print("Value of x is", x)
5print("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.