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 minimum2x = min(1, -4, 6)3print(x) # -445# abs() function takes a number and returns absolute value of the number6y = abs(-6)7print(y) # 689# Gives an error if we do not give exactly one number10z = 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 = 32y = 43z = x ** 2 + y ** 2 # this expression evaluates to an int object4print(z) # 2556s = "hello"7s2 = s * len(s) # this expression evaluates to str value8print(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 below2>>> x # This is an trivially an expression31234>>> 10 + (x = 123) # Trying to use assignment statement in an expression5 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.
1x = -52y = -83a = abs(x)4b = abs(y)5z = min(a, b)6print(x, y, z)
1x = -52y = -83z = min(abs(x), abs(y))4print(x, y, z)
Check 2.2 (B) — Built-in Functions on Ed Lessons.
print() displays a space between arguments
1num = 1.5e32city = "New York City"3year = 20234print(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
1x1 = 1.52y1 = 234print("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 )
1x1 = 1.52y1 = 234point1 = "(" + 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)
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 definition2def display_greeting():3 print("+------------+")4 print("| Welcome! |")5 print("+------------+")67# Function call8display_greeting()910# Call it again11display_greeting()
+------------+ | 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 - 13 return result4 # OR: return x * x - x - 156# Call the function f7y = f(5)8print(y) # 19910# Call again11y = f(10)12print(y) # 89
1# two parameters2def mean(x, y):3 return (x + y) / 2456print(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 header2 # function body3 statement14 statement25 .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.45 Parameters:6 x1 (float): x-coordinate of first point7 y1 (float): y-coordinate of first point8 x2 (float): x-coordinate of second point9 y2 (float): y-coordinate of second point1011 Returns: the euclidean distance as a float12 """13 d = (x1 - x2) ** 2 + (y1 - y2) ** 214 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 = 53print("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 because2# variable y was not created before it is used.3x = 54print("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.