Python Essentials: Data, Control, Files, and Libraries

Data Types and Operations

Python provides a variety of built‑in data types. Numeric types include int, float, complex, and the now‑unused long (Python 2). Integers can be written in decimal, binary, octal, or hexadecimal. Floating‑point numbers represent real numbers, while complex numbers use a j suffix for the imaginary part.

Strings are sequences of Unicode characters enclosed in single or double quotes. They support slicing with the [start:stop] syntax, which extracts a substring (left‑inclusive, right‑exclusive). Concatenation uses + and repetition uses *. Special characters are escaped with backslashes, e.g., \n for newline. The string module offers additional helper functions.

One useful string method is join():

separator = " | "
items = ("apple", "banana", "cherry")
result = separator.join(items)
print(result)   # apple | banana | cherry

Lists are mutable, ordered collections written inside square brackets. They can contain mixed data types and are manipulated with methods such as append(), extend(), and del.

languages = ['Python', 'Java', 'C++']
more_langs = ['Rust', 'Go']
languages.extend(more_langs)
print(languages)   # ['Python', 'Java', 'C++', 'Rust', 'Go']
del languages[1]
print(languages)   # ['Python', 'C++', 'Rust', 'Go']

Common list functions include len(), max(), min(), list.count(), and list.index(). The list(seq) call converts a tuple or other iterable to a list.

Tuples are similar to lists but immutable; they are defined with parentheses. They are often used for data that should not change.

Dictionaries store key‑value pairs inside curly braces. Keys must be immutable (strings, numbers, or tuples), while values can be any Python object.

user = {"name": "Alice", "age": 30, "city": "London"}
print(user["name"])          # Alice
del user["age"]
print(user.keys())           # dict_keys(['name', 'city'])

Dictionary methods include keys(), values(), items(), and update(). Use len() to get the number of entries.

Control Flow

Conditional execution uses if, elif, and else:

score = 85
if score >= 90:
    grade = 'A'
elif score >= 75:
    grade = 'B'
else:
    grade = 'C'

Loops are provided by for (iteration over sequences) and while (condition‑based).

for fruit in ['apple', 'banana', 'cherry']:
    print(fruit.upper())

while loops continue until a condition becomes false, and an optional else block runs when the loop exits normally (without break).

count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("Done")

The break statement terminates the innermost loop; continue skips the rest of the current iteration. pass is a no‑operation placeholder used where syntax requires a statement but no action is needed.

Exceptions are handled with try and except. Code that may raise an exception is placed in the try block; matching except clauses catch and handle the error.

try:
    value = int(input("Enter a number: "))
    print(10 / value)
except ValueError:
    print("Not a valid integer.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Functions and Modules

Functions are defined with the def keyword, followed by a name, a parameter list, and a colon. They can return values with return; a function without an explicit return returns None.

def greet(name, greeting="Hello"):
    """Return a customised greeting."""
    return f"{greeting}, {name}!"

print(greet("Bob"))              # Hello, Bob!
print(greet("Eve", "Hi"))        # Hi, Eve!

Python passes arguments by object reference. Immutable objects (numbers, strings, tuples) cannot be modified inside a function; mutable objects (lists, dictionaries) can be changed.

A module is a file containing Python definitions and statements. Use import to bring a module into your script, or from ... import ... to import specific names.

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

from datetime import datetime
print(datetime.now())

The dir() function lists all names defined in a module.

File I/O

Files are opened with open() which returns a file object. The recommended pattern is the with statement, which automatically closes the file even if an exception occurs.

# Writing
with open('output.txt', 'w') as f:
    f.write('Hello, world!\n')
    f.write('Welcome to Python.\n')

# Reading all lines
with open('output.txt', 'r') as f:
    for line in f:
        print(line.strip())

Alternatively, read() returns the entire content as a string, and readlines() returns a list of lines. Always ensure files are closed. The older try … finally pattern is superseded by with.

Standard Library Highlights

os and os.path

The os module provides operating system interfaces:

import os
os.rename('old_report.txt', 'new_report.txt')   # rename
os.remove('obsolete.txt')                         # delete file
os.mkdir('archive')                               # create directory
os.chdir('archive')                                # change directory
print(os.getcwd())                                 # show current directory
os.rmdir('archive')                                # remove directory

os.path works with file paths:

import os.path
path = '/home/user/docs/report.pdf'
print(os.path.basename(path))      # report.pdf
print(os.path.exists(path))        # True or False

To split a file path into its components:

folder, filename = os.path.split(path)
name, extension = os.path.splitext(filename)

argparse

The argparse module builds command‑line interfaces. An ArgumentParser object describes the program’s arguments.

import argparse

parser = argparse.ArgumentParser(description='Multiply two numbers')
parser.add_argument('x', type=float, help='first number')
parser.add_argument('y', type=float, help='second number')
parser.add_argument('-v', '--verbose', action='store_true', help='show full equation')
args = parser.parse_args()

product = args.x * args.y
if args.verbose:
    print(f'{args.x} * {args.y} = {product}')
else:
    print(product)

Positional arguments are required by default; optional arguments (like --verbose) can be flagged with action='store_true' to act as boolean switches.

Useful Built‑ins and System Functions

sys.argv is a list of command‑line arguments passed to the script (the first element is the script name). exit() terminates a program immediately. type() returns the type of an object.

int() can convert strings or numbers in a given base:

print(int('1F', 16))   # 31

To convert a JSON‑like string into a dictionary, use the json module:

import json
data = '{"name": "Alice", "age": 28}'
result = json.loads(data)
print(result['age'])   # 28

The eval() function can also achieve this but should be avoided with untrusted input for security reasons.

A list can be turned into a dictionary with dict() and a sequence of key‑value pairs, for example dict([('a',1), ('b',2)]).

Numeric Libraries: NumPy and Pandas

NumPy introduces the array object. np.arange(start, stop, step) creates an evenly spaced sequence:

import numpy as np
arr = np.arange(0, 10, 2)
print(arr)   # [0 2 4 6 8]

np.empty(shape, dtype) allocates an uninitialised array:

x = np.empty((3, 2), dtype=int)
print(x)     # values are arbitrary

Pandas provides DataFrame and Seriees objects. A new column can be added by direct assignment:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})
df['C'] = 0

To combine two Series:

s1 = pd.Series([10, 20, 30])
s2 = pd.Series([40, 50])
combined = pd.concat([s1, s2], ignore_index=True)

By default, pandas may truncate large outputs. To display all rows and columns:

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)

Regular expressions are supported through the re module, allowing pattern matching, searching, and substitution on strings.

Tags: python Tutorial data-structures control-flow file-io

Posted on Sun, 11 Oct 2026 16:21:50 +0000 by jworisek