Docsity

Python Programming in a Nutshell, Summaries of Programming Languages

Toggle sidebar
bg1
Python Programming
Beginner's Step-by-Step Study Guide & Reference Notes
CORE EDITION
MODULES 01
–
12
01
Getting Started with Python
Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum and
released in 1991. It is celebrated for its clean, readable syntax and philosophy (PEP 20 - "The Zen of Python").
Execution Architecture:
Python code goes through two main stages:
1.
Compilation:
Source code (
.py
) is compiled into low-level byte code (
.pyc
).
2.
Interpretation:
The Python Virtual Machine (PVM) reads and executes the byte code line by line.
KEY ADVANTAGES
Dynamic typing, automatic memory management (garbage collection), cross-platform portability, and an extensive
standard library ("batteries included").
First Script & Execution:
# Executing script via CLI: python main.py
print
(
"Hello, Python World!"
)
print
(
"Python Version:"
,
3.12
)
# Output:
# Hello, Python World!
# Python Version: 3.12
02
Python Syntax & Comments
Python uses
indentation
(typically 4 spaces) rather than curly braces
{}
or keywords like
begin/end
to de
fi
ne
block scope (functions, loops, classes, conditionals).
Statements:
Instructions that the Python interpreter can execute. Multiple statements can be on one line using
;
(though
discouraged).
Line Continuation:
Implicit inside parentheses
()
, brackets
[]
, braces
{}
, or explicit using backslash
\
.
# 1. Single-line comment
"""
2. Multi-line docstring:
Used for module, class, or function documentation.
"""
x =
10
if
x >
5
:
# Indented block (4 spaces)
msg =
"Block start"
\
" across lines"
print
(msg)
# Output:
# Block start across lines
PEP 8 STANDARD
Never mix spaces and tabs! Mixing them leads to an
IndentationError: unexpected indent
at runtime.
pf3
pf4
pf5

Partial preview of the text

Download Python Programming in a Nutshell and more Summaries Programming Languages in PDF only on Docsity!

Python Programming

Beginner's Step-by-Step Study Guide & Reference Notes

CORE EDITION

MODULES 01 – 12

(^01) Getting Started with Python

Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum and

released in 1991. It is celebrated for its clean, readable syntax and philosophy (PEP 20 - "The Zen of Python").

Execution Architecture: Python code goes through two main stages:

  1. Compilation: Source code (.py) is compiled into low-level byte code (.pyc).
  2. Interpretation: The Python Virtual Machine (PVM) reads and executes the byte code line by line.

KEY ADVANTAGES

Dynamic typing, automatic memory management (garbage collection), cross-platform portability, and an extensive

standard library ("batteries included").

First Script & Execution:

# Executing script via CLI: python main.py print("Hello, Python World!") print("Python Version:", 3.12)

_# Output:

Hello, Python World!

Python Version: 3._

(^02) Python Syntax & Comments

Python uses indentation (typically 4 spaces) rather than curly braces {} or keywords like begin/end to define

block scope (functions, loops, classes, conditionals).

Statements: Instructions that the Python interpreter can execute. Multiple statements can be on one line using ; (though discouraged). Line Continuation: Implicit inside parentheses (), brackets [], braces {}, or explicit using backslash .

# 1. Single-line comment

"""

  1. Multi-line docstring: Used for module, class, or function documentation. """

x = 10 if x > 5 : # Indented block (4 spaces) msg = "Block start" " across lines" print(msg)

_# Output:

Block start across lines_

PEP 8 STANDARD

Never mix spaces and tabs! Mixing them leads to an IndentationError: unexpected indent at runtime.

(^03) Variables & Data Types

In Python, variables are memory references pointing to objects. Objects are strongly typed, but variables are

dynamically bound.

Category Type Example & Notes

Numeric int, float, complex 10 , 3.14, 2 + 3j

Text str "hello" (Immutable Unicode)

Boolean bool True or False (Subclass of int)

None NoneType None (Represents absence of value)

# Variable assignment & Type Casting age = 25 # int price = float("19.99") # Explicit cast to float is_active = True # bool empty_val = None # NoneType

print(type(age), type(price), type(is_active)) print(f"ID of age: {id(age)}") # Unique memory location ID

_# Output:

ID of age: 140728987113168_

(^04) Input, Output & Formatting

Input is read from standard input as a string using input(). Output is generated via print() with flexible

separator and end parameters.

# Customizing print() print("Python", "is", "awesome", sep=" - ", end="!\n")

# F-String Formatting Options val = 123. pct = 0. print(f"2 Decimal places: {val:.2f}") print(f"Percentage format: {pct:.1%}") print(f"Padded number: {42:05d}")

_# Output:

Python - is - awesome!

2 Decimal places: 123.

Percentage format: 75.0%

Padded number: 00042_

INPUT TYPE WARNING

input() returns a string. Performing arithmetic without explicit numeric casting (e.g., int(input())) causes a

TypeError.

score = 88

score >= : grade = score >= : grade = : grade =

status = score >=

match grade: case | : msg = case _: msg =

(f)

if 90 "A" elif 80 "B" else "C" # Ternary Operator (Conditional Assignment) "Passed" if 70 else "Failed" # Structural Pattern Matching (Python 3.10+) "A""B""Great Job!""Keep practicing."print"Grade: {grade}, Status: {status}, Msg: {msg}" # Output:# Grade: B, Status: Passed, Msg: Great Job!

(^07) Loops & Iteration

Loops iterate over sequences or repeat tasks while a condition holds true.

break: Immediately terminates the loop. continue: Skips the remainder of the current iteration and moves to the next. else clause: Executes only if the loop completes normally (without encountering a break statement).

# For loop with range(start, stop, step) for i in range( 1 , 6 , 2 ): # 1, 3, 5 print(f"Step {i}", end=" ") print()

# While Loop with else block n = 3 while n > 0 : n -= 1 else : print("Loop completed without break!")

_# Output:

Step 1 Step 3 Step 5

Loop completed without break!_

(^08) Strings & Text Manipulation

Strings (str) are ordered, immutable sequences of Unicode characters. Slicing syntax follows

string[start:stop:step].

s = " Python Programming "

# Slicing & String Reversal clean = s.strip() print(clean[ 0 : 6 ]) # 'Python' print(clean[::- 1 ]) # 'gnimmargorP nohtyP' (Reversed)

# Essential String Methods print(clean.replace("Python", "Core")) words = clean.split(" ") # Returns list: ['Python', 'Programming'] joined = ", ".join(words) # 'Python, Programming'

print(f"Joined: {joined}")

_# Output:

Python

gnimmargorP nohtyP

Core Programming

Joined: Python, Programming_

09 Lists, Tuples, Sets & Dicts

Python provides four native core sequence and collection types designed for varying structural and computational

needs.

Data Structure Order Mutable Duplicates

List [] Ordered Yes Allowed

Tuple () Ordered No Allowed Set {} Unordered Yes Unique Only

Dict {k:v} Insertion-Ordered Keys Mutable Keys Unique

# List Comprehension squares = [x** 2 for x in range( 5 ) if x % 2 == 0 ]

# Set Operations (Fast O(1) Lookups) set_a = { 1 , 2 , 3 } set_b = { 3 , 4 , 5 } union_set = set_a | set_b # {1, 2, 3, 4, 5} inter_set = set_a & set_b # {3}

# Dictionary Operations person = {"name": "Alice", "age": 30 } person["city"] = "NY" # Add key-value pair age = person.get("age", 0 ) # Safe lookup with default

print(f"Squares: {squares}, Inter: {inter_set}")

_# Output:

Squares: [0, 4], Inter: {3}_

(^12) File I/O & Modules

File I/O operations should use context managers (with statements) to ensure resources are automatically closed.

Modules organize code across multiple files.

# Writing and Reading Files with open("data.txt", "w", encoding="utf-8") as f: f.write("Line 1: Python File I/O\nLine 2: Context Manager")

with open("data.txt", "r", encoding="utf-8") as f: lines = f.readlines()

# Standard Modules Example import math from datetime import datetime

now = datetime.now().strftime("%Y-%m-%d") print(f"Read {len(lines)} lines | Date: {now} | Pi: {math.pi:.2f}")

_# Output:

Read 2 lines | Date: 2026-11-11 | Pi: 3._

MODULE SEARCH PATH

When executing import module, Python searches in order: Current Directory → Standard Library Modules → Third-

Party packages in site-packages (via sys.path).