Use built-in functions and library routines
11.1 Programming Basics – Built‑in Functions & Library Routines
Built‑in Functions
Built‑in functions are like pre‑made recipes that you can use straight away. They are already part of the language, so you don't need to write the code yourself. Think of them as kitchen appliances: you just turn them on and they do the work for you! 🍳
len()– returns the number of items in a list or string.sum()– adds up all numbers in an iterable.max(),min()– find the largest or smallest value.sorted()– returns a new sorted list.print()– displays information on the screen.
Library Routines
Library routines are collections of functions that you can import into your program. They are like a toolbox that contains many useful tools for specific tasks – for example, the math library for mathematical operations.
- Import the library:
import math - Call a function:
math.sqrt(25)returns5.0. - Use the function in your code to avoid reinventing the wheel.
Example: Using the math Library
| Function | Purpose | Example |
|---|---|---|
math.sqrt() |
Square root | math.sqrt(49) ➜ 7.0 |
math.sin() |
Sine of an angle (in radians) | math.sin(math.pi/2) ➜ 1.0 |
math.log() |
Natural logarithm | math.log(20) ➜ 2.9957 |
Analogy: Built‑in Functions are Kitchen Appliances
Imagine you’re cooking a meal. Instead of chopping every vegetable yourself, you use a food processor (built‑in function) to chop quickly. If you need a special sauce, you might use a pre‑made sauce kit (library routine) that already contains all the ingredients. This saves time and ensures consistency.
Exam Tips 📚
Know the most common built‑in functions: len(), sum(), max(), min(), sorted(), print().
Practice importing libraries: Write small snippets that use math, random, and datetime to become comfortable with syntax.
Remember the syntax: import library_name or from library_name import function_name. Mistakes in import statements are a common exam error.
Use comments: In exam answers, add brief comments to explain why you’re using a particular function or library. It shows understanding and can earn extra marks.
Time management: Allocate a few minutes at the start to identify which built‑in functions or libraries will simplify your solution before writing code.
Revision
Log in to practice.