Skip to main content

Python Language Fundamentals

Introduction​

This chapter solidifies your understanding of Python's built-in numeric and string types. You'll use the standard math module to perform calculations, and you'll explore some of the String class's most useful methods for formatting and validating text.

Python has several numeric types: int (arbitrary precision integers), float (double-precision floating point), and complex (numbers with a real and imaginary part, written as a + bj). Division has two flavours worth knowing: / always returns a float, while // performs floor division and truncates to a whole number — a common source of bugs for anyone coming from Python 2, where / between two integers used to floor-divide automatically.

Strings come with a rich set of built-in methods, several of which are extremely useful for formatting and validating user input: title(), upper(), lower(), format(), isdigit(), and the in operator for substring/membership checks.


Concepts​

The math module​

import math

r = 5.0
diameter = 2 * r
area = math.pi * r ** 2
circumference = 2 * math.pi * r
sphere_area = 4 * math.pi * r ** 2
sphere_volume = (4 / 3) * math.pi * r ** 3

Floor division vs true division​

print(7 / 2) # 3.5 (true division, always float)
print(7 // 2) # 3 (floor division, truncated)
print(4 // 3) # 1, not 1.333...

Useful string methods​

s = "hello world"
print(s.title()) # Hello World
print(s.upper()) # HELLO WORLD
print(s.lower()) # hello world
print("@" in "a@b.com") # True — membership check
print(len("1234")) # 4
print("1234".isdigit()) # True

String formatting with format()​

honorific = "Mr"
first = "john"
last = "SMITH"

full_name = "{}. {}{}".format(honorific, first[0].upper(), last.title())
print(full_name)

Complex numbers​

z = complex(2, 3) # 2 + 3j
print(z.real) # 2.0
print(z.imag) # 3.0

# math.sqrt can't handle negative numbers - use cmath instead
import cmath
print(cmath.sqrt(-4)) # 2j

Examples​

import math

r = float(input("Enter the radius: "))

print(f"Diameter: {2 * r}")
print(f"Circle area: {math.pi * r ** 2:.2f}")
print(f"Circumference: {2 * math.pi * r:.2f}")
print(f"Sphere area: {4 * math.pi * r ** 2:.2f}")
print(f"Sphere volume: {(4 / 3) * math.pi * r ** 3:.2f}")
email = "alice@example.com"
pin = "1234"

if "@" in email and len(pin) == 4 and pin.isdigit():
print(email.lower())
else:
print("Invalid details")

Challenges​

1. Circle and sphere calculations​

  • Prompt the user to enter the radius of a circle/sphere as a float.
  • Calculate and print the diameter, circle area, circumference, sphere area, and sphere volume.
  • Run the program with several different radius values to check your results.
💡 Show Answer
import math

r = float(input("Enter the radius: "))

diameter = 2 * r
area = math.pi * r ** 2
circumference = 2 * math.pi * r
sphere_area = 4 * math.pi * r ** 2
sphere_volume = (4 / 3) * math.pi * r ** 3

print(f"Diameter: {diameter}")
print(f"Circle area: {area:.2f}")
print(f"Circumference: {circumference:.2f}")
print(f"Sphere area: {sphere_area:.2f}")
print(f"Sphere volume: {sphere_volume:.2f}")

2. Formatting a name​

  • Prompt the user for an honorific (e.g. Mr or Mrs), a first name, and a last name.
  • Build a formatted name in the form Honorific. F. Lastname (first initial capitalised, last name capitalised with title()).
  • Print the formatted result.
💡 Show Answer
honorific = input("Enter your honorific (Mr/Mrs/Ms): ")
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")

formatted_name = f"{honorific}. {first_name[0].upper()}. {last_name.title()}"
print(formatted_name)

3. Validating an email and PIN​

  • Prompt the user for an email address and a 4-digit PIN (as strings).
  • Validate that the email contains an @ character.
  • Validate that the PIN is exactly 4 characters long and contains only digits.
  • If everything is valid, print the details in lowercase; otherwise print an error message.
💡 Show Answer
email = input("Enter your email: ")
pin = input("Enter your 4-digit PIN: ")

email_valid = "@" in email
pin_valid = len(pin) == 4 and pin.isdigit()

if email_valid and pin_valid:
print(f"Email: {email.lower()}, PIN: {pin.lower()}")
else:
print("Invalid email or PIN")

4. Solving a quadratic equation​

  • Prompt the user for the coefficients a, b, and c of a quadratic equation ax² + bx + c = 0.
  • Calculate the discriminant b² - 4ac.
  • If the discriminant is positive or zero, calculate and print the two real roots using math.sqrt().
  • If the discriminant is negative, use cmath.sqrt() to calculate the two complex roots instead.
💡 Show Answer
import math
import cmath

a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))

discriminant = b ** 2 - 4 * a * c

if discriminant >= 0:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
else:
root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)

print(f"Root 1: {root1}")
print(f"Root 2: {root2}")

5. Packages and modules​

  • Create a small package containing two or three simple modules (each with a function or two).
  • Write client code in a separate file that imports and uses these modules.
💡 Show Answer
# mypackage/greetings.py
def hello(name):
return f"Hello, {name}!"

# mypackage/math_utils.py
def double(n):
return n * 2

# mypackage/__init__.py
# (can be empty)

# client.py
from mypackage import greetings, math_utils

print(greetings.hello("Alice"))
print(math_utils.double(21))