



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




(^01) Getting Started with Python
KEY ADVANTAGES
# Executing script via CLI: python main.py print("Hello, Python World!") print("Python Version:", 3.12)
_# Output:
(^02) Python Syntax & Comments
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
"""
x = 10 if x > 5 : # Indented block (4 spaces) msg = "Block start" " across lines" print(msg)
_# Output:
PEP 8 STANDARD
(^03) Variables & Data Types
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:
(^04) Input, Output & Formatting
# 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:
INPUT TYPE WARNING
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
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:
(^08) Strings & Text Manipulation
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:
09 Lists, Tuples, Sets & Dicts
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:
(^12) File I/O & Modules
# 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:
MODULE SEARCH PATH