KTU S1

The math Module and Basic Input/Output

By the end you should be able to: Use functions and constants from the math module, and perform basic input and output with input() and print(), including formatting and multiple values.

The Python Standard Library

Python ships with a large collection of ready-made modules — "batteries included". You import what you need rather than writing it yourself.

import math
print(math.sqrt(16))        # 4.0

Three import styles:

import math                 # math.sqrt(16)     — clearest, preferred
from math import sqrt       # sqrt(16)          — shorter
from math import *          # sqrt(16)          — AVOID
import math as m            # m.sqrt(16)        — common for long names

from math import * is discouraged because it dumps every name into your program and can silently overwrite your own variables.

Useful math functions

FunctionMeaningExample
math.sqrt(x)Square rootmath.sqrt(25) → 5.0
math.pow(x, y)xyx^y, returns floatmath.pow(2,3) → 8.0
math.floor(x)Round downmath.floor(3.7) → 3
math.ceil(x)Round upmath.ceil(3.2) → 4
math.fabs(x)Absolute value, floatmath.fabs(-5) → 5.0
math.factorial(n)n!n!math.factorial(5) → 120
math.gcd(a, b)Greatest common divisormath.gcd(12,18) → 6
math.log(x)Natural logmath.log(math.e) → 1.0
math.log10(x)Base-10 logmath.log10(100) → 2.0
math.sin(x)Sine, radiansmath.sin(math.pi/2) → 1.0
math.radians(d)Degrees → radiansmath.radians(180) → 3.14159…

Constants: math.pi, math.e, math.inf, math.nan

Two traps:

Trigonometric functions take radians, not degrees. math.sin(90) is not 1.0 — it's the sine of 90 radians, about 0.894. Convert first: math.sin(math.radians(90)).

math.sqrt of a negative raises ValueError. Check the sign first, or use the cmath module for complex results.

math.pow versus **

2 ** 3            # 8    int, exact
math.pow(2, 3)    # 8.0  always float
2 ** 0.5          # 1.414...

Prefer ** unless you specifically want a float. For very large integers ** stays exact while math.pow loses precision.

Output with print()

print("Hello")
print("Sum is", 42)                  # Sum is 42     — space between arguments
print("a", "b", sep="-")             # a-b
print("no newline", end="")          # suppresses the line break

print separates arguments with a space by default and ends with a newline. sep and end change both.

f-strings are the modern way to embed values:

name, marks = "Anjali", 87.5
print(f"{name} scored {marks}")           # Anjali scored 87.5
print(f"{marks:.1f}")                     # 87.5    one decimal place
print(f"{marks:8.2f}")                    # '   87.50'  width 8
print(f"{name:>10}")                      # '    Anjali' right-aligned

:.2f is worth memorising — it's how you present money and averages sensibly.

Input with input()

name = input("Enter your name: ")             # string
age = int(input("Enter your age: "))          # convert to int
height = float(input("Enter height in m: "))  # convert to float

Reading several values from one line:

a, b = input("Enter two numbers: ").split()          # both strings
a, b = map(int, input("Enter two numbers: ").split())  # both ints

split() breaks the string at whitespace; map(int, …) applies int to each piece.

If the user types something unconvertible, int() raises ValueError. Handle it with try/except when robustness matters.