Use built-in functions and library routines

Resources | Subject Notes | Computer Science

Cambridge A-Level Computer Science 9618 - 11.1 Programming Basics

11.1 Programming Basics: Using Built-in Functions and Library Routines

Introduction

This section explores the fundamental concepts of using built-in functions and library routines in programming. These pre-written blocks of code provide ready-to-use functionality, saving development time and ensuring consistent results. Understanding how to utilize them effectively is crucial for writing efficient and robust programs.

Built-in Functions

Built-in functions are functions that are provided by the programming language itself. They are always available for use without requiring any imports. Examples include:

  • print(): Displays output to the console.
  • input(): Prompts the user for input and returns the entered value as a string.
  • len(): Returns the length of a sequence (e.g., string, list).
  • type(): Returns the data type of an object.
  • Mathematical functions (e.g., abs(), round()).

Library Routines (Modules)

Library routines, often referred to as modules, are collections of pre-written functions and classes that extend the functionality of the programming language. They need to be explicitly imported before use. Python has a rich standard library, and many third-party libraries are also available.

Example: The math module provides mathematical functions like sin(), cos(), sqrt(), etc.

Example Code (Python)

The following Python code demonstrates the use of built-in functions and a library routine:

Suggested diagram: A simple Python script demonstrating print, input, and math module usage.
Line Code Description
1 print("Hello, world!") Prints the string "Hello, world!" to the console.
2 name = input("Enter your name: ") Prompts the user to enter their name and stores the input in the variable name.
3 print("Hello, " + name + "!") Prints a personalized greeting using the entered name.
4 number = float(input("Enter a number: ")) Prompts the user to enter a number and converts the input string to a floating-point number.
5 square_root = math.sqrt(number) Calculates the square root of the entered number using the sqrt() function from the math module.
6 print("The square root is:", square_root) Prints the calculated square root to the console.

Benefits of Using Built-in Functions and Library Routines

  • Code Reusability: Avoids writing the same code repeatedly.
  • Efficiency: Pre-written functions are often optimized for performance.
  • Readability: Makes code easier to understand.
  • Consistency: Ensures consistent behavior across different parts of the program.

Further Exploration

Explore the Python documentation for the standard library to discover more powerful routines and modules. Experiment with different built-in functions and library routines to enhance your programming skills.