Introduction To Python

Python delivers powerful functionality in a clean, accessible way, whether you're comparing it to Ruby, Perl, Scheme, or Java, it holds its own as a go-to language for developers who value elegance and efficiency

Some of Python's Notable Features

Python Programming Features

here are some of the programming-language features of Python

Features

Installing/Getting Python

Before you dive in, make sure Python 3 is installed on your machine. This interpreter is what runs your Python code, it reads your instructions and executes them step-by-step. You'll need it installed before writing a single line.It can be found at Python's website.

If you're on macOS or Linux, your system might already have Python 2 floating around. That's legacy, grab the latest Python 3 build to ensure compatibility with modern tools and libraries.

Command Line Setup

To run Python directly from the Windows command line (cmd.exe), you'll need to add its install location to your system's PATH. Here's how to do it on current Windows builds:

Getting Started - Hello World

Getting Started with Python in the Terminal

Open your terminal and type python3, then press Enter. You should see the >>> prompt, indicating you're inside the Python interpreter.

Writing Your First Program

At the prompt, type print("Hello World") and press Enter. This command will output Hello World directly in your terminal.

Exiting the Python Interpreter

To quit:

Running Python from a Source File

Create a new file named hello.py and write print("Hello World") inside it. Save the file, then run it via terminal:

cd path/to/your/file
python hello.py

Choosing an Editor

Use a code editor with syntax highlighting and indentation support. Recommended beginner-friendly options include PyCharm Educational Edition. Avoid using Notepad on Windows, as it lacks Python-friendly features.

Summary

You now know how to:

This sets the foundation for your Python journey.

Python Basics

Comments

Use # to add notes in your code that Python will ignore. Useful for explaining logic or intentions.

Literal Constants

Fixed values like 5, 1.23, or "Hello" that appear directly in the code.

Numbers

Python supports integers (10), floating-point numbers (3.14), and scientific notation (52.3E-4).

Strings

Text wrapped in quotes: single, double, or triple quotes for multi-line strings. Example: "Hello World". Strings are immutable.

Escape Sequences

Special characters within strings using backslash: \n (newline), \t (tab), \\ (backslash).

Raw Strings

Prefix with r to prevent escape sequences from being processed. Example: r"C:\Path\to\file".

Variables

Use = to assign values. Python auto-detects types. Example: name = "Liam".

Identifiers

Variable names must begin with a letter or underscore. They can include letters, digits, and underscores, and are case-sensitive.

Data Types

Common types: int, float, str. Python treats everything as an object.

String Formatting

Use .format() or f-strings for dynamic output. Example: f"{name} is {age}".

Logical vs Physical Lines

Use line breaks normally. A backslash (\) can continue a line, and semicolons (;) can separate statements (not recommended).

Indentation

Python uses indentation (typically 4 spaces) to define code blocks. Consistency is crucial to avoid syntax errors.

Operators And Expressions

What Are Expressions?

An expression combines values (operands) with symbols or keywords (operators) to produce a result. Example: 2 + 3.

Common Operators

Arithmetic:
+ Addition
- Subtraction
* Multiplication
/ Division
// Floor Division
% Modulo (remainder)
** Exponentiation

Bitwise:
<< Left Shift
>> Right Shift
& AND
| OR
^ XOR
~ Invert

Comparison:
<, >, <=, >=, ==, !=
Returns True or False

Boolean:
not, and, or
Uses short-circuit evaluation

Shortcut Assignment

Instead of a = a * 3, use a *= 3. Works with other operators too.

Operator Precedence

Some operators are evaluated before others. Example: 2 + 3 * 4 evaluates as 2 + (3 * 4).

Use parentheses to control order: (2 + 3) * 4.

Associativity

Most operators are evaluated left to right. Example: 2 + 3 + 4 is (2 + 3) + 4.

Example Program

length = 5
breadth = 2
area = length * breadth
print("Area is", area)
print("Perimeter is", 2 * (length + breadth))

Summary

Operators and expressions are the building blocks of Python programs. Use them to perform calculations, comparisons, and logic.

Control Flow

What Is Control Flow?

Control flow lets your program make decisions and repeat actions. Python uses if, for, and while statements to control execution.

If Statement

Used to run code based on conditions. You can use if, elif, and else blocks.

if guess == number:
    print("Correct!")
elif guess < number:
    print("Too low")
else:
    print("Too high")

While Loop

Repeats a block of code while a condition is True. Optional else block runs when the loop ends naturally.

while running:
    guess = int(input("Enter a number: "))
    if guess == number:
        print("Correct!")
        running = False
    else:
        print("Try again")
else:
    print("Loop ended")

For Loop

Iterates over a sequence like a list or range. Optional else block runs after the loop finishes.

for i in range(1, 5):
    print(i)
else:
    print("Loop complete")

Break Statement

Stops a loop immediately. Skips the else block if used.

while True:
    s = input("Enter something: ")
    if s == "quit":
        break
    print("Length:", len(s))

Continue Statement

Skips the rest of the current loop iteration and continues with the next one.

while True:
    s = input("Enter something: ")
    if s == "quit":
        break
    if len(s) < 3:
        print("Too short")
        continue
    print("Valid input")

Summary

Python’s control flow tools—if, while, for, break, and continue—help you write flexible, responsive programs. Mastering these is key to building logic-driven applications.

Functions

What Are Functions?

Functions are reusable blocks of code that can be called by name. They help organize and simplify programs.

Defining a Function

Use the def keyword followed by the function name, parentheses, and a colon. The body is indented.

def say_hello():
    print("hello world")

Calling a Function

Invoke a function by writing its name followed by parentheses: say_hello().

Function Parameters

Functions can accept input values (parameters). Arguments are passed when calling the function.

def print_max(a, b):
    if a > b:
        print(a, "is maximum")

Local Variables

Variables defined inside a function are local and don’t affect variables outside the function.

Global Variables

Use the global keyword to modify a variable defined outside the function.

Default Argument Values

Provide default values for parameters using =. These are used if no argument is passed.

def say(message, times=1):
    print(message * times)

Keyword Arguments

Specify arguments by name to avoid relying on position. Useful when functions have many parameters.

func(a=10, c=20)

Variable-Length Arguments

Use *args for any number of positional arguments and **kwargs for keyword arguments.

Return Statement

Use return to send a value back from a function. If omitted, Python returns None by default.

DocStrings

Use triple quotes at the start of a function to describe its purpose. Access with function.__doc__.

Summary

Functions help structure code, reduce repetition, and improve readability. Learn to use parameters, return values, and docstrings effectively.

Modules

What Are Modules?

Modules are reusable Python files containing functions, variables, or classes. They help organize code across multiple programs.

Using Standard Library Modules

Import built-in modules using import. Example:

import sys
print(sys.argv)

Command Line Arguments

sys.argv stores command line arguments as a list. The first item is always the script name.

Module Search Path

Python searches for modules in directories listed in sys.path. The current directory is included by default.

Byte-Compiled Files

Python creates .pyc files to speed up module loading. These are platform-independent and stored alongside .py files.

from..import Statement

Use from module import name to access specific items directly. Example:

from math import sqrt
print(sqrt(16))

Note: Prefer import module to avoid name clashes.

Module's __name__ Attribute

Use __name__ to check if a module is run directly or imported:

if __name__ == '__main__':
    print("Running standalone")

Creating Your Own Modules

Any .py file is a module. Example:

# mymodule.py
def say_hi():
    print("Hi from mymodule")

__version__ = '0.1'

Using Your Module

import mymodule
mymodule.say_hi()
print(mymodule.__version__)

The dir() Function

Returns a list of names defined in a module or current scope. Example:

import sys
print(dir(sys))

Packages

Packages are folders containing modules and an __init__.py file. They allow hierarchical organization of modules.

Summary

Modules and packages help structure Python programs for reuse and clarity. The standard library is a rich source of built-in modules.

Data Structures

Overview

Python provides built-in data structures to store and organize data: list, tuple, dictionary, and set.

List

Ordered, mutable collections. Defined with square brackets [].

shoplist = ['apple', 'mango', 'carrot']
shoplist.append('banana')
shoplist.sort()
del shoplist[0]

Tuple

Ordered, immutable collections. Defined with commas, optionally inside parentheses.

zoo = ('python', 'elephant', 'penguin')
new_zoo = ('monkey', 'camel', zoo)

Dictionary

Key-value pairs. Keys must be immutable; values can be any type.

ab = {
  'Swaroop': 'swaroop@swaroopch.com',
  'Larry': 'larry@wall.org'
}
del ab['Larry']
ab['Guido'] = 'guido@python.org'

Sequence Operations

Lists, tuples, and strings support indexing, slicing, and membership tests.

shoplist[1:3]
name = 'swaroop'
name[1:-1]

Set

Unordered collections of unique items. Useful for membership and set operations.

bri = set(['brazil', 'russia', 'india'])
bric = bri.copy()
bric.add('china')
bri & bric

References

Variables refer to objects, not copies. Use slicing to copy lists.

mylist = shoplist[:]  # creates a copy

String Methods

Strings are objects with useful methods like startswith, find, and join.

name = 'Swaroop'
name.startswith('Swa')
'_'.join(['Brazil', 'Russia'])

Summary

These data structures are essential for organizing and manipulating data in Python. Lists and dictionaries are especially versatile for real-world programming.

Problem Solving

Overview

This chapter demonstrates how to design and build a real Python script step by step. The example is a backup tool that compresses selected files into a zip archive.

Problem Definition

Goal: Create a backup of important files. Key questions include: which files to back up, where to store them, and how to compress them.

Design Plan

Implementation (Version 1)

Uses os and time modules to build a zip command and execute it. Creates the backup directory if needed.

Testing and Debugging

Run the script and verify output. If it fails, test the zip command manually and check for typos or path issues.

Enhancement (Version 2)

Improves file organization by creating a subdirectory named after the current date and storing zip files named by time.

Adding Comments (Version 3 & 4)

Allows user to add a comment to the filename. Version 3 fails due to a syntax error (missing line continuation). Version 4 fixes it using a backslash.

Further Refinements

Software Development Process

Follows these phases: Analysis → Design → Implementation → Testing → Deployment → Maintenance.

Summary

This chapter walks through building a useful Python script from scratch, emphasizing design, iteration, and debugging. Try creating your own script to practice problem-solving.

Object Orientated Programming

Overview

Introduces the object-oriented paradigm, where data and functionality are bundled into objects. Useful for organizing large programs.

Key Concepts

The self Parameter

Refers to the current object. Required in all method definitions. Python automatically passes it when calling methods.

Creating a Class

class Person:
    pass

Use class keyword. pass indicates an empty block.

Adding Methods

class Person:
    def say_hi(self):
        print("Hello!")

Methods must include self as the first parameter.

Constructor: __init__

Automatically called when an object is created. Used to initialize fields.

class Person:
    def __init__(self, name):
        self.name = name

Class vs Object Variables

Example: Robot Class

Demonstrates class variable population and object variable name. Includes methods like say_hi, die, and how_many.

Inheritance

Allows reuse of code by creating subclasses. Example: Teacher and Student inherit from SchoolMember.

Summary

OOP helps organize code, encourages reuse, and supports scalability. Python’s OOP model is flexible and intuitive for beginners.

Input And Output

Overview

Explores how Python programs interact with users and files. Covers input/output functions, file handling, object persistence, and Unicode support.

User Input

File Handling

Example: Writing and Reading a Poem

poem = '''Programming is fun...'''
f = open('poem.txt', 'w')
f.write(poem)
f.close()

f = open('poem.txt')
for line in f:
    print(line, end='')
f.close()

Pickle Module

Unicode and Encoding

Summary

This chapter introduces essential I/O techniques in Python, including user interaction, file operations, object serialization, and Unicode handling.

Exceptions

Overview

Exceptions are used to handle unexpected situations in a program, such as missing files or invalid input. Python provides built-in mechanisms to catch and respond to these errors gracefully.

Errors vs Exceptions

Handling Exceptions

try:
    text = input('Enter something --> ')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else:
    print('You entered {}'.format(text))

Use try to wrap risky code, except to catch specific exceptions, and else to run code if no exception occurs.

Raising Exceptions

class ShortInputException(Exception):
    def __init__(self, length, atleast):
        self.length = length
        self.atleast = atleast

try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
except ShortInputException as ex:
    print(f'ShortInputException: The input was {ex.length} long, expected at least {ex.atleast}')

You can define custom exceptions by subclassing Exception and raise them using raise.

Using finally

Ensures cleanup actions (like closing files) are performed regardless of whether an exception occurred.

try:
    f = open("poem.txt")
    # read file
except IOError:
    print("Could not find file poem.txt")
finally:
    if f:
        f.close()

The with Statement

Simplifies resource management by automatically handling setup and teardown.

with open("poem.txt") as f:
    for line in f:
        print(line, end='')

Summary

This chapter covers how to detect, handle, and raise exceptions in Python. It also introduces best practices for resource management using try..finally and with.

Standard Library

Overview

The Python Standard Library is a collection of built-in modules that provide powerful tools for common programming tasks. Learning these modules can help solve problems efficiently.

sys Module

logging Module

os and platform Modules

Exploration Tips

Summary

This chapter introduces key modules like sys, logging, os, and platform. Mastering the standard library unlocks efficient solutions to many programming challenges.