0% found this document useful (0 votes)
0 views15 pages

Python

The document provides a comprehensive overview of various Python programming concepts, including iterators, generators, modules, list comprehensions, and more. Each concept is defined, illustrated with examples, and explained for clarity. Additionally, it touches on advanced topics like object-oriented programming, error handling, and functional programming tools.

Uploaded by

priyaapriiyaa26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views15 pages

Python

The document provides a comprehensive overview of various Python programming concepts, including iterators, generators, modules, list comprehensions, and more. Each concept is defined, illustrated with examples, and explained for clarity. Additionally, it touches on advanced topics like object-oriented programming, error handling, and functional programming tools.

Uploaded by

priyaapriiyaa26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1.

Iterators

Definition: An object in Python that implements the iterator protocol with __iter__() and __next__()
methods.

Example:

python

CopyEdit

nums = [1, 2, 3]

it = iter(nums)

print(next(it)) # Output: 1

print(next(it)) # Output: 2

Explanation: iter() returns an iterator object; next() fetches the next item. for loops use this protocol
internally.

2. Generators

Definition: A function that uses yield to return a sequence of values lazily (on demand), saving
memory.

Example:

python

CopyEdit

def fib(n):

a, b = 0, 1

for _ in range(n):

yield a

a, b = b, a + b

for i in fib(5): # Output: 0 1 1 2 3

print(i)

Explanation: yield pauses function state and resumes on next iteration, useful for large or infinite
sequences.

3. Modules and Packages

Definition:
• Module: A .py file containing Python code.

• Package: A directory with an __init__.py, grouping related modules.

Example:

python

CopyEdit

# file: math_utils.py

def square(x):

return x * x

# main.py

import math_utils

print(math_utils.square(4)) # Output: 16

Explanation: Helps organize and reuse code across multiple scripts.

4. List Comprehensions

Definition: A concise way to create lists using for loops and optional if conditions.

Example:

python

CopyEdit

squares = [x*x for x in range(5)] # [0, 1, 4, 9, 16]

evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]

Explanation: Improves readability and performance for simple list transformations.

5. Regular Expressions

Definition: A powerful tool for pattern matching and text processing using the re module.

Example:

python

CopyEdit

import re

pattern = r"\d{3}-\d{2}-\d{4}"

text = "My SSN is 123-45-6789"


match = re.search(pattern, text)

print(match.group()) # Output: 123-45-6789

Explanation: \d{3} matches exactly 3 digits; useful for extracting patterns like dates, emails, or IDs.

6. Serialization (Pickle)

Definition: Converting Python objects into byte streams using pickle for saving or transferring.

Example:

python

CopyEdit

import pickle

data = {"name": "Anusha", "age": 21}

with open("data.pkl", "wb") as f:

pickle.dump(data, f)

# Load back

with open("data.pkl", "rb") as f:

restored = pickle.load(f)

print(restored["name"]) # Output: Anusha

Explanation: Saves and retrieves complex objects like dictionaries between sessions.

7. Partial Functions

Definition: Fixes some arguments of a function using functools.partial, creating a new callable.

Example:

python

CopyEdit

from functools import partial

def power(base, exponent):

return base ** exponent

square = partial(power, exponent=2)


print(square(5)) # Output: 25

Explanation: Creates customized versions of functions without rewriting them.

8. Closures

Definition: A function defined inside another that remembers variables from the enclosing scope.

Example:

python

CopyEdit

def outer(x):

def inner(y):

return x + y

return inner

add10 = outer(10)

print(add10(5)) # Output: 15

Explanation: inner retains access to x even after outer has finished execution.

9. Decorators

Definition: Functions that modify the behavior of other functions without changing their code.

Example:

python

CopyEdit

def logger(func):

def wrapper(*args, **kwargs):

print(f"Calling {func.__name__}")

return func(*args, **kwargs)

return wrapper

@logger

def greet(name):

print(f"Hello, {name}!")
greet("Anusha")

# Output: Calling greet

# Hello, Anusha!

Explanation: Enhances functions with additional logic (like logging) using @decorator syntax.

10. Functional Programming Tools (map, filter, reduce)

Definition:

• map: Applies a function to all items.

• filter: Filters items based on a condition.

• reduce: Reduces a sequence to a single value.

Example:

python

CopyEdit

from functools import reduce

nums = [1, 2, 3, 4]

print(list(map(lambda x: x*x, nums))) # [1, 4, 9, 16]

print(list(filter(lambda x: x % 2 == 0, nums))) # [2, 4]

print(reduce(lambda x, y: x + y, nums)) # 10

Explanation: Supports concise transformations, filtering, and aggregation.

11. Stacks (Abstract Data Structure)

Definition: A linear data structure following LIFO (Last-In-First-Out) principle.

Example:

python

CopyEdit

stack = []

stack.append('A') # Push

stack.append('B')

print(stack.pop()) # Output: B
Explanation: Use .append() to push and .pop() to remove the top element.

12. Object-Oriented Stack Implementation

Definition: Implementing stack using class for better abstraction and reuse.

Example:

python

CopyEdit

class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

return self.items.pop()

def is_empty(self):

return len(self.items) == 0

s = Stack()

s.push(1)

print(s.pop()) # Output: 1

Explanation: Encapsulates stack operations within a class for clean, structured use.

13. Reversing a String using Stack

Example:

python

CopyEdit

def reverse_string(s):

stack = list(s)

result = ''

while stack:

result += stack.pop()
return result

print(reverse_string("Python")) # Output: nohtyP

Explanation: Shows real-world stack usage by reversing the order of characters (LIFO principle).
1. Functions (with Parameters & Return Values)

Definition: Blocks of reusable code that can accept inputs (parameters) and optionally return
outputs.

Example:

python

CopyEdit

def greet(name):

return f"Hello, {name}!"

print(greet("Anusha")) # Output: Hello, Anusha!

Explanation: Enables modular, reusable, and clean code.

2. Variable Scope

Definition: Refers to where a variable can be accessed (local, global, or nonlocal).

Example:

python

CopyEdit

x = 10 # Global

def show():

x = 5 # Local

print(x) # Output: 5

Explanation: Scope determines variable visibility and lifespan.

3. Data Types

• String (str):

python

CopyEdit

name = "Python"

print(name.upper()) # Output: PYTHON

• Integer (int), Float (float), Boolean (bool):


python

CopyEdit

age = 20

pi = 3.14

is_valid = True

• List:

python

CopyEdit

colors = ['red', 'green']

colors.append('blue')

• Tuple:

python

CopyEdit

point = (1, 2)

• Dictionary:

python

CopyEdit

student = {"name": "Anusha", "age": 21}

print(student["name"])

• Set:

python

CopyEdit

s = {1, 2, 2, 3}

print(s) # Output: {1, 2, 3}

Explanation: These are the core building blocks for data representation and manipulation.

4. Operators

• Arithmetic:

python

CopyEdit

print(5 + 3) # Output: 8
• Comparison:

python

CopyEdit

print(5 > 3) # Output: True

• Logical:

python

CopyEdit

print(True and False) # Output: False

• Bitwise:

python

CopyEdit

print(5 & 3) # Output: 1

Explanation: Operators perform computations and comparisons.

5. Control Structures

• If-Else:

python

CopyEdit

if x > 0:

print("Positive")

elif x == 0:

print("Zero")

else:

print("Negative")

• While Loop:

python

CopyEdit

i=0

while i < 3:

print(i)

i += 1
• For Loop:

python

CopyEdit

for i in range(3):

print(i)

Explanation: Control the flow of program execution based on conditions and repetition.

6. Error Handling

Definition: Catch and handle exceptions using try-except.

Example:

python

CopyEdit

try:

print(10 / 0)

except ZeroDivisionError:

print("Cannot divide by zero!")

Explanation: Prevents programs from crashing due to unexpected errors.

7. Recursion

Definition: A function calling itself to solve subproblems.

Example:

python

CopyEdit

def factorial(n):

if n == 0:

return 1

return n * factorial(n - 1)

Explanation: Useful for problems like factorial, Fibonacci, etc.

8. Decorators

Definition: A way to modify a function’s behavior without changing its code.


Example:

python

CopyEdit

def decorator(func):

def wrapper():

print("Before function call")

func()

print("After function call")

return wrapper

@decorator

def say_hello():

print("Hello!")

say_hello()

Explanation: Enhances functions, often used in logging or access control.

9. Lambda Functions

Definition: Small anonymous functions for quick operations.

Example:

python

CopyEdit

square = lambda x: x * x

print(square(4)) # Output: 16

Explanation: Ideal for short, simple functions used once.

10. map(), filter(), reduce()

• Map:

python

CopyEdit

print(list(map(lambda x: x*2, [1, 2, 3]))) # Output: [2, 4, 6]


• Filter:

python

CopyEdit

print(list(filter(lambda x: x % 2 == 0, [1, 2, 3]))) # Output: [2]

• Reduce:

python

CopyEdit

from functools import reduce

print(reduce(lambda x, y: x + y, [1, 2, 3])) # Output: 6

Explanation: Enables functional-style programming for transformation and reduction of data.

11. OOP (Classes, Inheritance, Operator Overloading)

• Class & Object:

python

CopyEdit

class Dog:

def __init__(self, name):

self.name = name

def speak(self):

return f"{self.name} says Woof!"

d = Dog("Buddy")

print(d.speak())

• Inheritance:

python

CopyEdit

class Puppy(Dog):

def speak(self):

return f"{self.name} says Yip!"

• Operator Overloading:
python

CopyEdit

class Point:

def __init__(self, x, y):

self.x, self.y = x, y

def __add__(self, other):

return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)

p2 = Point(3, 4)

p3 = p1 + p2 # Uses overloaded `+`

Explanation: OOP promotes encapsulation, code reuse, and logical structuring for large projects.

12. Modules & Package Management (pip)

• Importing Modules:

python

CopyEdit

import math

print(math.sqrt(16)) # Output: 4.0

• Using pip:

bash

CopyEdit

pip install requests

• Example:

python

CopyEdit

import requests

r = requests.get("https://api.github.com")

print(r.status_code)

Explanation: Modules and pip extend Python's capabilities with built-in and third-party packages.
13. Real-World Project: Blackjack Game

Project Structure:

• Card class: holds suit and rank

• Deck class: builds and shuffles deck

• Hand class: stores cards for player/dealer

• Game loop: manages turns, user input, win/loss logic

Example Snippet:

python

CopyEdit

class Card:

def __init__(self, suit, rank):

self.suit = suit

self.rank = rank

def __str__(self):

return f"{self.rank} of {self.suit}"

Explanation: This project reinforces all concep

You might also like