Programming Fundamentals
Welcome to the fourth lesson of Woodlands Computer Science!
What Are Functions?
Functions in programming are a set of instructions grouped together to achieve a specific task. You can pass data into a function (known as function parameters) and the function can return data.
You’ve already seen functions - Python has built-in functions that we’ve used throughout the last few lessons.
Here are some examples:
Built-in Function | Description |
---|---|
print() | Prints to the standard output device (display messages and information on the screen). |
str() | Returns the string version of the object which is passed in. |
range() | Returns a sequence of numbers, starting from 0. |
abs() | Returns the absolute value of a number. |
Why Use Functions?
- Functions make our code more organized and readable.
- Allow us to reuse the same code in different parts of the program.
- For example, a function could be created to compute the volume of a sphere if we needed to reuse this calculation throughout our program.
Function Syntax
- The
def
keyword marks the start of the function header. - Next, the name of the function, which follows the rules of writing identifiers in Python.
- The function name must be followed by parentheses with any number of parameters inside.
- A semicolon to mark the end of the function header.
- At least one line of indented code that will execute when the function is called.
- If want our function to return data, we can use the
return
keyword inside our function.
Function Example
In our first meeting, we created a program (Pythagorean Theorem) that calculated the value of $\sqrt{a^2+b^2}$.
If we needed to compute this value multiple times in our program, we could create a function instead of rewriting the code!
In this example:
- calculate_hypotenuse is the name of the function.
- a and b are the parameters/arguments of the function.
return (a**2 + b**2)**0.5
is the code that executes when our function is called.- Note the
return
keyword - this means that our function returns data whenever it is called.
- Note the
Scope of Functions
The “scope” of a function refers to where in the program the variable is recognized. For functions, the parameters and variables declared inside have a local scope. This means that they cannot be accessed outside of the function.
Scope Example 1
What if we want to modify or access a variable outside the local scope of our function?
We can use the global
keyword. By placing global
before any global variable name inside a function, it will be assigned its value and any modifications will not be local.
Scope Example 2
Activity
- Write a function that takes in a non-negative integer n and returns the sum of the first n integers.
- Bonus: Can you think of a very fast way to write your function without using a loop?
- Write a function that takes in a non-negative integer n and returns the value of n!
- Write a function that counts the number of lowercase and uppercase characters in a string, and prints the values.
- Secondly, the function should return a list containing all uppercase characters in the string.
Comments
Comments are used to provide explanatory information about the source code of a program.
Comments keep your code readable, especially if you plan to revisit your program in the future or share it with others.
In Python, single line comments are created by preceding the comment with #
and multi-line comments are created by enclosing the comments with a pair of triple apostrophes ('''
or """
).
Reading Text Files
Sometimes, instead of user input, we want to read information from a file instead. If we have a file named a.txt
which contains:
Hello!
Line 1.
Line 2.
- We can use Python’s built-in
open()
function to open the file. - To read a file, we can specify the text file’s path and name, and then pass in
'r'
as the function’s second argument. - Finally, we use the
.read()
method to see the contents of the file.
File Example
If we pass an integer N into the .read()
method, we will only read the first N characters.
The .readline()
method returns one line of the text file.
If we want to get rid of the new lines or any whitespace at the start or end of a line, we can use Python’s built-in .strip()
method
It is often useful to loop through a text file line by line.
Writing to a Text File
Sometimes, we want to output to a text file instead of to the screen. Once again, we will employ Python’s built-in open()
function.
However, the second parameter of the function depends on what you’re trying to achieve:
Second Parameter | Description |
---|---|
‘a’ | Adds to the end of the file, and creates a new file if the specified file does not exist. |
‘w’ | Overwrites any existing content of the file, creates a new file if the specified file does not exist. |
‘x’ | Creates a new file, throws an error if the specified file already exists. |
abs() | Returns the absolute value of a number. |
If we wanted to add more text to the end of a.txt
, we would use the following code:
Now that we have opened the file, we can use the .write()
method to add any text to the file!
Note that for the text file to save, you need to use the .close()
method after you are finished editing the file.
Bee Movie Activity
- Create a .txt file in the same directory as your code and copy/paste The Bee Movie script into it.
- Then, loop through the script, and write every line that contains the word “bee” in it into a separate text file.
- Bonus Problems:
- Print how many times each letter in the alphabet appears in the script.
- Print the three most frequent words in the entire script.
Try this in your own code editor!
Try/Except
Usually, errors in our code would stop the execution of our program. However, if we want to catch and handle these errors, we can use the try
and except
block.
The format of a try
and except
block is as follows (indentation is needed):
Try/Except Example
We can also specify a specific error to catch using except
. Consequently, like if/else
statements, we can stack except
statements:
We can use an else
statement after except
which will execute if no errors were encountered.
Try/Except Activity
Write a program that takes in two integers a and b as input, and prints the result of a/b.
Use try
and except
to print an error if the user tries to divide by 0, and reprompt for input until they provide valid values for a and b.