0% found this document useful (0 votes)
5 views3 pages

Python Functions and OOP Overview

Uploaded by

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

Python Functions and OOP Overview

Uploaded by

shristii365
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Cheatsheet (with OOP + Exception

Handling)

📌 1. Python Basics

# Variables
x = 10
name = "Alice"
# Data Types
num = 5 # int
pi = 3.14 # float
flag = True # bool
text = "Hello" # str
items = [1, 2, 3] # list
info = {'a': 1} # dict

📌 2. Functions

def greet(name):
return f"Hello, {name}"
# Default argumentdef greet(name="Friend"):
return f"Hello, {name}"
# Keyword arguments
greet(name="Bob")

📌 3. Loops & Conditions

# if-elif-elseif x > 0:
print("Positive")elif x == 0:
print("Zero")else:
print("Negative")
# for loopfor item in [1, 2, 3]:
print(item)
# while loop
i = 0while i < 5:
print(i)
i += 1

📌 4. List Comprehension

squares = [x**2 for x in range(5)]


evens = [x for x in range(10) if x % 2 == 0]
🧱 5. OOP in Python (Class, Object, Inheritance)
✅ Class & Object

class Person:
def __init__(self, name, age): # constructor
[Link] = name
[Link] = age

def greet(self):
print(f"Hi, I'm {[Link]}")

p1 = Person("Alice", 22)
[Link]()

✅ Inheritance

class Student(Person): # Inherits from Person


def __init__(self, name, age, grade):
super().__init__(name, age) # Call parent constructor
[Link] = grade

def show_grade(self):
print(f"Grade: {[Link]}")

s1 = Student("Bob", 20, "A")


[Link]()
s1.show_grade()

✅ Encapsulation (private variables)

class BankAccount:
def __init__(self, balance):
self.__balance = balance # private

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

acc = BankAccount(1000)
[Link](500)print(acc.get_balance()) # ✅ 1500

✅ Polymorphism (method overriding)


class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Bark")

a = Animal()
d = Dog()

[Link]() # Some sound


[Link]() # Bark

6. Exception Handling
try:
x = int(input("Enter number: "))
y = 10 / xexcept ZeroDivisionError:
print("Can't divide by zero!")except ValueError:
print("Invalid input")else:
print("Result:", y)finally:
print("This always runs")

📌 7. Common Built-ins
len([1, 2, 3]) # → 3sum([1, 2, 3]) # → 6max([5, 10, 2]) #→
10sorted([3, 1, 2]) # → [1, 2, 3]"hello".upper() # → "HELLO"list("abc")
# → ['a', 'b', 'c']

🧠 Tip:
If you're coming from C++, focus on how Python handles:

self instead of this

No need for semicolons or type declarations

Indentation = structure

Common questions

Powered by AI

In Python, variables are dynamically typed and do not require explicit type declarations, unlike C++ where variables must be declared with a specific data type before use. Python employs 'self' to refer to instance variables and does not use semicolons for statement termination, relying instead on indentation for block structuring .

List comprehensions offer a concise syntax to create lists, improving readability and often reducing the number of lines of code. They allow the integration of filtering and mapping operations within a single line. For example, '[x**2 for x in range(5)]' efficiently generates a list of squared numbers compared to using a traditional loop .

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass, facilitating polymorphism by enabling different behaviors. For instance, the 'sound' method is overridden in the 'Dog' class, which inherits from 'Animal'. The 'Dog' class redefines 'sound' to output 'Bark' instead of the superclass's 'Some sound', thus supporting polymorphic behavior .

Python's built-in functions like 'len()', 'sum()', and 'sorted()' offer standardized, optimized solutions for common tasks, ensuring ease of use and performance. However, custom functions provide unparalleled flexibility to encapsulate specific business logic tailored to particular needs, albeit without the assured efficiency of built-in equivalents. Built-ins are best for general tasks, while custom functions excel in scenarios demanding unique operations or integrations .

Inheritance in Python allows a class to inherit attributes and methods from another class, promoting code reuse and logical hierarchies. Implemented using the syntax 'class DerivedClass(BaseClass):', the derived class inherits from the base class. For example, in the document, the class 'Student' inherits from the 'Person' class. It uses 'super().__init__(name, age)' to call the parent class constructor and adds its 'grade' attribute .

The 'finally' block is crucial for executing cleanup or recovery actions, ensuring code runs regardless of whether an exception occurs, thus maintaining program stability. It is particularly important for resource management tasks such as closing files or releasing locks, where neglect could cause data corruption or system resource leaks. The block maintains exception chain integrity while ensuring consistent cleanup .

A Python programmer might choose to use keyword arguments to improve code readability and clarify the purpose of passed values, especially in functions with multiple parameters. Keyword arguments allow the function to be called in any order, and defaults can be set, reducing the risk of error. For instance, 'greet(name="Bob")' makes it clear that 'Bob' is the value for 'name', enhancing readability .

Default arguments in Python functions allow parameters to have default values if no argument is provided during function calls, aiding in code flexibility and simplicity. For instance, 'def greet(name="Friend"): return f"Hello, {name}"' calls 'greet()' without arguments, defaulting 'name' to 'Friend'. This feature simplifies function calls and reduces necessity for overloaded methods in cases with common default needs .

Encapsulation in Python involves restricting access to certain components of an object, thereby protecting the internal state and maintaining integrity. It is achieved by defining private variables using underscores (e.g., '__balance'). The class 'BankAccount' demonstrates this by encapsulating the '__balance' variable, which can only be accessed or modified through defined methods like 'deposit' or 'get_balance' .

Error handling in Python is crucial for creating robust programs that can gracefully handle runtime errors and exceptions, preventing unexpected crashes. It is implemented using 'try', 'except', 'else', and 'finally' blocks. The 'try' block contains code that might raise an exception; 'except' handles specific exceptions like 'ZeroDivisionError'; 'else' executes code if no exceptions occur; and 'finally' runs code regardless of the outcome, ensuring resources are released or checked .

You might also like