Learn Python Programming from scratch
Table of Contents
1. [Introduction to Python](#introduction-to-python) 2. [Installation and Setup](#installation-and-setup) 3. [Python Basics](#python-basics) 4. [Data Types](#data-types) 5. [Variables and Operators](#variables-and-operators) 6. [Control Flow](#control-flow) 7. [Functions](#functions) 8. [Data Structures](#data-structures) 9. [File Handling](#file-handling) 10. [Error Handling](#error-handling) 11. [Object-Oriented Programming](#object-oriented-programming) 12. [Modules and Packages](#modules-and-packages)
Introduction to Python
Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability and simplicity, making it an excellent choice for beginners and professionals alike.
Key Features of Python
| Feature | Description | |---------|-------------| | Easy to Learn | Simple syntax similar to English | | Interpreted | No compilation step needed | | Cross-platform | Runs on Windows, macOS, Linux | | Open Source | Free to use and modify | | Large Standard Library | Extensive built-in functionality | | Dynamic Typing | Variables don't need explicit type declaration |
Python Applications
- Web Development - Data Science and Analytics - Artificial Intelligence and Machine Learning - Automation and Scripting - Game Development - Desktop Applications
Installation and Setup
Installing Python
#### Windows
1. Visit python.org
2. Download the latest Python installer
3. Run the installer and check "Add Python to PATH"
4. Verify installation by opening Command Prompt and typing python --version
#### macOS
`bash
Using Homebrew
brew install python3Verify installation
python3 --version`#### Linux (Ubuntu/Debian)
`bash
Update package list
sudo apt updateInstall Python
sudo apt install python3 python3-pipVerify installation
python3 --version`Setting Up Development Environment
#### Command Line Interface
`bash
Start Python interpreter
python3Exit Python interpreter
exit()`#### Popular IDEs and Editors - IDLE - Built-in Python IDE - PyCharm - Professional Python IDE - Visual Studio Code - Lightweight editor with Python extensions - Jupyter Notebook - Interactive development environment
Python Basics
Your First Python Program
`python
hello_world.py
print("Hello, World!")`Command to run:
`bash
python3 hello_world.py
`
Python Syntax Rules
| Rule | Description | Example |
|------|-------------|---------|
| Indentation | Uses spaces/tabs for code blocks | if True:
print("Hello") |
| Case Sensitive | Variables are case sensitive | name and Name are different |
| Comments | Use # for single line comments | # This is a comment |
| Multi-line Comments | Use triple quotes | """This is a multi-line comment""" |
Interactive Python Shell
`python
Start interactive shell
>>> print("Hello, Python!") Hello, Python!>>> 2 + 3 5
>>> name = "Alice"
>>> print(f"Hello, {name}!")
Hello, Alice!
`
Data Types
Python has several built-in data types that are fundamental to programming.
Numeric Types
| Type | Description | Example | Range |
|------|-------------|---------|-------|
| int | Integer numbers | 42, -17, 0 | Unlimited precision |
| float | Floating-point numbers | 3.14, -2.5, 1.0 | ~15-17 decimal digits |
| complex | Complex numbers | 3+4j, 1-2j | Real and imaginary parts |
`python
Integer examples
age = 25 population = 1000000 negative_number = -42Float examples
price = 19.99 temperature = -5.5 scientific_notation = 1.5e6 # 1,500,000Complex numbers
z1 = 3 + 4j z2 = complex(2, -1) # 2 - 1jType checking
print(type(age)) #`String Type
Strings are sequences of characters enclosed in quotes.
`python
String creation
single_quote = 'Hello' double_quote = "World" triple_quote = """This is a multi-line string"""String operations
first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name # ConcatenationString formatting
age = 30 message = f"My name is {full_name} and I am {age} years old" print(message)String methods
text = "Python Programming" print(text.upper()) # PYTHON PROGRAMMING print(text.lower()) # python programming print(text.split()) # ['Python', 'Programming'] print(len(text)) # 18`Boolean Type
`python
Boolean values
is_student = True is_graduated = FalseBoolean operations
print(True and False) # False print(True or False) # True print(not True) # FalseComparison operations return boolean
print(5 > 3) # True print(10 == 10) # True print("hello" != "world") # True`None Type
`python
None represents absence of value
result = None print(result) # None print(type(result)) #Common usage
def get_user_input(): user_input = input("Enter something: ") if user_input: return user_input else: return None`Variables and Operators
Variable Declaration and Assignment
`python
Variable assignment
name = "Alice" age = 25 height = 5.6 is_student = TrueMultiple assignment
x, y, z = 1, 2, 3 a = b = c = 0Variable naming rules
valid_name = "correct" _private_var = "valid" name123 = "valid"Invalid variable names (will cause errors)
123name = "invalid" # Cannot start with number
my-var = "invalid" # Cannot contain hyphens
class = "invalid" # Cannot use reserved keywords
`Operators
#### Arithmetic Operators
| Operator | Name | Example | Result |
|----------|------|---------|--------|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| | Multiplication | 5 3 | 15 |
| / | Division | 10 / 3 | 3.333... |
| // | Floor Division | 10 // 3 | 3 |
| % | Modulus | 10 % 3 | 1 |
| | Exponentiation | 2 3 | 8 |
`python
Arithmetic operations
a = 10 b = 3print(f"{a} + {b} = {a + b}") # 10 + 3 = 13
print(f"{a} - {b} = {a - b}") # 10 - 3 = 7
print(f"{a} {b} = {a b}") # 10 * 3 = 30
print(f"{a} / {b} = {a / b}") # 10 / 3 = 3.333...
print(f"{a} // {b} = {a // b}") # 10 // 3 = 3
print(f"{a} % {b} = {a % b}") # 10 % 3 = 1
print(f"{a} {b} = {a b}") # 10 3 = 1000
`
#### Comparison Operators
| Operator | Name | Example | Result |
|----------|------|---------|--------|
| == | Equal to | 5 == 5 | True |
| != | Not equal to | 5 != 3 | True |
| > | Greater than | 5 > 3 | True |
| < | Less than | 3 < 5 | True |
| >= | Greater than or equal | 5 >= 5 | True |
| <= | Less than or equal | 3 <= 5 | True |
#### Logical Operators
| Operator | Description | Example |
|----------|-------------|---------|
| and | Returns True if both operands are True | True and False → False |
| or | Returns True if at least one operand is True | True or False → True |
| not | Returns opposite boolean value | not True → False |
`python
Logical operators example
age = 25 has_license = True has_car = Falsecan_drive = age >= 18 and has_license print(f"Can drive: {can_drive}") # True
needs_transport = not has_car or age < 16
print(f"Needs transport: {needs_transport}") # True
`
#### Assignment Operators
| Operator | Example | Equivalent |
|----------|---------|------------|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| = | x = 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| %= | x %= 3 | x = x % 3 |
| = | x = 3 | x = x 3 |
Control Flow
Conditional Statements
#### if, elif, else
`python
Basic if statement
age = 18 if age >= 18: print("You are an adult")if-else statement
temperature = 25 if temperature > 30: print("It's hot outside") else: print("It's not too hot")if-elif-else statement
score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F"print(f"Your grade is: {grade}")
`
#### Nested Conditions
`python
Nested if statements
weather = "sunny" temperature = 25if weather == "sunny": if temperature > 20: print("Perfect day for outdoor activities!") else: print("Sunny but a bit cold") else: print("Not a sunny day")
Complex conditions
age = 25 income = 50000 credit_score = 720if age >= 18 and income >= 30000 and credit_score >= 650:
print("Loan approved")
else:
print("Loan denied")
`
Loops
#### for Loop
`python
Basic for loop
fruits = ["apple", "banana", "orange"] for fruit in fruits: print(f"I like {fruit}")for loop with range
for i in range(5): print(f"Number: {i}")range with start, stop, step
for i in range(1, 10, 2): print(i) # Prints: 1, 3, 5, 7, 9for loop with enumerate
names = ["Alice", "Bob", "Charlie"] for index, name in enumerate(names): print(f"{index}: {name}")`#### while Loop
`python
Basic while loop
count = 0 while count < 5: print(f"Count: {count}") count += 1while loop with user input
user_input = "" while user_input.lower() != "quit": user_input = input("Enter 'quit' to exit: ") if user_input.lower() != "quit": print(f"You entered: {user_input}")Infinite loop prevention
attempts = 0 max_attempts = 3 while attempts < max_attempts: password = input("Enter password: ") if password == "secret123": print("Access granted!") break else: attempts += 1 print(f"Wrong password. {max_attempts - attempts} attempts left.")`#### Loop Control Statements
| Statement | Description | Usage |
|-----------|-------------|-------|
| break | Exits the loop completely | Used to terminate loop early |
| continue | Skips current iteration | Used to skip to next iteration |
| pass | Does nothing (placeholder) | Used as syntactic placeholder |
`python
break example
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for num in numbers: if num == 6: break print(num) # Prints: 1, 2, 3, 4, 5continue example
for num in range(1, 11): if num % 2 == 0: continue print(num) # Prints odd numbers: 1, 3, 5, 7, 9pass example
for i in range(5): if i == 2: pass # Placeholder - do nothing else: print(i)`Functions
Functions are reusable blocks of code that perform specific tasks.
Function Definition and Calling
`python
Basic function definition
def greet(): print("Hello, World!")Calling the function
greet() # Output: Hello, World!Function with parameters
def greet_person(name): print(f"Hello, {name}!")greet_person("Alice") # Output: Hello, Alice!
Function with multiple parameters
def add_numbers(a, b): result = a + b return resultsum_result = add_numbers(5, 3)
print(sum_result) # Output: 8
`
Function Parameters and Arguments
#### Default Parameters
`python
def greet_with_title(name, title="Mr./Ms."):
print(f"Hello, {title} {name}!")
greet_with_title("Smith") # Hello, Mr./Ms. Smith!
greet_with_title("Johnson", "Dr.") # Hello, Dr. Johnson!
`
#### Keyword Arguments
`python
def create_profile(name, age, city, occupation):
return f"{name}, {age} years old, works as {occupation} in {city}"
Positional arguments
profile1 = create_profile("Alice", 30, "New York", "Engineer")Keyword arguments
profile2 = create_profile(name="Bob", occupation="Teacher", age=25, city="Boston")print(profile1)
print(profile2)
`
#### Variable-Length Arguments
`python
*args - Variable number of positional arguments
def calculate_sum(*numbers): total = 0 for num in numbers: total += num return totalprint(calculate_sum(1, 2, 3)) # 6 print(calculate_sum(1, 2, 3, 4, 5)) # 15
kwargs - Variable number of keyword arguments
def create_student(details): print("Student Information:") for key, value in details.items(): print(f"{key}: {value}")create_student(name="Alice", age=20, major="Computer Science", gpa=3.8)
`
Lambda Functions
`python
Lambda function (anonymous function)
square = lambda x: x 2 print(square(5)) # 25Lambda with multiple arguments
multiply = lambda x, y: x * y print(multiply(3, 4)) # 12Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x 2, numbers)) print(squared_numbers) # [1, 4, 9, 16, 25]Filter with lambda
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # [2, 4]`Scope and Global Variables
`python
Global variable
global_var = "I am global"def function_scope(): # Local variable local_var = "I am local" print(global_var) # Can access global variable print(local_var) # Can access local variable
function_scope()
print(local_var) # This would cause an error
Modifying global variable
counter = 0def increment(): global counter counter += 1
increment()
increment()
print(counter) # 2
`
Data Structures
Lists
Lists are ordered, mutable collections that can store different data types.
`python
Creating lists
fruits = ["apple", "banana", "orange"] numbers = [1, 2, 3, 4, 5] mixed_list = ["hello", 42, 3.14, True]List operations
print(len(fruits)) # 3 print(fruits[0]) # apple print(fruits[-1]) # orange (last element)Modifying lists
fruits.append("grape") # Add to end fruits.insert(1, "mango") # Insert at index 1 fruits.remove("banana") # Remove first occurrence popped_item = fruits.pop() # Remove and return last itemList slicing
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(numbers[2:5]) # [2, 3, 4] print(numbers[:3]) # [0, 1, 2] print(numbers[7:]) # [7, 8, 9] print(numbers[::2]) # [0, 2, 4, 6, 8] (every 2nd element)`#### List Methods
| Method | Description | Example |
|--------|-------------|---------|
| append(item) | Add item to end | list.append("new") |
| insert(index, item) | Insert item at index | list.insert(0, "first") |
| remove(item) | Remove first occurrence | list.remove("item") |
| pop(index) | Remove and return item | list.pop(0) |
| index(item) | Find index of item | list.index("item") |
| count(item) | Count occurrences | list.count("item") |
| sort() | Sort list in place | list.sort() |
| reverse() | Reverse list in place | list.reverse() |
Tuples
Tuples are ordered, immutable collections.
`python
Creating tuples
coordinates = (10, 20) colors = ("red", "green", "blue") single_item = ("item",) # Note the comma for single item tupleAccessing tuple elements
print(coordinates[0]) # 10 print(colors[-1]) # blueTuple unpacking
x, y = coordinates print(f"X: {x}, Y: {y}")Tuples are immutable
coordinates[0] = 15 # This would cause an error
Tuple methods
numbers = (1, 2, 3, 2, 4, 2) print(numbers.count(2)) # 3 print(numbers.index(3)) # 2`Dictionaries
Dictionaries store key-value pairs and are mutable.
`python
Creating dictionaries
student = { "name": "Alice", "age": 20, "major": "Computer Science", "gpa": 3.8 }Accessing dictionary values
print(student["name"]) # Alice print(student.get("age")) # 20 print(student.get("phone", "N/A")) # N/A (default value)Modifying dictionaries
student["age"] = 21 # Update existing key student["phone"] = "123-456-7890" # Add new key-value pair del student["gpa"] # Delete key-value pairDictionary methods
print(student.keys()) # dict_keys(['name', 'age', 'major', 'phone']) print(student.values()) # dict_values(['Alice', 21, 'Computer Science', '123-456-7890']) print(student.items()) # dict_items([('name', 'Alice'), ...])Iterating through dictionary
for key, value in student.items(): print(f"{key}: {value}")`#### Dictionary Methods
| Method | Description | Example |
|--------|-------------|---------|
| get(key, default) | Get value or default | dict.get("key", "default") |
| keys() | Get all keys | dict.keys() |
| values() | Get all values | dict.values() |
| items() | Get key-value pairs | dict.items() |
| pop(key) | Remove and return value | dict.pop("key") |
| update(other) | Update with another dict | dict.update(other_dict) |
| clear() | Remove all items | dict.clear() |
Sets
Sets are unordered collections of unique elements.
`python
Creating sets
fruits = {"apple", "banana", "orange"} numbers = {1, 2, 3, 4, 5}Set operations
fruits.add("grape") # Add element fruits.remove("banana") # Remove element (raises error if not found) fruits.discard("mango") # Remove element (no error if not found)Set mathematical operations
set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6}print(set1.union(set2)) # {1, 2, 3, 4, 5, 6} print(set1.intersection(set2)) # {3, 4} print(set1.difference(set2)) # {1, 2}
Checking membership
print(3 in set1) # True print(7 in set1) # False`File Handling
Reading Files
`python
Reading entire file
with open("example.txt", "r") as file: content = file.read() print(content)Reading line by line
with open("example.txt", "r") as file: for line in file: print(line.strip()) # strip() removes newline charactersReading lines into a list
with open("example.txt", "r") as file: lines = file.readlines() print(lines)`Writing Files
`python
Writing to file (overwrites existing content)
with open("output.txt", "w") as file: file.write("Hello, World!\n") file.write("This is a new line.\n")Appending to file
with open("output.txt", "a") as file: file.write("This line is appended.\n")Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"] with open("output.txt", "w") as file: file.writelines(lines)`File Modes
| Mode | Description | Usage |
|------|-------------|-------|
| "r" | Read only | Default mode for reading |
| "w" | Write only | Overwrites existing file |
| "a" | Append only | Adds to end of file |
| "r+" | Read and write | File must exist |
| "w+" | Write and read | Creates new file |
| "x" | Exclusive creation | Fails if file exists |
Working with CSV Files
`python
import csv
Reading CSV file
with open("data.csv", "r") as file: csv_reader = csv.reader(file) for row in csv_reader: print(row)Writing CSV file
data = [ ["Name", "Age", "City"], ["Alice", "25", "New York"], ["Bob", "30", "Boston"], ["Charlie", "35", "Chicago"] ]with open("output.csv", "w", newline="") as file: csv_writer = csv.writer(file) csv_writer.writerows(data)
Working with CSV dictionaries
with open("data.csv", "r") as file: csv_reader = csv.DictReader(file) for row in csv_reader: print(f"Name: {row['Name']}, Age: {row['Age']}")`Error Handling
Try-Except Blocks
`python
Basic exception handling
try: number = int(input("Enter a number: ")) result = 10 / number print(f"Result: {result}") except ValueError: print("Invalid input! Please enter a valid number.") except ZeroDivisionError: print("Cannot divide by zero!")Multiple exceptions in one except block
try: # Some risky operation pass except (ValueError, TypeError) as e: print(f"Error occurred: {e}")Catching all exceptions
try: # Some operation pass except Exception as e: print(f"An error occurred: {e}")`Finally and Else Clauses
`python
try-except-else-finally
def divide_numbers(a, b): try: result = a / b except ZeroDivisionError: print("Cannot divide by zero!") return None else: print("Division successful!") return result finally: print("This always executes")print(divide_numbers(10, 2)) # Division successful! This always executes 5.0
print(divide_numbers(10, 0)) # Cannot divide by zero! This always executes None
`
Common Exception Types
| Exception | Description | Example |
|-----------|-------------|---------|
| ValueError | Invalid value for operation | int("abc") |
| TypeError | Wrong data type | "hello" + 5 |
| IndexError | List index out of range | list[10] when list has 5 items |
| KeyError | Dictionary key not found | dict["nonexistent"] |
| FileNotFoundError | File doesn't exist | open("missing.txt") |
| ZeroDivisionError | Division by zero | 10 / 0 |
Raising Custom Exceptions
`python
Raising built-in exceptions
def validate_age(age): if age < 0: raise ValueError("Age cannot be negative") if age > 150: raise ValueError("Age seems unrealistic") return ageCustom exception classes
class CustomError(Exception): def __init__(self, message): self.message = message super().__init__(self.message)def process_data(data): if not data: raise CustomError("Data cannot be empty") return data.upper()
Using custom exceptions
try: result = process_data("") except CustomError as e: print(f"Custom error: {e.message}")`Object-Oriented Programming
Classes and Objects
`python
Basic class definition
class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): return f"Hi, I'm {self.name} and I'm {self.age} years old." def have_birthday(self): self.age += 1 return f"Happy birthday! {self.name} is now {self.age}."Creating objects (instances)
person1 = Person("Alice", 25) person2 = Person("Bob", 30)print(person1.introduce()) # Hi, I'm Alice and I'm 25 years old.
print(person1.have_birthday()) # Happy birthday! Alice is now 26.
`
Class Attributes and Methods
`python
class BankAccount:
# Class attribute (shared by all instances)
bank_name = "Python Bank"
interest_rate = 0.02
def __init__(self, account_holder, initial_balance=0):
# Instance attributes
self.account_holder = account_holder
self.balance = initial_balance
self.transaction_history = []
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transaction_history.append(f"Deposited: ${amount}")
return f"Deposited ${amount}. New balance: ${self.balance}"
else:
return "Deposit amount must be positive"
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient funds"
elif amount > 0:
self.balance -= amount
self.transaction_history.append(f"Withdrew: ${amount}")
return f"Withdrew ${amount}. New balance: ${self.balance}"
else:
return "Withdrawal amount must be positive"
def get_balance(self):
return f"Current balance: ${self.balance}"
@classmethod
def set_interest_rate(cls, new_rate):
cls.interest_rate = new_rate
@staticmethod
def validate_account_number(account_number):
return len(str(account_number)) == 10
Using the class
account = BankAccount("Alice", 1000) print(account.deposit(500)) # Deposited $500. New balance: $1500 print(account.withdraw(200)) # Withdrew $200. New balance: $1300 print(account.get_balance()) # Current balance: $1300`Inheritance
`python
Base class
class Animal: def __init__(self, name, species): self.name = name self.species = species def make_sound(self): return f"{self.name} makes a sound" def info(self): return f"{self.name} is a {self.species}"Derived class
class Dog(Animal): def __init__(self, name, breed): super().__init__(name, "Dog") # Call parent constructor self.breed = breed def make_sound(self): # Method overriding return f"{self.name} barks!" def fetch(self): # New method specific to Dog return f"{self.name} fetches the ball!"class Cat(Animal): def __init__(self, name, color): super().__init__(name, "Cat") self.color = color def make_sound(self): return f"{self.name} meows!" def climb(self): return f"{self.name} climbs the tree!"
Using inheritance
dog = Dog("Buddy", "Golden Retriever") cat = Cat("Whiskers", "Orange")print(dog.info()) # Buddy is a Dog print(dog.make_sound()) # Buddy barks! print(dog.fetch()) # Buddy fetches the ball!
print(cat.info()) # Whiskers is a Cat
print(cat.make_sound()) # Whiskers meows!
print(cat.climb()) # Whiskers climbs the tree!
`
Encapsulation
`python
class Student:
def __init__(self, name, student_id):
self.name = name
self._student_id = student_id # Protected attribute
self.__grades = [] # Private attribute
def add_grade(self, grade):
if 0 <= grade <= 100:
self.__grades.append(grade)
else:
raise ValueError("Grade must be between 0 and 100")
def get_average(self):
if self.__grades:
return sum(self.__grades) / len(self.__grades)
return 0
def get_grades(self):
return self.__grades.copy() # Return copy to prevent external modification
def __str__(self): # String representation
return f"Student: {self.name} (ID: {self._student_id})"
Using encapsulation
student = Student("Alice", "12345") student.add_grade(85) student.add_grade(92) student.add_grade(78)print(student) # Student: Alice (ID: 12345) print(f"Average grade: {student.get_average():.2f}") # Average grade: 85.00 print(f"Grades: {student.get_grades()}") # Grades: [85, 92, 78]
Cannot directly access private attributes
print(student.__grades) # This would cause an AttributeError
`Modules and Packages
Importing Modules
`python
Different ways to import
import math from math import pi, sqrt from datetime import datetime as dt import random as rndUsing imported modules
print(math.pi) # 3.141592653589793 print(sqrt(16)) # 4.0 print(dt.now()) # Current date and time print(rnd.randint(1, 10)) # Random integer between 1 and 10`Creating Custom Modules
Create a file named my_module.py:
`python
my_module.py
def greet(name): return f"Hello, {name}!"def calculate_area(length, width): return length * width
PI = 3.14159
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
`
Using the custom module:
`python
main.py
import my_module from my_module import greet, PIprint(greet("World")) # Hello, World! print(f"Area: {my_module.calculate_area(5, 3)}") # Area: 15 print(f"PI value: {PI}") # PI value: 3.14159
calc = my_module.Calculator()
print(calc.add(5, 3)) # 8
`
Standard Library Modules
| Module | Description | Common Usage |
|--------|-------------|--------------|
| os | Operating system interface | File operations, environment variables |
| sys | System-specific parameters | Command line arguments, exit |
| datetime | Date and time handling | Current time, date calculations |
| random | Random number generation | Random numbers, choices |
| json | JSON encoder/decoder | Working with JSON data |
| re | Regular expressions | Pattern matching |
| urllib | URL handling | Web requests |
`python
Examples of standard library usage
import os import sys import datetime import json import randomOS module
print(os.getcwd()) # Current working directory print(os.listdir('.')) # List files in current directoryDatetime module
now = datetime.datetime.now() print(f"Current time: {now}") future_date = now + datetime.timedelta(days=30) print(f"Date in 30 days: {future_date}")JSON module
data = {"name": "Alice", "age": 25, "city": "New York"} json_string = json.dumps(data) print(json_string) # {"name": "Alice", "age": 25, "city": "New York"}parsed_data = json.loads(json_string) print(parsed_data["name"]) # Alice
Random module
print(random.randint(1, 100)) # Random integer print(random.choice(["apple", "banana", "orange"])) # Random choice numbers = [1, 2, 3, 4, 5] random.shuffle(numbers) print(numbers) # Shuffled list`This comprehensive guide covers the fundamental concepts of Python programming. Each section builds upon previous knowledge and provides practical examples that you can run and modify. Practice these concepts by writing your own programs and experimenting with the code examples provided.