Python Datetime

Python Tutorial › Modules › Datetime

Python Datetime

IntermediateLesson 36 of 4712 min read11 runnable examples

Dates and times appear in almost every real program: log timestamps, expiry dates, report periods, test data. The datetime module handles creating, formatting, parsing and calculating with them.

In this lesson
  • Create date, time and datetime objects
  • Format dates with strftime
  • Parse text into dates with strptime
  • Add, subtract and compare dates with timedelta

The main classes

ClassHoldsExample
dateyear, month, daydate(2026, 11, 2)
timehour, minute, second, microsecondtime(9, 30)
datetimedate and time togetherdatetime(2026, 11, 2, 9, 30)
timedeltaa durationtimedelta(days=7)
timezonea fixed UTC offsettimezone.utc
Python
from datetime import date, time, datetime d = date(2026, 11, 2)t = time(9, 30, 15)dt = datetime(2026, 11, 2, 9, 30, 15) print(d, t, dt)print(d.year, d.month, d.day, d.weekday())   # Monday is 0print(dt.date(), dt.time())
Output
2026-11-02 09:30:15 2026-11-02 09:30:15
2026 11 2 0
2026-11-02 09:30:15

Today and now

Python
from datetime import date, datetime today = date.today()now = datetime.now()print(type(today).__name__, type(now).__name__)print(today == now.date())
Output
date datetime
True

The values depend on when you run the code, so press Try it to see your own date and time.

Format dates with strftime

strftime() turns a date into text using format codes:

CodeMeaningExample
%dday, 2 digits02
%mmonth, 2 digits11
%Yyear, 4 digits2026
%B / %bmonth name / shortNovember / Nov
%A / %aweekday / shortMonday / Mon
%H:%M:%S24-hour time14:05:09
%I %p12-hour hour, AM/PM02 PM
Python
from datetime import datetime dt = datetime(2026, 11, 2, 14, 5, 9)print(dt.strftime("%d-%m-%Y"))print(dt.strftime("%A, %d %B %Y"))print(dt.strftime("%I:%M %p"))print(dt.isoformat())print(f"{dt:%Y/%m/%d %H:%M}")
Output
02-11-2026
Monday, 02 November 2026
02:05 PM
2026-11-02T14:05:09
2026/11/02 14:05

Parse text with strptime

strptime() does the reverse: it reads text in a known format and returns a datetime.

Python
from datetime import datetime, date dt = datetime.strptime("02/11/2026 18:45", "%d/%m/%Y %H:%M")print(dt, dt.hour) print(date.fromisoformat("2026-12-25"))
Output
2026-11-02 18:45:00 18
2026-12-25

A mismatch between the text and the format raises ValueError:

Python
from datetime import datetimedatetime.strptime("2026-11-02", "%d/%m/%Y")
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    datetime.strptime("2026-11-02", "%d/%m/%Y")
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python3\Lib\_strptime.py", line 844, in _strptime_datetime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
                                    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python3\Lib\_strptime.py", line 574, in _strptime
    raise ValueError("time data %r does not match format %r" %
                     (data_string, format))
ValueError: time data '2026-11-02' does not match format '%d/%m/%Y'

Date arithmetic with timedelta

Python
from datetime import date, timedelta start = date(2026, 11, 2)print(start + timedelta(days=30))print(start - timedelta(weeks=2)) deadline = date(2026, 12, 31)remaining = deadline - start          # subtracting dates gives a timedeltaprint(remaining, remaining.days)
Output
2026-12-02
2026-10-19
59 days, 0:00:00 59
Python
from datetime import datetime, timedelta login = datetime(2026, 11, 2, 9, 15)logout = datetime(2026, 11, 2, 17, 40)worked = logout - loginprint(worked)print(worked.total_seconds() / 3600, "hours")
Output
8:25:00
8.416666666666666 hours

Compare and sort dates

Python
from datetime import date dates = [date(2026, 3, 1), date(2025, 12, 25), date(2026, 1, 15)]print(sorted(dates))print(max(dates), date(2026, 1, 1) < date(2026, 1, 2))
Output
[datetime.date(2025, 12, 25), datetime.date(2026, 1, 15), datetime.date(2026, 3, 1)]
2026-03-01 True

Age and days until a birthday

Python
from datetime import date def age_on(birth, on_day):    years = on_day.year - birth.year    if (on_day.month, on_day.day) < (birth.month, birth.day):        years -= 1          # birthday not reached yet this year    return years print(age_on(date(1995, 12, 20), date(2026, 11, 2)))print(age_on(date(1995, 6, 1), date(2026, 11, 2)))
Output
30
31

Time zones

A datetime without time zone information is “naive”. Attach a zone to make it “aware”. zoneinfo (Python 3.9+) uses the IANA time zone names.

Python
from datetime import datetime, timezone, timedelta utc_time = datetime(2026, 11, 2, 12, 0, tzinfo=timezone.utc)ist = timezone(timedelta(hours=5, minutes=30))print(utc_time.astimezone(ist))print(utc_time.astimezone(ist).strftime("%H:%M %z"))
Output
2026-11-02 17:30:00+05:30
17:30 +0530
Tip

Store and compare times in UTC, and convert to the user’s local zone only when displaying them.

Timestamps

Python
from datetime import datetime, timezone dt = datetime(2026, 1, 1, tzinfo=timezone.utc)ts = dt.timestamp()print(ts)print(datetime.fromtimestamp(ts, tz=timezone.utc))
Output
1767225600.0
2026-01-01 00:00:00+00:00

Check your understanding

Predict the output

from datetime import date, timedeltad = date(2024, 2, 28) + timedelta(days=2)print(d, d.strftime("%a"))

Quick quiz

1. Which method turns a datetime into formatted text?

2. What is the type of date(2026, 12, 31) - date(2026, 11, 2)?

3. What does %B produce?

Exercise: days until a deadline

Given today’s date and a deadline, print how many days are left and the deadline’s weekday name. Use fixed dates so the output is repeatable.

Input
today = 2026-11-02, deadline = 2027-01-15
Expected output
74 days left
Deadline is on a Friday
Hint 1

Subtract the dates and use .days.

Program Practice

Python datetime FAQ

How do I get the current date and time in Python?

from datetime import datetime then datetime.now(). Use date.today() for the date only.

How do I convert a string to a date in Python?

Use datetime.strptime(text, format), for example datetime.strptime("02/11/2026", "%d/%m/%Y"), or date.fromisoformat("2026-11-02") for ISO text.

How do I add days to a date in Python?

Add a timedelta: date + timedelta(days=10).

What is the difference between strftime and strptime?

strftime formats a date as text; strptime parses text into a date.

Python sys Module

Python Tutorial › Modules › sys Module

Python sys Module

IntermediateLesson 39 of 479 min read6 runnable examples

The sys module gives your program access to the Python interpreter itself: the command-line arguments it was started with, the version and platform, where it looks for modules, and the standard input and output streams.

In this lesson
  • Read command-line arguments with sys.argv
  • Stop a program with sys.exit and an exit code
  • Inspect the Python version and module search path
  • Write to stdout and stderr

Command-line arguments: sys.argv

sys.argv is a list of the words typed after python. Item 0 is the script name, and the rest are the arguments, always as strings.

greet.py
import sys print("script:", sys.argv[0])print("arguments:", sys.argv[1:]) if len(sys.argv) > 1:    name = sys.argv[1]    times = int(sys.argv[2]) if len(sys.argv) > 2 else 1    for _ in range(times):        print("Hello,", name)
Terminal
$ python greet.py Asha 2script: greet.pyarguments: ['Asha', '2']Hello, AshaHello, Asha$ python greet.pyscript: greet.pyarguments: []
Tip

For real command-line tools, use the argparse module. It builds --help output, converts types and reports missing arguments for you.

Exit with a status code: sys.exit

sys.exit() stops the program. By convention, exit code 0 means success and anything else means failure; CI systems and shell scripts check this code.

check.py
import sys def main(values):    if not values:        print("no values given", file=sys.stderr)        sys.exit(2)    print("total:", sum(map(int, values))) main(sys.argv[1:])
Terminal
$ python check.py 4 5 6total: 15$ python check.pyno values given$ python -c "import subprocess, sys; print('exit code:', subprocess.run([sys.executable, 'check.py']).returncode)"no values givenexit code: 2

Version and platform

Python
import sys print(sys.version_info.major, sys.version_info.minor)print(sys.version_info >= (3, 10))print(sys.platform)print(sys.maxsize == 2 ** 63 - 1)
Output
3 15
True
win32
True

Use a version check to fail early with a clear message:

Python
import sys if sys.version_info < (3, 10):    sys.exit("This script needs Python 3.10 or newer")print("version OK")
Output
version OK

Where Python looks for modules: sys.path

import searches the folders in sys.path, in order: the script’s folder first, then the standard library, then installed packages.

Python
import sys print(type(sys.path).__name__, len(sys.path) > 2)print(any(p.endswith("site-packages") for p in sys.path))
Output
list True
True
Note

A ModuleNotFoundError means none of these folders contains the module. Usually the package was installed into a different Python or virtual environment; see Modules & pip.

stdin, stdout and stderr

print() writes to sys.stdout. Error messages belong on sys.stderr, so they stay visible even when normal output is redirected to a file.

Python
import sys sys.stdout.write("normal output\n")print("also normal output", file=sys.stdout)print("number of bytes written:", sys.stdout.write("abc\n"))
Output
normal output
also normal output
abc
number of bytes written: 4

Reading all input lines from sys.stdin is the fastest way to read large input, which is common in coding challenges:

Python
import sys numbers = [int(line) for line in sys.stdin if line.strip()]print("sum:", sum(numbers))
Outputtyped input: 5, 10, 15
sum: 30

Other useful sys features

Python
import sys print(sys.getrecursionlimit())print(sys.getsizeof([]) < sys.getsizeof([1, 2, 3]))print(sys.executable.endswith(("python.exe", "python", "python3")))
Output
1000
True
True

Check your understanding

Quick quiz

1. What is sys.argv[0]?

2. What type are the values in sys.argv?

3. Which exit code means success?

Exercise: sum the arguments

Write add.py that prints the sum of all numbers passed on the command line, or exits with code 1 and a message if any argument is not a number.

Input
python add.py 3 4.5 10
Expected output
sum = 17.5
Hint 1

Wrap the conversion in try/except ValueError and call sys.exit(1) on failure.

Program Practice

Python sys module FAQ

How do I read command-line arguments in Python?

Use sys.argv, a list of strings where sys.argv[1:] are the arguments. For anything beyond a couple of arguments, use argparse.

What is the difference between sys.exit() and exit()?

exit() is a convenience for the interactive shell. Use sys.exit() in scripts; it raises SystemExit, which can carry an exit code or message.

How do I check the Python version in code?

Compare sys.version_info with a tuple: if sys.version_info >= (3, 10):.

Python Collections Module

Python Tutorial › Modules › Collections

Python Collections Module

IntermediateLesson 37 of 4711 min read9 runnable examples

The collections module adds specialised containers that solve common problems in one line: counting items, grouping values, building fast queues and giving names to tuple fields. Interview questions love them.

In this lesson
  • Count anything with Counter
  • Group values with defaultdict
  • Build queues with deque
  • Name tuple fields with namedtuple

Counter: count items

Counter takes any iterable and counts how many times each item appears.

Python
from collections import Counter words = "the cat and the hat and the bat".split()counts = Counter(words)print(counts)print(counts["the"], counts["dog"])     # missing items count as 0print(counts.most_common(2))
Output
Counter({'the': 3, 'and': 2, 'cat': 1, 'hat': 1, 'bat': 1})
3 0
[('the', 3), ('and', 2)]

Counting characters, and doing arithmetic with counters:

Python
from collections import Counter print(Counter("mississippi").most_common(3)) week1 = Counter(passed=40, failed=5)week2 = Counter(passed=42, failed=2, skipped=1)print(week1 + week2)print(sorted((week1 + week2).elements())[:3])
Output
[('i', 4), ('s', 4), ('p', 2)]
Counter({'passed': 82, 'failed': 7, 'skipped': 1})
['failed', 'failed', 'failed']

Two words are anagrams if their letter counts are equal:

Python
from collections import Counterprint(Counter("listen") == Counter("silent"), Counter("apple") == Counter("paple"))
Output
True True

defaultdict: no more KeyError

A defaultdict creates a default value the first time a missing key is used. Pass the type of the default: list, int, set…

Python
from collections import defaultdict employees = [("qa", "Asha"), ("dev", "Ravi"), ("qa", "Meena"), ("ops", "John")] teams = defaultdict(list)for team, name in employees:    teams[team].append(name)       # no need to check if the key exists print(dict(teams)) letters = defaultdict(int)for ch in "banana":    letters[ch] += 1print(dict(letters))
Output
{'qa': ['Asha', 'Meena'], 'dev': ['Ravi'], 'ops': ['John']}
{'b': 1, 'a': 3, 'n': 2}

deque: a fast queue

A deque (“deck”) adds and removes items quickly at both ends. Removing from the front of a list is slow for big lists; a deque does it instantly.

Python
from collections import deque queue = deque(["task1", "task2"])queue.append("task3")          # join at the backqueue.appendleft("urgent")     # jump the queueprint(queue) print(queue.popleft())         # serve from the frontprint(queue.pop())             # remove from the backprint(queue)
Output
deque(['urgent', 'task1', 'task2', 'task3'])
urgent
task3
deque(['task1', 'task2'])

maxlen keeps only the last N items, perfect for “recent history”:

Python
from collections import deque recent = deque(maxlen=3)for page in ["home", "search", "product", "cart", "checkout"]:    recent.append(page)print(list(recent)) d = deque([1, 2, 3, 4, 5])d.rotate(2)print(d)
Output
['product', 'cart', 'checkout']
deque([4, 5, 1, 2, 3])

namedtuple: tuples with field names

Python
from collections import namedtuple Employee = namedtuple("Employee", ["name", "dept", "salary"])e = Employee("Asha", "QA", 52000) print(e)print(e.name, e.salary)print(e._asdict())print(e._replace(salary=56000))
Output
Employee(name='Asha', dept='QA', salary=52000)
Asha 52000
{'name': 'Asha', 'dept': 'QA', 'salary': 52000}
Employee(name='Asha', dept='QA', salary=56000)

OrderedDict

Normal dicts keep insertion order since Python 3.7. OrderedDict still adds move_to_end() and an order-sensitive ==, which is handy for simple caches:

Python
from collections import OrderedDict cache = OrderedDict(a=1, b=2, c=3)cache.move_to_end("a")print(list(cache))cache.popitem(last=False)      # remove the oldestprint(list(cache))
Output
['b', 'c', 'a']
['c', 'a']

ChainMap

ChainMap looks up keys in several dicts in order, without copying them. It is a neat way to layer settings:

Python
from collections import ChainMap defaults = {"browser": "chromium", "headless": True, "timeout": 30}env = {"headless": False}cli = {"timeout": 60} settings = ChainMap(cli, env, defaults)print(settings["browser"], settings["headless"], settings["timeout"])
Output
chromium False 60

Which one to use

NeedUse
Count occurrencesCounter
Group items into lists or setsdefaultdict(list) / defaultdict(set)
Queue or stack with fast endsdeque
Lightweight record with namesnamedtuple (or dataclass)
Layered configurationChainMap

Check your understanding

Predict the output

from collections import Counter, defaultdictc = Counter("hello")d = defaultdict(int)d["x"] += 5print(c["l"], c["z"], dict(d))

Quick quiz

1. Which container counts items automatically?

2. What does defaultdict(list) give for a missing key?

3. Which is fastest for removing items from the front?

Exercise: most frequent words

Print the three most common words in the text, ignoring case and punctuation.

Input
"Test early. Test often! Automate the test, then test again."
Expected output
test 4
early 1
often 1
Hint 1

Lower-case the text, replace punctuation with spaces, then use Counter(words).most_common(3).

Program Practice

Python collections FAQ

What is Counter in Python?

collections.Counter is a dict subclass that counts hashable items. Counter("banana") gives {'a': 3, 'n': 2, 'b': 1}.

What is the difference between dict and defaultdict?

A normal dict raises KeyError for a missing key. A defaultdict creates the key with a default value from the factory you supplied.

When should I use deque instead of list?

When you add or remove items at the front, as in a queue. A deque does this in constant time; a list has to shift every item.

Python Exception Handling

Python Tutorial › Errors › Exception Handling

Python Exception Handling

IntermediateLesson 34 of 4713 min read10 runnable examples

An exception is Python’s way of saying “something went wrong here”: a file is missing, a number cannot be parsed, a key does not exist. Handling exceptions lets your program recover, retry or report the problem clearly instead of crashing.

In this lesson
  • Read a traceback
  • Catch specific exceptions with try/except
  • Use else and finally correctly
  • Raise your own and define custom exceptions

What an exception looks like

When an error is not handled, Python stops and prints a traceback. Read it from the bottom: the last line names the exception and the message, and the lines above show where it happened.

Python
def average(values):    return sum(values) / len(values) print(average([10, 20]))print(average([]))
Output
15.0
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(average([]))
          ~~~~~~~^^^^
  File "main.py", line 2, in average
    return sum(values) / len(values)
           ~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero

Common built-in exceptions

ExceptionTypical cause
ValueErrorRight type, wrong value: int("abc")
TypeErrorWrong type: "2" + 2
KeyErrorMissing dict key
IndexErrorList index out of range
ZeroDivisionErrorDivision by zero
FileNotFoundErrorOpening a file that does not exist
AttributeErrorObject has no such attribute or method
NameErrorUsing a name that was never defined

try and except

Put the risky code in try. If an exception happens, Python jumps to the matching except block and continues after it.

Python
text = "12a"try:    number = int(text)    print("Parsed", number)except ValueError:    print(f"{text!r} is not a number")print("program continues")
Output
'12a' is not a number
program continues

Catch specific exceptions

Catch only the errors you expect and know how to handle. Use several except blocks, or a tuple, for different errors. as e gives you the exception object.

Python
def safe_divide(a, b):    try:        return a / b    except ZeroDivisionError:        return "cannot divide by zero"    except TypeError as e:        return f"bad input: {e}" print(safe_divide(10, 4))print(safe_divide(10, 0))print(safe_divide(10, "2"))
Output
2.5
cannot divide by zero
bad input: unsupported operand type(s) for /: 'int' and 'str'
Python
data = {"items": [1, 2]}for key, index in [("items", 5), ("users", 0)]:    try:        print(data[key][index])    except (KeyError, IndexError) as e:        print(type(e).__name__, e)
Output
IndexError list index out of range
KeyError 'users'
Watch out

Avoid a bare except: or except Exception: that swallows every error silently. It hides real bugs, including typos. If you must catch broadly, log the error.

else and finally

  • else runs only if the try block raised no exception.
  • finally runs always, error or not. Use it for clean-up such as closing a connection.
Python
def read_number(text):    try:        n = int(text)    except ValueError:        print("  invalid:", text)    else:        print("  valid:", n)    finally:        print("  done with", repr(text)) read_number("42")read_number("x")
Output
  valid: 42
  done with '42'
  invalid: x
  done with 'x'
Tip

For files and connections, a with statement does the clean-up for you, so you rarely need finally for that. See File Handling.

Raise an exception

Use raise to signal that something is wrong in your own code. Choose the built-in exception that fits best and write a helpful message.

Python
def set_age(age):    if not isinstance(age, int):        raise TypeError(f"age must be an int, got {type(age).__name__}")    if age < 0:        raise ValueError("age cannot be negative")    return age for value in [30, -1, "30"]:    try:        print("ok", set_age(value))    except (TypeError, ValueError) as e:        print("rejected:", e)
Output
ok 30
rejected: age cannot be negative
rejected: age must be an int, got str

A bare raise inside except re-raises the same exception after you have logged it:

Python
try:    {}["missing"]except KeyError:    print("logging the error, then passing it on")    raise
Output
logging the error, then passing it on
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    {}["missing"]
    ~~^^^^^^^^^^^
KeyError: 'missing'

Custom exceptions

Create your own exception classes by inheriting from Exception. They make errors easy to recognise and catch.

Python
class InsufficientFundsError(Exception):    def __init__(self, balance, amount):        super().__init__(f"need {amount}, only {balance} available")        self.balance = balance        self.amount = amount def withdraw(balance, amount):    if amount > balance:        raise InsufficientFundsError(balance, amount)    return balance - amount try:    withdraw(500, 800)except InsufficientFundsError as e:    print("Declined:", e)    print("Short by", e.amount - e.balance)
Output
Declined: need 800, only 500 available
Short by 300

Exception chaining

raise ... from ... keeps the original error attached, so the traceback shows both:

Python
def load_port(config):    try:        return int(config["port"])    except (KeyError, ValueError) as e:        raise RuntimeError("invalid config: port") from e load_port({"port": "eighty"})
Output
Traceback (most recent call last):
  File "main.py", line 3, in load_port
    return int(config["port"])
ValueError: invalid literal for int() with base 10: 'eighty'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    load_port({"port": "eighty"})
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "main.py", line 5, in load_port
    raise RuntimeError("invalid config: port") from e
RuntimeError: invalid config: port

Retry pattern

Python
attempts = iter(["timeout", "timeout", "ok"]) def call_api():    result = next(attempts)    if result == "timeout":        raise TimeoutError("server did not answer")    return "200 OK" for attempt in range(1, 4):    try:        print(call_api(), "on attempt", attempt)        break    except TimeoutError as e:        print(f"attempt {attempt}: {e}")
Output
attempt 1: server did not answer
attempt 2: server did not answer
200 OK on attempt 3

Check your understanding

Predict the output

def f():    try:        return "try"    finally:        print("finally runs first") print(f())

Quick quiz

1. When does the else block of a try statement run?

2. Which exception does int("abc") raise?

3. How do you create a custom exception?

4. Why is a bare except: discouraged?

Exercise: safe average

Write safe_average(items) that converts every item to float, skips items that cannot be converted (printing a warning), and returns 0 for an empty result.

Input
["10", "abc", "20.5", None, "30"]
Expected output
skipping 'abc'
skipping None
20.166666666666668
0
Hint 1

Catch both ValueError (bad text) and TypeError (None).

Program Practice

Python exception handling FAQ

What is the difference between an error and an exception in Python?

In everyday use they mean the same thing. Technically, syntax errors stop the file from running at all, while exceptions happen while the program runs and can be caught.

Can I catch multiple exceptions in one except?

Yes. Use a tuple: except (ValueError, TypeError) as e:.

What is the purpose of finally in Python?

finally holds clean-up code that must run whether or not an exception happened, such as closing a connection.

How do I print the full traceback of a caught exception?

Use the traceback module: traceback.print_exc() inside the except block, or logging.exception("message").

Python Modules

Python Modules Tutorial

Introduction

Python, renowned for its simplicity and versatility, owes a significant part of its power to modules. Modules are an essential concept in Python programming, enabling developers to organize code, enhance reusability, and maintain a clean project structure. In this tutorial, we’ll delve into the world of Python modules, exploring their significance, creation, unique features, and diverse applications.

Importance of Modules

Modules serve as building blocks that encapsulate code, variables, and functions, making it easier to manage and scale projects. By grouping related functionalities together, modules facilitate code readability, reduce redundancy, and enable collaborative development. This modular approach enhances the maintainability and extensibility of Python applications.

Creating a Module

Creating a module is a straightforward process. To begin, save a collection of related functions and variables in a .py file. This file name becomes the module name. For instance, let’s create a simple module named math_operations:

				
					# math_operations.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

				
			

Features

Python modules offer a range of features that streamline development and optimize code organization:

  1. Namespace Isolation: Modules create separate namespaces, preventing naming conflicts between variables and functions.
  2. Reusability: Code encapsulated within modules can be easily reused in multiple projects.
  3. Modularity: Modules support a modular architecture, enhancing code separation and maintainability.
  4. Information Hiding: By controlling what is exposed in a module’s interface, you can encapsulate implementation details.
  5. Standard Library: Python’s standard library provides a plethora of pre-built modules, saving time and effort in coding common functionalities.

Different Python Modules

  1. Math Module: The math module offers a suite of mathematical functions. Let’s calculate the factorial of a number using the math module:
				
					import math
num = 5
factorial = math.factorial(num)
print(f"The factorial of {num} is {factorial}")

				
			
  1. Datetime Module: The datetime module simplifies date and time manipulation. Here’s an example of getting the current date and time:
				
					import datetime
current_datetime = datetime.datetime.now()
print(f"Current date and time: {current_datetime}")

				
			
  1. Random Module: The random module facilitates random number generation. Let’s generate a random integer between 1 and 100:
				
					import random
random_number = random.randint(1, 100)
print(f"Random number: {random_number}")

				
			
  1. JSON Module: The json module simplifies JSON encoding and decoding. Here, we’ll encode a Python dictionary as a JSON string:
				
					import json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_string = json.dumps(data)
print(f"JSON representation: {json_string}")

				
			

Python Classes & Objects

Python Tutorial › Object-Oriented Python › Classes & Objects

Python Classes & Objects

IntermediateLesson 31 of 4714 min read8 runnable examples

A class is a blueprint, and an object is a thing built from that blueprint. Classes bundle data (attributes) with the functions that work on it (methods). Page objects in test automation, models in web apps and most libraries you use are built from classes.

In this lesson

  • Define a class and create objects
  • Use __init__ and self correctly
  • Class vs instance attributes
  • Special methods, classmethods and dataclasses

Define a class and create objects

Python
class Dog:    pass rex = Dog()bella = Dog()print(type(rex).__name__, rex is bella)

Output
Dog False

Each call to Dog() creates a new, separate object (an instance) of the class.

__init__ and self

__init__ runs automatically when an object is created. Use it to set the object’s starting attributes. self is the object being created; Python passes it for you.

Python
class Account:    def __init__(self, owner, balance=0):        self.owner = owner          # instance attribute        self.balance = balance acc1 = Account("Asha", 500)acc2 = Account("Ravi")print(acc1.owner, acc1.balance)print(acc2.owner, acc2.balance)

Output
Asha 500
Ravi 0
Note

self is just the conventional name for the first parameter. Every method needs it, because it is how the method reaches the object’s data.

Methods

Methods are functions defined inside a class. Call them on an object with a dot.

Python
class Account:    def __init__(self, owner, balance=0):        self.owner = owner        self.balance = balance     def deposit(self, amount):        if amount <= 0:            raise ValueError("Deposit must be positive")        self.balance += amount        return self.balance     def withdraw(self, amount):        if amount > self.balance:            print("Insufficient funds")            return self.balance        self.balance -= amount        return self.balance acc = Account("Asha", 100)print(acc.deposit(50))print(acc.withdraw(500))print(acc.withdraw(30))

Output
150
Insufficient funds
150
120

acc.deposit(50) is really Account.deposit(acc, 50): the object goes into self.

Class attributes vs instance attributes

An attribute set on the class is shared by all objects. One set on self belongs to a single object.

Python
class Employee:    company = "SQA Tools"          # class attribute: shared    count = 0     def __init__(self, name):        self.name = name           # instance attribute: per object        Employee.count += 1 a = Employee("Asha")b = Employee("Ravi")print(a.company, b.company, Employee.count)print(a.name, b.name)

Output
SQA Tools SQA Tools 2
Asha Ravi

__str__ and __repr__

Special methods (with double underscores) let your objects work with built-in functions. __str__ controls print(); __repr__ controls how the object looks in lists and the shell.

Python
class Product:    def __init__(self, name, price):        self.name = name        self.price = price     def __str__(self):        return f"{self.name} (Rs {self.price})"     def __repr__(self):        return f"Product({self.name!r}, {self.price})" p = Product("Mouse", 349)print(p)print([p, Product("Pen", 10)])

Output
Mouse (Rs 349)
[Product('Mouse', 349), Product('Pen', 10)]

Other useful special methods include __len__, __eq__ and __lt__:

Python
class Playlist:    def __init__(self, *songs):        self.songs = list(songs)     def __len__(self):        return len(self.songs)     def __eq__(self, other):        return self.songs == other.songs p1 = Playlist("a", "b")p2 = Playlist("a", "b")print(len(p1), p1 == p2, p1 is p2)

Output
2 True False

classmethod and staticmethod

  • A @classmethod receives the class (cls) instead of an object. It is often used as an alternative constructor.
  • A @staticmethod receives neither; it is a plain function grouped with the class.
Python
class Temperature:    def __init__(self, celsius):        self.celsius = celsius     @classmethod    def from_fahrenheit(cls, f):        return cls(round((f - 32) * 5 / 9, 1))     @staticmethod    def is_freezing(celsius):        return celsius <= 0 t = Temperature.from_fahrenheit(98.6)print(t.celsius, Temperature.is_freezing(t.celsius))

Output
37.0 False

Dataclasses

For classes that mainly hold data, @dataclass writes __init__, __repr__ and __eq__ for you:

Python
from dataclasses import dataclass, field @dataclassclass TestCase:    name: str    priority: int = 3    tags: list = field(default_factory=list) tc = TestCase("login works", 1, ["smoke"])print(tc)print(tc == TestCase("login works", 1, ["smoke"]))

Output
TestCase(name='login works', priority=1, tags=['smoke'])
True

Check your understanding

Predict the output

class Counter:    total = 0    def __init__(self):        self.mine = 0    def hit(self):        self.mine += 1        Counter.total += 1 a, b = Counter(), Counter()a.hit(); a.hit(); b.hit()print(a.mine, b.mine, Counter.total)

Quick quiz

1. What is self in a method?

2. When does __init__ run?

3. Which method controls what print(obj) shows?

4. What does a @classmethod receive as its first argument?

Exercise: rectangle class

Create a Rectangle class with width and height, methods area() and perimeter(), and a __str__ that prints like Rectangle 4x6.

Input

Rectangle(4, 6)
Expected output

Rectangle 4x6
Area: 24
Perimeter: 20
Hint 1

Store width and height on self in __init__.

Program Practice

48 Python OOP Programs

Every program has a step-by-step explanation, colour-coded code and its real output.

Start practising →

Related sets:All practice sets

Python classes and objects FAQ

What is the difference between a class and an object?

A class is the definition (the blueprint). An object is a concrete instance created from it, with its own attribute values.

Why do Python methods need self?

self is how a method accesses the object it was called on. Python passes the object automatically as the first argument.

What is __init__ in Python?

It is the initialiser that runs right after an object is created. It sets up the object’s attributes.

When should I use a dataclass?

When a class mainly stores data. @dataclass generates the boilerplate methods and keeps the class short and readable.

Python NumPy

Python Tutorial › Libraries & Databases › NumPy

Python NumPy

IntermediateLesson 45 of 4714 min read11 runnable examples

NumPy is the foundation of numerical Python. Its ndarray stores numbers in a compact block of memory and runs maths on whole arrays at once, which is far faster and shorter than looping over lists. Pandas, scikit-learn and Matplotlib are all built on it.

In this lesson
  • Create arrays and inspect their shape
  • Index, slice and filter with masks
  • Vectorised maths and broadcasting
  • Statistics along rows and columns

Install and import

Terminal
python -m pip install numpy
Python
import numpy as npprint(np.__version__.split(".")[0] >= "2")
Output
True

np is the standard alias; every NumPy example you find online uses it.

Create arrays

Python
import numpy as np a = np.array([3, 1, 4, 1, 5])print(a, a.dtype, a.shape) m = np.array([[1, 2, 3], [4, 5, 6]])print(m)print(m.shape, m.ndim, m.size)
Output
[3 1 4 1 5] int64 (5,)
[[1 2 3]
 [4 5 6]]
(2, 3) 2 6

Helper functions build common arrays:

Python
import numpy as np print(np.zeros(3), np.ones((2, 2), dtype=int).tolist())print(np.arange(0, 10, 2))print(np.linspace(0, 1, 5))print(np.eye(3, dtype=int))
Output
[0. 0. 0.] [[1, 1], [1, 1]]
[0 2 4 6 8]
[0.   0.25 0.5  0.75 1.  ]
[[1 0 0]
 [0 1 0]
 [0 0 1]]

Arrays vs lists

Maths on an array applies to every element. The same operator on a list does something else:

Python
import numpy as np prices = [100, 250, 80]print(prices * 2)                 # list: repeated arr = np.array(prices)print(arr * 2)                    # array: every element doubledprint(arr * 1.18)                 # add 18% tax to allprint(arr + np.array([1, 2, 3]))  # element-wise addition
Output
[100, 250, 80, 100, 250, 80]
[200 500 160]
[118.  295.   94.4]
[101 252  83]

Reshape

Python
import numpy as np a = np.arange(1, 13)grid = a.reshape(3, 4)print(grid)print(grid.T.shape)               # transpose: 4 x 3print(grid.flatten()[:5])
Output
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
(4, 3)
[1 2 3 4 5]

Indexing and slicing

For 2-D arrays, use [row, column]:

Python
import numpy as np g = np.arange(1, 13).reshape(3, 4)print(g[0, 0], g[2, -1])print(g[1])            # second rowprint(g[:, 1])         # second columnprint(g[0:2, 1:3])     # sub-grid
Output
1 12
[5 6 7 8]
[ 2  6 10]
[[2 3]
 [6 7]]

Boolean masks

A comparison gives an array of True/False values, which you can use to select elements:

Python
import numpy as np scores = np.array([45, 82, 67, 91, 38, 74])mask = scores >= 60print(mask)print(scores[mask])print(scores[(scores > 50) & (scores < 80)])   # use & and |, not and/orprint(np.where(scores >= 60, "pass", "fail"))
Output
[False  True  True  True False  True]
[82 67 91 74]
[67 74]
['fail' 'pass' 'pass' 'pass' 'fail' 'pass']

Statistics

Python
import numpy as np sales = np.array([[120, 90, 150],                  [80, 110, 95]])       # 2 stores x 3 monthsprint(sales.sum(), sales.mean().round(2))print(sales.sum(axis=0))                # per month (down the columns)print(sales.sum(axis=1))                # per store (across the rows)print(sales.max(), sales.argmax(), np.median(sales))
Output
645 107.5
[200 200 245]
[360 285]
150 2 102.5
Tip

axis=0 means “collapse the rows” (one result per column) and axis=1 means “collapse the columns” (one result per row).

Broadcasting

When shapes differ, NumPy stretches the smaller array to fit, as long as the dimensions are compatible:

Python
import numpy as np marks = np.array([[70, 80, 90],                  [60, 75, 85]])bonus = np.array([5, 0, 10])            # one bonus per subjectprint(marks + bonus)print(marks / marks.max(axis=1, keepdims=True))   # normalise each row
Output
[[ 75  80 100]
 [ 65  75  95]]
[[0.77777778 0.88888889 1.        ]
 [0.70588235 0.88235294 1.        ]]

Random numbers

Python
import numpy as np rng = np.random.default_rng(seed=42)print(rng.integers(1, 7, size=5))         # dice rollsprint(rng.random(3).round(3))print(rng.choice(["red", "green", "blue"], size=4))
Output
[1 5 4 3 3]
[0.697 0.094 0.976]
['blue' 'blue' 'blue' 'blue']

A fixed seed makes the results repeatable, which is useful for tests.

Why NumPy is fast

Python
import numpy as np, time n = 1_000_000numbers = list(range(n))arr = np.arange(n) t = time.perf_counter(); total_list = sum(x * x for x in numbers); list_time = time.perf_counter() - tt = time.perf_counter(); total_np = int((arr * arr).sum()); np_time = time.perf_counter() - t print(total_list == total_np)print("NumPy faster:", np_time < list_time)
Output
True
NumPy faster: True

Check your understanding

Predict the output

import numpy as npa = np.array([[1, 2], [3, 4]])print(a * a, a.sum(axis=0), a[a > 2])

Quick quiz

1. What is np.array([1, 2, 3]) * 2?

2. What does arr.shape return for a 3 x 4 array?

3. Which combines two conditions in a mask?

Exercise: class report

Marks of 4 students in 3 subjects are in a 4 x 3 array. Print each student’s total, each subject’s average, and how many marks are below 40.

Input
[[78, 65, 90], [35, 48, 52], [88, 92, 79], [40, 39, 61]]
Expected output
Totals: [233 135 259 140]
Subject averages: [60.25 61.   70.5 ]
Marks below 40: 2
Hint 1

sum(axis=1) for students, mean(axis=0) for subjects.

Program Practice

NumPy FAQ

What is NumPy used for?

Fast numerical computing: arrays, linear algebra, statistics and random numbers. It is the base for pandas, SciPy, scikit-learn and most data and ML libraries.

What is the difference between a Python list and a NumPy array?

A NumPy array holds items of one type in contiguous memory and supports element-wise maths. A list can mix types and its operators mean concatenation and repetition.

What does axis=0 mean in NumPy?

It means “along the rows”, so the result has one value per column. axis=1 gives one value per row.

Python Pandas

Python Tutorial › Libraries & Databases › Pandas

Python Pandas

IntermediateLesson 46 of 4715 min read12 runnable examples

pandas turns tables of data into DataFrames that you can filter, sort, group and summarise in a few lines. It reads CSV, Excel, JSON and SQL, which makes it the everyday tool for data analysis and for preparing test data.

In this lesson
  • Create Series and DataFrames
  • Read CSV files and inspect the data
  • Select, filter and sort rows
  • Handle missing values, group and merge

Install and import

Terminal
python -m pip install pandas
Python
import pandas as pdprint(int(pd.__version__.split(".")[0]) >= 2)
Output
True
Note

The examples were run with pandas 3. The in-browser Try it uses an older pandas, so a few outputs (such as column types) may print slightly differently there.

Series and DataFrame

A Series is one labelled column. A DataFrame is a table of Series that share an index.

Python
import pandas as pd scores = pd.Series([91, 78, 85], index=["Asha", "Ravi", "Meena"])print(scores)print(scores["Ravi"], scores.mean().round(2))
Output
Asha     91
Ravi     78
Meena    85
dtype: int64
78 84.67
Python
import pandas as pd df = pd.DataFrame({    "name": ["Asha", "Ravi", "Meena", "John", "Sara"],    "dept": ["QA", "Dev", "QA", "Ops", "Dev"],    "salary": [52000, 61000, 48000, 55000, 67000],    "years": [4, 6, 2, 5, 8],})print(df)print(df.shape)
Output
    name dept  salary  years
0   Asha   QA   52000      4
1   Ravi  Dev   61000      6
2  Meena   QA   48000      2
3   John  Ops   55000      5
4   Sara  Dev   67000      8
(5, 4)

Read a CSV file

Python
import pandas as pd with open("orders.csv", "w") as f:    f.write("order_id,city,amount,status\n101,Pune,1200,paid\n102,Delhi,450,pending\n"            "103,Pune,980,paid\n104,Mumbai,,cancelled\n105,Delhi,2300,paid\n") orders = pd.read_csv("orders.csv")print(orders.head(3))print(orders.dtypes["amount"], len(orders))
Output
   order_id   city  amount   status
0       101   Pune  1200.0     paid
1       102  Delhi   450.0  pending
2       103   Pune   980.0     paid
float64 5

Quick ways to inspect a new dataset:

Python
import pandas as pd orders = pd.read_csv("orders.csv")print(orders.columns.tolist())print(orders["amount"].describe().round(1).to_dict())print(orders["city"].value_counts().to_dict())
Output
['order_id', 'city', 'amount', 'status']
{'count': 4.0, 'mean': 1232.5, 'std': 778.2, 'min': 450.0, '25%': 847.5, '50%': 1090.0, '75%': 1475.0, 'max': 2300.0}
{'Pune': 2, 'Delhi': 2, 'Mumbai': 1}

Select columns and rows

Python
import pandas as pd df = pd.DataFrame({"name": ["Asha", "Ravi", "Meena"], "dept": ["QA", "Dev", "QA"], "salary": [52000, 61000, 48000]}) print(df["name"].tolist())             # one columnprint(df[["name", "salary"]])          # several columnsprint(df.loc[1, "name"])               # by labelprint(df.iloc[0].to_dict())            # by position
Output
['Asha', 'Ravi', 'Meena']
    name  salary
0   Asha   52000
1   Ravi   61000
2  Meena   48000
Ravi
{'name': 'Asha', 'dept': 'QA', 'salary': 52000}

Filter rows

Python
import pandas as pd df = pd.DataFrame({    "name": ["Asha", "Ravi", "Meena", "John", "Sara"],    "dept": ["QA", "Dev", "QA", "Ops", "Dev"],    "salary": [52000, 61000, 48000, 55000, 67000],})print(df[df["salary"] > 55000])print(df[(df["dept"] == "QA") & (df["salary"] > 50000)]["name"].tolist())print(df[df["dept"].isin(["Dev", "Ops"])].shape[0])print(df.query("salary < 50000")["name"].tolist())
Output
   name dept  salary
1  Ravi  Dev   61000
4  Sara  Dev   67000
['Asha']
3
['Meena']

Sort and add columns

Python
import pandas as pd df = pd.DataFrame({"name": ["Asha", "Ravi", "Meena"], "salary": [52000, 61000, 48000], "years": [4, 6, 2]})df["bonus"] = df["salary"] * 0.1df["level"] = df["years"].apply(lambda y: "senior" if y >= 5 else "junior")print(df.sort_values("salary", ascending=False))
Output
    name  salary  years   bonus   level
1   Ravi   61000      6  6100.0  senior
0   Asha   52000      4  5200.0  junior
2  Meena   48000      2  4800.0  junior

Missing data

Python
import pandas as pd orders = pd.read_csv("orders.csv")print(orders["amount"].isna().sum())print(orders.dropna(subset=["amount"]).shape)filled = orders.fillna({"amount": 0})print(filled["amount"].tolist())
Output
1
(4, 4)
[1200.0, 450.0, 980.0, 0.0, 2300.0]

Group and aggregate

groupby splits the rows into groups, applies a calculation to each, and combines the results:

Python
import pandas as pd orders = pd.read_csv("orders.csv")paid = orders[orders["status"] == "paid"]print(paid.groupby("city")["amount"].sum())print(orders.groupby("status").size().to_dict())print(paid.groupby("city")["amount"].agg(["count", "mean"]))
Output
city
Delhi    2300.0
Pune     2180.0
Name: amount, dtype: float64
{'cancelled': 1, 'paid': 3, 'pending': 1}
       count    mean
city                
Delhi      1  2300.0
Pune       2  1090.0

Merge two tables

Python
import pandas as pd users = pd.DataFrame({"user_id": [1, 2, 3], "name": ["Asha", "Ravi", "Meena"]})orders = pd.DataFrame({"order_id": [10, 11, 12, 13], "user_id": [1, 1, 3, 4], "amount": [500, 250, 900, 100]}) joined = orders.merge(users, on="user_id", how="left")print(joined)print(joined.groupby("name")["amount"].sum().to_dict())
Output
   order_id  user_id  amount   name
0        10        1     500   Asha
1        11        1     250   Asha
2        12        3     900  Meena
3        13        4     100    NaN
{'Asha': 750, 'Meena': 900}

A left merge keeps every order; user 4 has no match, so name is missing (NaN) for that row.

Save results

Python
import pandas as pd orders = pd.read_csv("orders.csv")summary = orders.groupby("city", as_index=False)["amount"].sum()summary.to_csv("city_totals.csv", index=False)print(open("city_totals.csv").read().strip())
Output
city,amount
Delhi,2750.0
Mumbai,0.0
Pune,2180.0

Check your understanding

Predict the output

import pandas as pddf = pd.DataFrame({"x": [1, 2, 3, 4], "g": ["a", "b", "a", "b"]})print(df[df["x"] > 1]["x"].sum(), df.groupby("g")["x"].sum().to_dict())

Quick quiz

1. Which reads a CSV file into a DataFrame?

2. What is the difference between loc and iloc?

3. How do you count missing values in a column?

Exercise: department report

For each department, print the number of employees and the average salary, sorted by average salary, highest first.

Input
the employee DataFrame from the Series and DataFrame section
Expected output
      count     mean
dept                
Dev       2  64000.0
Ops       1  55000.0
QA        2  50000.0
Hint 1

groupby("dept")["salary"].agg(["count", "mean"]), then sort_values("mean", ascending=False).

Program Practice

95 Python Pandas Programs

Every program has a step-by-step explanation, colour-coded code and its real output.

Start practising →
Related sets:All practice sets

Pandas FAQ

What is pandas used for in Python?

Loading, cleaning, transforming and summarising tabular data from CSV, Excel, JSON and SQL sources.

What is the difference between a Series and a DataFrame?

A Series is a single labelled column. A DataFrame is a two-dimensional table made of several Series that share an index.

How do I filter rows in pandas?

Use a boolean condition inside brackets: df[df["salary"] > 50000]. Combine conditions with & and | and wrap each one in brackets.

How do I handle missing values in pandas?

Find them with isna(), remove them with dropna(), or replace them with fillna().

Python File Handling

Python Tutorial › File Handling › File Handling

Python File Handling

BeginnerLesson 41 of 4712 min read11 runnable examples

Programs save results, read test data and process logs, and all of that means working with files. Python’s built-in open() function plus a with block is all you need for text files.

In this lesson
  • Open files safely with with
  • Choose the right file mode
  • Read a whole file, a line, or all lines
  • Write, append and process files line by line

Write a file

open(path, mode) returns a file object. Mode "w" creates the file (or empties it if it exists). The with block closes the file automatically, even if an error happens.

Python
with open("notes.txt", "w", encoding="utf-8") as f:    f.write("Python file handling\n")    f.write("Line two\n")    f.writelines(["Line three\n", "Line four\n"]) print("written")
Output
written
Tip

Always pass encoding="utf-8" for text files. Without it, Python uses the operating system’s default encoding, which differs between Windows and Linux.

Read a whole file

Python
with open("notes.txt", encoding="utf-8") as f:    content = f.read() print(repr(content[:25]))print(len(content.splitlines()), "lines")
Output
'Python file handling\nLine'
4 lines

Read line by line

A file object is iterable: a for loop gives one line at a time, which works for files of any size.

Python
with open("notes.txt", encoding="utf-8") as f:    for number, line in enumerate(f, start=1):        print(number, line.rstrip("\n"))
Output
1 Python file handling
2 Line two
3 Line three
4 Line four

readline() reads the next line; readlines() returns a list of all lines (keeping the \n):

Python
with open("notes.txt", encoding="utf-8") as f:    first = f.readline()    rest = f.readlines() print(repr(first))print(rest)
Output
'Python file handling\n'
['Line two\n', 'Line three\n', 'Line four\n']

File modes

ModeMeaningIf the file existsIf it does not
"r"read (default)read from the startFileNotFoundError
"w"writeemptied firstcreated
"a"appendwrite at the endcreated
"x"exclusive createFileExistsErrorcreated
"r+"read and writefrom the startFileNotFoundError
add "b"binary, e.g. "rb"bytes instead of str

Append to a file

Python
with open("notes.txt", "a", encoding="utf-8") as f:    f.write("Appended line\n") with open("notes.txt", encoding="utf-8") as f:    print(f.read().splitlines()[-2:])
Output
['Line four', 'Appended line']

Handle a missing file

Python
with open("does_not_exist.txt", encoding="utf-8") as f:    print(f.read())
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    with open("does_not_exist.txt", encoding="utf-8") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'does_not_exist.txt'

Check first, or catch the error:

Python
from pathlib import Path path = Path("does_not_exist.txt")if path.exists():    print(path.read_text(encoding="utf-8"))else:    print(f"{path} not found, using defaults") try:    open("does_not_exist.txt", encoding="utf-8")except FileNotFoundError as e:    print("Caught:", e.strerror)
Output
does_not_exist.txt not found, using defaults
Caught: No such file or directory

Process a log file

A typical job: read a log, count errors and write a summary.

Python
log = """2026-11-02 09:00 INFO start2026-11-02 09:01 ERROR db timeout2026-11-02 09:02 INFO retry2026-11-02 09:03 ERROR db timeout2026-11-02 09:04 WARN slow response"""with open("app.log", "w", encoding="utf-8") as f:    f.write(log) counts = {}errors = []with open("app.log", encoding="utf-8") as f:    for line in f:        level = line.split()[2]        counts[level] = counts.get(level, 0) + 1        if level == "ERROR":            errors.append(line.split(maxsplit=3)[3].strip()) with open("summary.txt", "w", encoding="utf-8") as out:    for level, n in sorted(counts.items()):        out.write(f"{level}: {n}\n") print(open("summary.txt", encoding="utf-8").read().strip())print(set(errors))
Output
ERROR: 2
INFO: 2
WARN: 1
{'db timeout'}

Read and write several files

Python
with open("notes.txt", encoding="utf-8") as src, open("upper.txt", "w", encoding="utf-8") as dst:    for line in src:        dst.write(line.upper()) print(open("upper.txt", encoding="utf-8").readline().strip())
Output
PYTHON FILE HANDLING

Binary files

Images, PDFs and zip files are binary. Open them with "rb" / "wb" and you get bytes:

Python
data = bytes([137, 80, 78, 71])          # the first bytes of every PNG filewith open("sample.bin", "wb") as f:    f.write(data) with open("sample.bin", "rb") as f:    head = f.read()print(head, len(head))
Output
b'\x89PNG' 4

seek and tell

Python
with open("notes.txt", encoding="utf-8") as f:    print(f.read(6))    print(f.tell())        # current position    f.seek(0)              # back to the start    print(f.readline().strip())
Output
Python
6
Python file handling

Check your understanding

Predict the output

with open("t.txt", "w") as f:    f.write("a\nb\n")with open("t.txt", "w") as f:    f.write("c\n")print(open("t.txt").read().split())

Quick quiz

1. What does mode “w” do to an existing file?

2. Why use with open(...) as f:?

3. Which reads one line at a time without loading the whole file?

Exercise: word statistics

Write a short text to story.txt, then read it back and print the number of lines, words and characters, and the longest word.

Input
"Python reads files easily\nAnd writes them too\n"
Expected output
2 8 46 Python
Hint 1

Count lines while looping; len(line.split()) counts words.

Program Practice

Python file handling FAQ

How do I read a file line by line in Python?

with open(path, encoding="utf-8") as f: then for line in f:. Use line.rstrip("\n") to drop the newline.

What is the difference between write() and writelines()?

write() writes one string. writelines() writes every string from a list or other iterable; neither adds newlines for you.

How do I check if a file exists before opening it?

Use os.path.exists(path) or Path(path).exists(), or open it inside try and catch FileNotFoundError.

Do I need to close a file in Python?

Not when you use with, which closes it automatically. Otherwise call f.close() yourself.

Python Lambda Function

Python Lambda Function Tutorial

Python Lambda Functions ( Anonymous function )

Anonymous functions in Python, also known as lambda functions, allow you to create small, one-line functions without explicitly defining a function using the `def` keyword.

Syntax: `lambda arguments: expression`

The `lambda` keyword is used to define a lambda function. It is followed by the arguments (comma-separated) and a colon (:), then the expression that is evaluated and returned as the function’s result. Here is an example:

				
					# Creating a lambda function to add two numbers
add_numbers = lambda x, y: x + y

# Calling the lambda function
result = add_numbers(10, 15)
print(result)  # Output: 25

				
			

In this example, we define a lambda function `add_numbers` that takes two arguments, `x` and `y`. The function adds these two numbers together using the `+` operator and returns the result. We then call the lambda function by providing the arguments `10` and `15`, and store the returned value in the `result` variable.

Lambda functions are commonly used when you need a simple, one-line function and don’t want to define a separate named function. They are often used in combination with built-in functions like `map()`, `filter()`, and `reduce()` to perform operations on iterables in a concise and readable manner.

Features of Python Lambda Functions:

  1. Anonymity: Lambda functions do not have a name, making them useful for short, simple operations where defining a separate function using def is not necessary.
  2. Compactness: Lambda functions are typically concise and can be defined in a single line.
  3. Single Expression: Lambda functions are limited to a single expression, which means they cannot contain multiple statements or complex logic.
  4. Functional Programming: Lambda functions are commonly used in functional programming to pass behavior as arguments to higher-order functions like map, filter, and reduce.

Difference between Built-in functions and Lambda functions (also known as Anonymous functions)

In Python, the main difference between built-in functions and anonymous functions (also known as lambda functions) lies in their structure, creation, and usage.

Built-in Functions:

Built-in functions in Python are pre-defined functions that are provided by the Python language itself. They are readily available for use without any additional coding or import statements. These functions cover a wide range of tasks and operations, such as mathematical calculations, string manipulations, list operations, file I/O, etc. They are named and can be used repeatedly throughout the code. Here’s an example of using a built-in function to find the length of a list:

				
					# Using the built-in function len() to find the length of a list
numbers = [1, 2, 3, 4, 5]
length = len(numbers)
print(length)  # Output: 5

				
			

In this example, the len() function is a built-in function that returns the number of elements in the list numbers.

Lambda Functions (Anonymous Functions):

Lambda functions are a special type of function in Python that allows you to create small, one-line functions without explicitly defining them using the def keyword. Lambda functions are typically used for simple, one-time tasks and are often used in conjunction with higher-order functions like map(), filter(), and reduce().

Lambda functions have the following structure: lambda arguments: expression

The lambda function takes a set of arguments, performs the specified expression on those arguments, and returns the result of the expression. Here’s an example of a lambda function that calculates the square of a number:

				
					# Using a lambda function to calculate the square of a number
square = lambda x: x**2
result = square(5)
print(result)  # Output: 25

				
			

In this example, we create a lambda function that takes an argument x, calculates the square using the expression x**2, and then we call the lambda function with square(5) to calculate the square of 5.

Key Differences:

  1. Structure and Definition: Built-in functions are predefined and come with Python, whereas lambda functions are created on-the-fly and are not explicitly defined using the def keyword.
  2. Usage and Complexity: Built-in functions are used for a wide range of tasks and can be complex with multiple parameters, whereas lambda functions are typically used for simple operations with one or few parameters.
  3. Naming: Built-in functions have names, and you can call them using their names whenever needed. Lambda functions, on the other hand, do not have names and are often used as temporary, inline functions.
  4. Return Statement: Built-in functions return their results as any other function, using the return statement. Lambda functions automatically return the value of the expression without using the return statement.
  5. Use Cases: Built-in functions are ideal for general-purpose and reusable tasks, while lambda functions are more suited for immediate, short-term, and one-time uses.