Understand and use library routines

📚 Programming: Library Routines

What is a Library Routine?

A library routine is a pre‑written piece of code that performs a specific task. Think of it as a tool in a toolbox: you don’t have to build the tool yourself; you just pick it up and use it.

In Python, library routines live in modules and are accessed with the import statement.

Why Use Libraries?

  • ?? Saves time – no need to write code from scratch.
  • ?? Reduces bugs – well‑tested routines are reliable.
  • ?? Keeps code readable – clear names like math.sqrt() say what they do.

🔍 Common Python Library Routines

Module Routine What It Does
math sqrt(x) Returns the square root of x.
random randint(a, b) Returns a random integer between a and b (inclusive).
datetime now() Returns the current date and time.

🧰 Using a Library Routine: Step‑by‑Step

  1. Import the module: import math
  2. Call the routine: result = math.sqrt(25)
  3. Use the result in your program: print(result)

Example: Calculating the hypotenuse of a right‑angled triangle using the Pythagorean theorem.

import math

a = 3
b = 4
c = math.sqrt(a**2 + b**2)
print("Hypotenuse:", c)  # Output: Hypotenuse: 5.0

📐 Mathematics in Code

When you see a formula like $c = \sqrt{a^2 + b^2}$, you can directly translate it into code using math.sqrt() and the exponent operator **:

c = math.sqrt(a**2 + b**2)

📝 Examination Tips

Tip 1: Always import the module before using its routines.

Tip 2: When a question asks for a specific routine, write the exact function name (e.g., math.sqrt()) rather than describing what it does.

Tip 3: Practice writing small scripts that use at least two different library routines; this will boost confidence during the exam.

🤔 Quick Quiz

  • What routine would you use to generate a random number between 1 and 10?
  • How do you find the current year using the datetime module?

Revision

Log in to practice.

1 views 0 suggestions