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

Python Basic

Python is a high-level, easy-to-learn programming language used for various applications like web development, data science, and automation. It features a simple syntax, case sensitivity, and does not require variable type declaration. Key concepts include variables, data types, string manipulation, and operators.

Uploaded by

anamikasaukta9
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)
5 views43 pages

Python Basic

Python is a high-level, easy-to-learn programming language used for various applications like web development, data science, and automation. It features a simple syntax, case sensitivity, and does not require variable type declaration. Key concepts include variables, data types, string manipulation, and operators.

Uploaded by

anamikasaukta9
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/ 43

Python Basic

What is Python?

Python is a high-level programming language that is:

• Simple & Easy to Learn – Its code looks like English, so even beginners can
understand it.

• Powerful – You can use Python for almost anything:

o Web development (websites, apps)

o Data Science & Machine Learning

o Artificial Intelligence

o Game Development

o Automation (making the computer do repetitive tasks for you)

• Interpreted Language – You can run Python code directly without converting it
into machine code first.

• Open Source – Free for everyone to use and supported by a huge community.

In short: Python is like a tool that allows you to “talk” to the computer in a very easy
way.

First Python Code

The traditional first program is to print a message:

print("Hello, World!")

Explanation in simple words:

• print → A command (called a function) that tells the computer to show


something on the screen.

• "Hello, World!" → This is a string (text inside quotes).

• Together → The computer will display:

Hello, World!
Python Syntax
Syntax = The set of rules that define how we must write Python code so the computer
can understand it.
If we don’t follow the rules → Python will show errors.

Think of syntax like grammar in English:

• In English: “I playing am” is wrong grammar.

• In Python: print"Hello" is wrong syntax.

Main Rules of Python Syntax

1. Case Sensitivity

Python is case-sensitive, meaning Print, PRINT, and print are all different.

• Correct:

print("Hello")

• Wrong:

Print("Hello") # will give error

2. Indentation (Very Important!)

• Indentation = spaces at the start of a line.

• In Python, indentation shows which block of code belongs together.

• Example:

if 10 > 5:

print("Ten is greater") # 4 spaces indentation

• Without indentation:

if 10 > 5:

print("Ten is greater") # Error

In most other languages, { } are used for blocks, but Python uses indentation.
3. No Semicolons Needed

• In C, C++, Java → lines end with ;

• In Python → you just press Enter.

• Example:

x=5

y = 10

print(x + y)

4. Comments in Python

Comments are ignored by Python, used only for humans to read the code.

• Single-line comment:

# This is a comment

print("Hello") # This will print Hello

• Multi-line comment:

"""

This is a

multi-line comment

in Python

"""

5. Quotes for Strings

• Strings (text) can be written in:

o Single quotes 'Hello'

o Double quotes "Hello"

• Both work the same.

• Example:

print("Python is fun")

print('I love coding')


6. Variables Don’t Need Declaration

In Python, you don’t need to declare variable types.

• Example:

x = 10 # integer

y = "Hello" # string

z = 5.5 # float

print(x, y, z)

7. Spacing and New Lines

• Each new statement goes on a new line.

• Example:

print("Line 1")

print("Line 2")

• You can also write multiple statements on one line using ; (but not
recommended):

print("Hello"); print("World")

Example Code with All Rules

# Python Syntax Example

x = 20 # variable

y = 15 # another variable

if x > y: # condition

print("x is greater than y") # indented block

Output:

x is greater than y
Common Beginner Mistakes

1. Forgetting indentation → IndentationError

2. Using Print instead of print → NameError

3. Forgetting quotes in strings → SyntaxError

4. print(Hello) # Wrong

5. print("Hello") # Correct

Summary:
Python syntax is clean, simple, and beginner-friendly.

• Indentation is the most important rule.

• No semicolons needed.

• Case sensitive.

• Easy use of variables and comments.


Variables in Python
A variable is like a container that stores data.
Think of it as a box with a label → you can put something inside it, check it later, or
replace it.

In Python, you don’t need to declare variables with their type (like int, string). Python
automatically understands the type from the value.

1. Creating Variables

You create a variable just by writing its name and assigning a value with =.

Examples:

x = 10

y = "Hello"

print(x) # Output: 10

print(y) # Output: Hello

age = 18

name = "Alice"

print("My name is", name, "and I am", age, "years old.")

2. Variable Names

Rules for naming variables:

• Must start with a letter or underscore (_)

• Cannot start with a number

• Can only contain letters, numbers, underscores

• Case-sensitive (Name and name are different)

Examples:

student_name = "John" # valid

_age = 20 # valid

2student = "Mike" # invalid (starts with number)

student-name = "Sam" # invalid (dash not allowed)


3. Assign Multiple Values

Python lets you assign values to multiple variables in one line.

Examples:

x, y, z = 10, 20, 30

print(x, y, z) # Output: 10 20 30

a = b = c = "Python"

print(a) # Output: Python

print(b) # Output: Python

print(c) # Output: Python

4. Output Variables

You can print variables using the print() function.

Examples:

name = "Alice"

print("Hello " + name) # Output: Hello Alice

x=5

y = 10

print("The sum is", x + y) # Output: The sum is 15

5. Global Variables

• A global variable is created outside of any function and can be used anywhere in
the program.

• A local variable is created inside a function and only works there.

• If you want to modify a global variable inside a function, use the global keyword.
Examples:

x = "awesome" # global variable

def myFunc():

print("Python is " + x) # using global variable

myFunc()

x = "awesome"

def myFunc():

global x

x = "fantastic" # modify global variable inside function

myFunc()

print("Python is " + x) # Output: Python is fantastic

6. Variable Exercises (Practice for Students)

Exercise 1:
Create variables name and age. Print:

My name is ___ and I am ___ years old.

Exercise 2:
Assign values 10, 20, 30 to variables a, b, c in a single line. Print their sum.

Exercise 3:
Try to use a global variable inside a function and change its value. Print before and after
the function call.

Summary:

• Variables store values.

• Python variable names must follow rules.

• You can assign multiple values in one line.

• Use print() to show variables.

• Variables can be global or local.


Python Data Types
In Python, data type means the kind of value you are storing in a variable.
For example, numbers, text, list of items, True/False values etc.

Python has many built-in data types, but let’s learn the most important ones:

1. Numbers
There are three types of numbers in Python:

• int → whole numbers (e.g., 5, -10, 100)

• float → decimal numbers (e.g., 3.14, -2.5, 10.0)

• complex → numbers with imaginary part (e.g., 3+5j)

Example:

x = 10 # int

y = 3.14 # float

z = 2 + 3j # complex

print(type(x))

print(type(y))

print(type(z))

2. String (str)
A string is text written inside quotes (" " or ' ').

Example:

name = "Python"

greeting = 'Hello, World!'

print(name)

print(greeting)
3. Boolean (bool)
Boolean values are either True or False. They are often used in conditions.

Example:

is_student = True

is_teacher = False

print(is_student)

print(is_teacher)

4. List
A list stores multiple items in one variable. Lists are written inside square brackets [ ].

Example:

fruits = ["apple", "banana", "cherry"]

numbers = [1, 2, 3, 4, 5]

print(fruits)

print(numbers)

5. Tuple
A tuple is like a list, but it cannot be changed (immutable). Written with parentheses ( ).

Example:

coordinates = (10, 20)

colors = ("red", "green", "blue")

print(coordinates)

print(colors)
6. Set
A set stores unique values (no duplicates) and is written inside curly braces { }.

Example:

my_set = {1, 2, 3, 4, 4, 5}

print(my_set) # duplicate 4 is removed

letters = {"a", "b", "c"}

print(letters)

7. Dictionary (dict)
A dictionary stores data in key–value pairs. Written with {key: value}.

Example:

student = {"name": "Alice", "age": 20, "grade": "A"}

print(student)

person = {"name": "Bob", "city": "Delhi"}

print(person["name"]) # Access value using key

Quick Summary
• int, float, complex → Numbers

• str → Text

• bool → True/False

• list, tuple, set → Collections

• dict → Key-value pairs


Practice Questions
1. Create a variable age with your age (integer) and print its type.

2. Store your name in a string and print it.

3. Make a list of 3 favorite foods and print the second one.

4. Create a tuple of 3 numbers and try changing one value (see what happens).

5. Make a set with duplicate numbers and print it (observe result).

6. Create a dictionary for a car with keys: brand, model, year. Print the model.
Python Strings
A string is a sequence of characters enclosed in single quotes ' ' or double quotes " ".

Strings are used to store text in Python.

name = "Alice"

greeting = 'Hello, World!'

print(name)

print(greeting)

1. Slicing Strings
Slicing is used to get a part of a string.
Syntax:

string[start:end:step]

• start → starting index (default 0)

• end → ending index (not included)

• step → how many steps to move forward (default 1)

Examples:

text = "Python"

print(text[0:4]) # Output: Pyth (from index 0 to 3)

print(text[2:]) # Output: thon (from index 2 to end)

print(text[:4]) # Output: Pyth (from start to index 3)

print(text[::2]) # Output: Pto (every 2nd character)

2. Modify Strings
Strings are immutable, meaning you cannot change them directly.
But you can create new strings by methods.
Common String Methods:

• .upper() → converts to uppercase

• .lower() → converts to lowercase

• .strip() → removes spaces from start/end

• .replace() → replace a substring with another

• .split() → splits string into a list

Examples:

text = " hello Python "

print(text.upper()) # Output: HELLO PYTHON

print(text.lower()) # Output: hello python

print(text.strip()) # Output: hello Python

print(text.replace("Python", "World")) # Output: hello World

print(text.split()) # Output: ['hello', 'Python']

3. String Concatenation
Concatenation means joining two or more strings using +.

Examples:

first = "Hello"

last = "World"

full = first + " " + last

print(full) # Output: Hello World

name = "Alice"

greeting = "Hi " + name + "!"

print(greeting) # Output: Hi Alice!


4. Format Strings
Formatting allows inserting variables or values into strings.

Methods:

1. Using f-strings (Python 3.6+)

name = "Alice"

age = 20

print(f"My name is {name} and I am {age} years old.")

2. Using format() method

name = "Bob"

age = 25

print("My name is {} and I am {} years old.".format(name, age))

3. Using % formatting (older method)

name = "Charlie"

age = 30

print("My name is %s and I am %d years old." % (name, age))

5. String Exercises
1. Create a string "PythonProgramming" and print only "Python" using slicing.

2. Convert " hello world " to uppercase and remove extra spaces.

3. Replace "Python" with "Java" in the string "I love Python".

4. Join the strings "Good" and "Morning" using concatenation.

5. Use f-string to print: "My favorite number is 7" (store 7 in a variable).

6. Split the string "Apple,Banana,Cherry" into a list.


Summary:
Topic Key Points

Strings Sequence of characters in ' ' or " "

Slicing Extract part of string using [start:end:step]

Use methods like .upper(), .lower(), .strip(), .replace(),


Modify Strings
.split()

Concatenation Join strings using +

Format Strings Insert variables using f"{}", .format(), %


Python Operators
Operators in Python are symbols that perform operations on variables and values.

There are 7 main types of operators:

1. Arithmetic Operators
Perform mathematical calculations.

Operator Meaning Example Output

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/2 2.5

// Floor Division 5 // 2 2

% Modulus 5%2 1

** Exponentiation 5 ** 2 25

Example:

x = 10

y=3

print(x + y) # 13

print(x % y) # 1

print(x ** y) # 1000
2. Assignment Operators
Used to assign or update values.

Operator Meaning Example

= Assign x=5

+= Add and assign x += 3

-= Subtract and assign x -= 2

*= Multiply and assign x *= 2

/= Divide and assign x /= 2

%= Modulus and assign x %= 3

**= Exponent and assign x **= 2

//= Floor divide and assign x //= 3

Example:

x=5

x += 3

print(x) # 8

y = 10

y *= 2

print(y) # 20
3. Comparison Operators
Used to compare values → returns True or False.

Operator Meaning Example

== Equal to 5 == 5 → True

!= Not equal 5 != 3 → True

> Greater than 5 > 3 → True

< Less than 5 < 3 → False

>= Greater or equal 5 >= 5 → True

<= Less or equal 5 <= 4 → False

Example:

x = 10

y=7

print(x > y) # True

print(x == y) # False

4. Logical Operators
Combine conditional statements.

Operator Meaning Example

and True if both True and False → False

or True if any True or False → True

not Reverse value not True → False

Example:

x=5

print(x > 3 and x < 10) # True

print(not(x > 3)) # False


5. Identity Operators
Check if two variables point to the same object in memory.

Operator Meaning Example

is Same object x is y → True

is not Not same x is not y → True

Example:

x = [1, 2, 3]

y=x

z = [1, 2, 3]

print(x is y) # True

print(x is z) # False

6. Membership Operators
Check if value exists in a sequence (list, string, tuple).

Operator Meaning Example

in Exists "a" in "apple" → True

not in Does not exist "x" not in "apple" → True

Example:

fruits = ["apple", "banana", "cherry"]

print("apple" in fruits) # True

print("mango" not in fruits) # True

7. Bitwise Operators
Perform operations on bits (binary numbers).
Operator Meaning Example

& AND 5&3→1

` ` OR

^ XOR 5^3→6

~ NOT ~5 → -6

<< Left shift 5 << 1 → 10

>> Right shift 5 >> 1 → 2

Example:

x = 5 # 0101 in binary

y = 3 # 0011 in binary

print(x & y) # 1

print(x | y) # 7

print(x ^ y) # 6

print(~x) # -6

print(x << 1) # 10

print(x >> 1) # 2

Practice Questions
1. Add, subtract, multiply, divide two numbers using arithmetic operators.

2. Use assignment operators to update a variable multiple times.

3. Compare two numbers using comparison operators.

4. Write a condition using logical operators to check if a number is between 10


and 20.

5. Check if "Python" exists in "I love Python" using membership operators.


Python Lists
A list is an ordered collection of items that can store different data types.

• Lists are mutable, which means you can change, add, or remove elements.

• Lists are defined using square brackets [ ].

Example 1: Creating a List


fruits = ["apple", "banana", "cherry"]

print(fruits)

Accessing Elements
print(fruits[0]) # apple

print(fruits[-1]) # cherry

Adding Elements
fruits.append("orange")

fruits.insert(1, "mango")

print(fruits)

Removing Elements
fruits.remove("banana")

popped = fruits.pop(2)

print(fruits)

print("Popped:", popped)

Iterating Through List


for fruit in fruits:

print(fruit)
Python Tuples
A tuple is an ordered collection of items, similar to a list, but immutable (cannot
change elements).

• Tuples are defined using parentheses ( ).

Example 2: Creating a Tuple


numbers = (1, 2, 3, 4, 5)

print(numbers)

Accessing Elements
print(numbers[0]) # 1

print(numbers[-1]) # 5

Tuple with One Element


single = (10,) # comma is necessary

print(single)

Iterating Through Tuple


for num in numbers:

print(num)
Python Sets
A set is an unordered collection of unique items.

• Sets do not allow duplicates.

• Sets are defined using curly braces { }.

Example 3: Creating a Set


colors = {"red", "green", "blue"}

print(colors)

Adding Elements
colors.add("yellow")

print(colors)

Removing Elements
colors.remove("green")

print(colors)

Iterating Through Set


for color in colors:

print(color)
Python Dictionaries
A dictionary is an unordered collection of key-value pairs.

• Keys must be unique and immutable (string, number, tuple).

• Values can be any data type.

• Dictionaries are defined using curly braces {} with key: value.

Example 4: Creating a Dictionary

student = {"name": "Alice", "age": 20, "grade": "A"}

print(student)

Accessing Values
print(student["name"]) # Alice

print(student.get("age")) # 20

Adding/Updating Values
student["age"] = 21

student["city"] = "Delhi"

print(student)

Removing Items
student.pop("grade")

del student["city"]

print(student)

Iterating Through Dictionary


for key, value in student.items():

print(key, ":", value)


Practice Questions
1. Create a list of 5 fruits, add two more fruits, remove one, and print the final list.

2. Create a tuple of 5 numbers and print the first and last element.

3. Create a set of colors, add a new color, and try adding a duplicate. Observe the
result.

4. Create a dictionary for a student with keys: name, age, grade. Update age, add
city, remove grade, and print all items.

5. Iterate through your list, tuple, set, and dictionary and print all elements.
If...Else in Python
In Python, decision making is done using conditional statements. Sometimes, we want
the program to make a choice depending on a condition.
For example:

• If you are above 18, you can vote.

• If you are below 18, you cannot vote.

This is possible using if, elif, and else statements.

1. The if Statement
The if statement is used to check a condition. If the condition is True, the code inside
will run.

Example 1:

age = 20

if age >= 18:

print("You are eligible to vote.")

Here, since age is 20 (which is ≥ 18), the message will print.

2. The if...else Statement


The else block runs when the if condition is False.

Example 2:

age = 16

if age >= 18:

print("You can vote.")

else:

print("You cannot vote.")

Since age = 16 is less than 18, it prints You cannot vote.


3. The if...elif...else Statement
We can check multiple conditions using elif (else if).

Example 3:

marks = 85

if marks >= 90:

print("Grade: A+")

elif marks >= 75:

print("Grade: A")

elif marks >= 60:

print("Grade: B")

else:

print("Grade: C")

Since marks = 85, the output is Grade: A.

4. Short Hand If
If you have only one statement, you can write it in one line.

Example 4:

x = 10

if x > 5: print("x is greater than 5")

5. Short Hand If...Else


We can also write if...else in one line.

Example 5:

a=2

b=5

print("A is greater") if a > b else print("B is greater")

Since b is bigger, it prints B is greater.


6. Nested If
We can put an if inside another if.

Example 6:

x = 15

if x > 10:

print("x is greater than 10")

if x > 20:

print("x is also greater than 20")

else:

print("x is not greater than 20")

Output:

x is greater than 10

x is not greater than 20

Practice Questions for Students


1. Write a program to check if a number is positive or negative.

2. Write a program to check if a person’s age is eligible for driving (≥18 years).

3. Write a program to find the largest of three numbers using if...elif...else.

4. Write a program that checks if a number is even or odd.


Python match Statement
The match statement in Python is used to compare a value against multiple
patterns.
It is similar to switch-case statements in other languages like C++ or Java.

It was introduced in Python 3.10.

Syntax

match variable:

case pattern1:

# code if pattern1 matches

case pattern2:

# code if pattern2 matches

case _:

# code if no pattern matches (default)

• variable → the value you want to check

• case pattern → pattern to match

• _ → wildcard (matches anything, acts like else)

Example 1: Basic Match

day = "Monday"

match day:

case "Monday":

print("Start of the work week!")

case "Friday":

print("End of the work week!")

case _:

print("Midweek days")
Output:

Start of the work week!

Example 2: Match Numbers

number = 3

match number:

case 1:

print("One")

case 2:

print("Two")

case 3:

print("Three")

case _:

print("Number not 1, 2, or 3")

Output:

Three

Example 3: Match with Multiple Patterns

You can match multiple values in the same case using |

color = "red"

match color:

case "red" | "pink":

print("Warm color")

case "blue" | "green":

print("Cool color")

case _:

print("Other color")
Output:

Warm color

Example 4: Match with Pattern Variables

You can capture the value in a variable using case var_name:

value = 10

match value:

case x if x > 5:

print(f"{x} is greater than 5")

case x:

print(f"{x} is 5 or less")

Output:

10 is greater than 5

Practice Questions
1. Write a program to print the name of the day based on a variable day (use
match).

2. Write a program to print whether a number is 1, 2, 3, or something else using


match.

3. Write a program that checks the color type (warm or cool) using multiple
patterns.

4. Use match to check if a number is positive, negative, or zero.


Python For Loops
A for loop in Python is used to iterate (repeat) over a sequence such as a list, string,
tuple, or range.

Syntax:

for variable in sequence:

# code to execute

• variable → takes the value of each item in the sequence one by one.

• The loop continues until all items are processed.

Example 1: Iterating over a List

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Output:

apple

banana

cherry

Example 2: Iterating over a String

word = "Python"

for letter in word:

print(letter)

Output:

t
h

Example 3: Using range() in For Loops

The range() function generates a sequence of numbers.

for i in range(5):

print(i)

Output:

• You can also use range(start, stop, step)

for i in range(1, 10, 2):

print(i)

Output:

Example 4: Nested For Loops

You can put a for loop inside another for loop.

for i in range(1, 4):

for j in range(1, 3):

print(f"i={i}, j={j}")
Output:

i=1, j=1

i=1, j=2

i=2, j=1

i=2, j=2

i=3, j=1

i=3, j=2

Example 5: Using break in For Loops

break stops the loop when a condition is met.

for i in range(1, 6):

if i == 4:

break

print(i)

Output:

Example 6: Using continue in For Loops

continue skips the current iteration and moves to the next one.

for i in range(1, 6):

if i == 3:

continue

print(i)

Output:

2
4

Example 7: Using else in For Loops

The else block runs when the loop finishes without encountering break.

for i in range(1, 4):

print(i)

else:

print("Loop is finished")

Output:

Loop is finished

Practice Questions
1. Print all numbers from 1 to 20 using a for loop.

2. Print all even numbers less than 30 using range().

3. Iterate over a list of your favorite colors and print each one.

4. Use a nested for loop to print a 3x3 multiplication table.

5. Write a program to skip printing number 5 while printing numbers 1 to 10 using


continue.

6. Write a program to stop the loop when a number 7 is reached using break.
Python Functions
A function is a block of reusable code that performs a specific task.
Instead of writing the same code again and again, you can call a function whenever
needed.

1. Defining a Function
Use the def keyword to define a function.

Syntax:

def function_name():

# code block

Example 1: Simple Function

def greet():

print("Hello, Python!")

greet() # calling the function

Output:

Hello, Python!

2. Function with Parameters


Parameters allow you to pass values into a function.

Syntax:

def function_name(parameter1, parameter2):

# code block

Example 2:

def greet(name):

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

greet("Alice")

greet("Bob")
Output:

Hello, Alice!

Hello, Bob!

3. Function with Return Value


A function can return a value using the return statement.

Example 3:

def add(a, b):

return a + b

result = add(5, 3)

print(result) # 8

4. Function with Default Parameter


You can give a default value to a parameter.

def greet(name="Student"):

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

greet() # Hello, Student!

greet("Alice") # Hello, Alice!


5. Arbitrary Arguments (*args)
If you don’t know how many arguments a function will receive, use *args.

def add_numbers(*numbers):

total = 0

for num in numbers:

total += num

return total

print(add_numbers(1, 2, 3)) #6

print(add_numbers(5, 10, 15, 20)) # 50

6. Keyword Arguments (**kwargs)


Use (**kwargs) to pass key-value arguments.

def student_info(**info):

print(info)

student_info(name="Alice", age=20, grade="A")

Output:

{'name': 'Alice', 'age': 20, 'grade': 'A'}


8. Scope of Variables
• Local variable → declared inside a function, accessible only inside.

• Global variable → declared outside, accessible anywhere.

x = 10 # global

def my_func():

y = 5 # local

print("Inside:", x, y)

my_func()

print("Outside:", x)

# print(y) -> Error, y is local

Practice Questions
1. Write a function greet() that prints "Hello!".

2. Write a function that adds two numbers and returns the result.

3. Write a function with a default parameter that prints "Hello, <name>!".

4. Write a function that accepts multiple numbers using *args and returns their
sum.

5. Write a function that accepts keyword arguments like name, age, grade and
prints them.

6. Create a lambda function to find the square of a number.

7. Write a function that demonstrates local and global variables.


OOPs in Python (Basics)
OOPs = Object-Oriented Programming System → Organizing code using classes and
objects.

• Provides a clear structure to programs


• Makes code easier to maintain, reuse, and debug
• Helps keep your code DRY (Don't Repeat Yourself)
• Allows you to build reusable applications with less code

1. Class and Object


• A class is like a blueprint (design).
• An object is like a real thing made from the blueprint.

# Class
class Car:
def __init__(self, brand, color):
self.brand = brand # Attribute
self.color = color # Attribute

def drive(self): # Method


print(f"{self.color} {self.brand} is driving ")

# Object
car1 = Car("BMW", "Black")
car2 = Car("Tesla", "White")

car1.drive()
car2.drive()

Output:

Black BMW is driving


White Tesla is driving

2. Four Pillars of OOPs


These are the most important:
(a) Encapsulation → Binding data + methods together
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private variable

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500

(b) Inheritance → Child class gets properties of Parent class


class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal): # Dog inherits Animal


def speak(self):
print("Dog barks ")

dog = Dog()
dog.speak()

Output:

Dog barks

(c) Polymorphism → Same function name, different behavior


class Cat:
def sound(self):
return "Meow "

class Dog:
def sound(self):
return "Woof "

# Polymorphism in action
for animal in [Cat(), Dog()]:
print(animal.sound())

Output:

Meow
Woof

(d) Abstraction → Hiding details, showing only necessary things

(We use abc module → abstract base class)

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

class Circle(Shape):
def __init__(self, r):
self.r = r

def area(self):
return 3.14 * self.r * self.r

circle = Circle(5)
print(circle.area()) # 78.5

Summary (Easiest Way to Remember)


1. Class → Design (blueprint).
2. Object → Real item made from class.
3. Encapsulation → Data hiding.
4. Inheritance → Child takes from parent.
5. Polymorphism → Same name, different work.
6. Abstraction → Hide details, show only what’s needed.

Do you want me to make a small real-life mini project (like Student Management or
ATM System) using OOPs so you can fully understand?

You might also like