Understand and Use Built-in Functions
In this step, we will explore the concept of functions and learn how to use Python's built-in functions. A function is a reusable block of code that performs a specific action. Python provides many built-in functions that are ready to use, such as print(), len(), and sum().
Let's start by writing a Python script to see some of these functions in action.
First, find the builtin_functions.py file in the WebIDE file explorer on the left. This file has been pre-created for you in the ~/project directory. Double-click the file to open it in the editor.
Now, add the following Python code to the builtin_functions.py file. This code demonstrates how to call several built-in functions.
## Using the print() function to display output
print("Hello, Python Functions!")
## Using the len() function to get the length of a string
message = "Hello World"
print(len(message))
## Using the sum() function to add numbers in a list
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
After writing the code, save the file by pressing Ctrl+S.
To run the script, open the integrated terminal in the WebIDE (if it's not already open, go to the top menu and select Terminal > New Terminal). Then, execute the following command:
python ~/project/builtin_functions.py
You will see the output from each print() call in the terminal.
Hello, Python Functions!
11
15
This output shows the results of calling the built-in functions: print() displays text, len() returns the number of characters in a string, and sum() calculates the sum of the items in a list.