Python The Essentials 1731972875
Python The Essentials 1731972875
Basic Syntax
Data Types
● Numbers: int (e.g., 42), float (e.g., 3.14), complex (e.g., 2+3j).
● Strings: Enclosed in single quotes '' or double quotes "", e.g.,
"Hello", 'Python'.
● Lists: Ordered, mutable sequences enclosed in [], e.g., [1, 2, 3], ["a",
"b", "c"].
● Tuples: Ordered, immutable sequences enclosed in (), e.g., (1, 2, 3),
("a", "b", "c").
● Sets: Unordered, unique elements enclosed in {}, e.g., {1, 2, 3}, {"a",
"b", "c"}.
● Dictionaries: Key-value pairs enclosed in {}, e.g., {"name": "John",
"age": 25}.
● Booleans: True and False.
Control Flow
● if, elif, else: Conditional statements, e.g., if x > 0: ... elif x < 0:
... else: ....
● for: Iteration over sequences, e.g., for item in list: ....
● while: Loops based on a condition, e.g., while condition: ....
● break, continue: Loop control statements, e.g., break to exit a loop,
continue to skip an iteration.
● pass: Placeholder statement, used when no action is required.
Collections
● Lists:
○ append(): Add an element to the end of the list, e.g.,
list.append(item).
○ insert(): Insert an element at a specific index, e.g.,
list.insert(index, item).
○ remove(): Remove the first occurrence of an element, e.g.,
list.remove(item).
○ pop(): Remove and return an element at a specific index, e.g., item
= list.pop(index).
○ sort(): Sort the list in-place, e.g., list.sort().
○ reverse(): Reverse the order of elements in the list, e.g.,
list.reverse().
● Tuples: Immutable, accessed using index, e.g., tuple[index].
● Sets:
○ add(): Add an element to the set, e.g., set.add(item).
○ remove(): Remove an element from the set, raises KeyError if not
found, e.g., set.remove(item).
○ discard(): Remove an element from the set if present, e.g.,
set.discard(item).
○ union(): Return a new set with elements from both sets, e.g.,
set1.union(set2).
○ intersection(): Return a new set with elements common to both sets,
e.g., set1.intersection(set2).
○ difference(): Return a new set with elements in the first set but
not in the second, e.g., set1.difference(set2).
● Dictionaries:
○ keys(): Return a view of dictionary keys, e.g., dict.keys().
○ values(): Return a view of dictionary values, e.g., dict.values().
File Handling
● Opening files: open(filename, mode), where mode can be 'r' (read), 'w'
(write), 'a' (append), 'x' (exclusive creation), 'b' (binary), 't'
(text), '+' (read/write).
● Reading files:
○ read(): Read the entire contents of a file as a string, e.g.,
content = file.read().
○ readline(): Read a single line from the file, e.g., line =
file.readline().
○ readlines(): Read all lines from the file and return them as a list,
e.g., lines = file.readlines().
● Writing to files:
○ write(): Write a string to the file, e.g., file.write("Hello,
World!").
○ writelines(): Write a list of strings to the file, e.g.,
file.writelines(lines).
● Closing files: file.close() to close the file after reading/writing.
● Context managers: Use with statement to automatically close the file,
e.g., with open(filename, mode) as file: ....
Exception Handling
Modules
String Manipulation
List Comprehensions
Decorators
Regular Expressions
● Syntax errors: Occur when code violates Python's grammar rules, e.g.,
missing colons, incorrect indentation.
● Exceptions: Raised during the execution of a program when an error
occurs, e.g., ZeroDivisionError, FileNotFoundError.
● Debugging techniques:
○ Use print() statements to display variable values and track program
flow.
○ Use a debugger to set breakpoints, step through code, and inspect
variables.
○ Use logging to record information during program execution, e.g.,
import logging; logging.debug(message).
Virtual Environments
Context Managers
Networking
@app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run()
Miscellaneous
Functional Programming
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")