0% found this document useful (0 votes)
1 views36 pages

03_python

The document provides a comprehensive overview of Python programming concepts, including tokens, identifiers, escape sequences, mutability, type casting, comments, debugging, features, advantages and disadvantages, print function syntax, data types, variable handling, operators, input and eval functions, user-defined functions, decision statements, looping statements, nested loops, range function, jump statements, string creation and operations. Each concept is explained with definitions, rules, examples, and code snippets. It serves as a foundational guide for understanding Python programming.

Uploaded by

Aarya Javia
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)
1 views36 pages

03_python

The document provides a comprehensive overview of Python programming concepts, including tokens, identifiers, escape sequences, mutability, type casting, comments, debugging, features, advantages and disadvantages, print function syntax, data types, variable handling, operators, input and eval functions, user-defined functions, decision statements, looping statements, nested loops, range function, jump statements, string creation and operations. Each concept is explained with definitions, rules, examples, and code snippets. It serves as a foundational guide for understanding Python programming.

Uploaded by

Aarya Javia
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/ 36

1.

Explain Token in Python

In Python, a token is the smallest unit of code that has meaning. Think of it like a word in
English – every line of Python is made of these tokens. Python has five main types of tokens:

1.​ Keywords: Reserved words used by Python. You cannot use them as variable names.
Examples include if, else, while, import, def, etc.​

2.​ Identifiers: Names used for variables, functions, classes. They must follow specific rules.​

3.​ Literals: Constant values such as numbers, strings, or boolean values (like "hello", 123,
True).​

4.​ Operators: Symbols that perform operations. For example: +, -, *, /, =, ==, etc.​

5.​ Punctuators (Delimiters): Symbols used to structure code, such as (), {}, []

# Token examples:

x = 10 # 'x' is identifier, '=' is operator, '10' is literal

if x > 5: # 'if' is keyword, '>' is operator, ':' is punctuator

print("Yes") # 'print' is identifier, '("Yes")' includes literal & delimiters

2. What are Rules of Identifier

An identifier is the name given to entities like variables, functions, classes, etc. Python has
specific rules for naming identifiers:

1.​ An identifier can consist of letters (A-Z, a-z), digits (0-9), and underscores (_).​

2.​ It must not start with a digit.​

3.​ It cannot use special symbols like @, $, %, etc.​

4.​ Identifiers are case-sensitive (e.g., Name and name are different).​

5.​ You cannot use Python keywords as identifiers (like for, if, class).

# Valid identifiers

my_var = 5

_name = "Alex"
value123 = 100

# Invalid identifiers (will cause error)

1name = "John" # starts with number

my-name = "Jane" # hyphen not allowed

class = 10 # 'class' is a keyword

3. Explain Escape Sequence Supported in Python

Escape sequences are special characters used in strings to represent actions like newlines, tabs, or
including quotes. They're introduced with a backslash (\).

Escape Code Description

\n Newline

\t Tab (horizontal space)

\\ Backslash

\' Single quote

\" Double quote

\r Carriage return

\b Backspace

These sequences help manage special formatting in string output.


print("Hello\nWorld") # Newline

print("Name:\tJohn") # Tab

print("She said: \"Hi\"") # Double quote inside string

print('It\'s Python!') # Single quote inside string

4. Explain Mutable and Immutable Concept in Python

In Python, mutability refers to whether an object can be changed after it’s created.

●​ Mutable objects can be modified. Examples include: list, set, dict.​

●​ Immutable objects cannot be changed. Examples include: int, float, str, tuple.​

If you try to modify an immutable object, Python creates a new object instead of changing the
original.

# Mutable example

my_list = [1, 2, 3]

my_list[0] = 10 # Changes list element

print(my_list) # Output: [10, 2, 3]

# Immutable example

name = "Alice"

# name[0] = "M" # Error: strings are immutable

name = "Mlice" # New string object created

print(name) # Output: Mlice

5. Explain Type Casting in Python

Type casting is the process of converting data from one type to another. There are two types:
1.​ Implicit Type Casting – Done automatically by Python, where it promotes values (like int
to float).​

2.​ Explicit Type Casting – Done manually using functions like int(), float(), str(), etc.​

Common casting operations:

●​ int("10") → converts string "10" to integer 10​

●​ float(5) → converts int 5 to float 5.0​

●​ str(100) → converts int 100 to string "100"

# Implicit casting

a=5

b = 2.0

c=a+b # int + float = float

print(c) # Output: 7.0

# Explicit casting

x = "123"

y = int(x) # Convert string to int

print(y + 1) # Output: 124

z = 45

print(str(z) + " is now a string") # Output: 45 is now a string

6. Rules and Conventions for Writing Python Program Comments

Types of Comments

1.​ Single-line comments​


○​ Start with # and a space.​

○​ Used for short explanations.​

2.​ Inline comments​

○​ On the same line as code, separated by at least two spaces.​

○​ Use only when needed.​

3.​ Block comments​

○​ Multiple lines explaining a code section.​

○​ Each line starts with #.​

4.​ Docstrings​

○​ Use triple quotes (""") to describe modules, functions, or classes.​

○​ First line is a short summary.

7. Explain Debugging in Python or Types of Errors in Python

Debugging is the process of finding and fixing errors in a Python program. Python provides tools
like tracebacks, debugging libraries (e.g., pdb), and IDEs to help.

🔹 Types of Errors:
1.​ Syntax Errors:​

○​ Occur due to incorrect syntax.​

○​ Prevent the code from running.​

○​ Example: Missing : in if statement.​

2.​ Runtime Errors:​

○​ Happen during program execution.​

○​ Example: Division by zero, file not found.​


3.​ Logical Errors:​

○​ The program runs but produces incorrect results.​

○​ Caused by mistakes in logic (like wrong formula).​

4.​ Semantic Errors:​

○​ Misuse of functions or incorrect assumptions.​

○​ Not always caught by the interpreter.​

🔹 Debugging Tools:
●​ print() statements (basic debugging)​

●​ pdb module (import pdb; pdb.set_trace())​

●​ IDE debuggers (like in PyCharm or VS Code)

# Syntax Error Example:

# if x > 10 # Missing colon - this will cause syntax error

# Runtime Error Example:

try:

result = 10 / 0

except ZeroDivisionError as e:

print("Error:", e)

# Logical Error Example:

def add(a, b):

return a - b # Logic error: should be a + b

print("Result:", add(5, 3)) # Incorrect result due to logic


8. Explain Features of Python

Python is a powerful, flexible, and beginner-friendly language. Here are some of its key features:

1.​ Simple and Easy to Learn: Clear syntax similar to English.​

2.​ Interpreted Language: Executes code line by line; no need for compilation.​

3.​ Dynamically Typed: No need to declare variable types.​

4.​ High-Level Language: Abstracts away low-level details.​

5.​ Platform Independent: Code runs on any OS with Python installed.​

6.​ Extensive Standard Library: Includes modules for math, files, web, etc.​

7.​ Object-Oriented: Supports classes and objects.​

8.​ Large Community & Open Source: Strong ecosystem and community support.

# Demonstrating Python features

message = "Python is easy" # Simple syntax and dynamic typing

print(message) # Interpreted line-by-line

def greet(name): # Function shows high-level structure

return f"Hello, {name}!"

print(greet("Alice"))

9. Explain Advantages and Disadvantages of Python

🔹 Advantages:
1.​ Easy to Learn and Use – Friendly syntax, perfect for beginners.​

2.​ Readable Code – Follows clean code principles.​


3.​ Extensive Libraries – Supports tasks like data analysis, web dev, ML, etc.​

4.​ Cross-platform Support – Write once, run anywhere.​

5.​ Active Community – Help and packages for every use case.​

6.​ Integration – Easily integrates with C/C++, Java, or .NET.​

🔹 Disadvantages:
1.​ Slower than Compiled Languages – Due to being interpreted.​

2.​ Not Great for Mobile Apps – Less support for mobile development.​

3.​ High Memory Usage – May be unsuitable for memory-constrained apps.​

4.​ Runtime Errors – Dynamic typing can lead to unexpected bugs.

10. Explain Syntax of Print Function in Python

The print() function in Python is used to display output on the screen. It supports several
parameters:

print(object1, object2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Parameters:

●​ object: One or more expressions to print.​

●​ sep: Separator between objects (default is space).​

●​ end: String appended after the last object (default is newline).​

●​ file: Where to output (default is screen).​

●​ flush: If True, flush the output buffer.​

🔹 String Formatting:
●​ f-strings: f"Hello {name}"​

●​ format(): "Hello {}".format(name)


# Basic usage

print("Hello", "World") # Output: Hello World

# Using sep and end

print("A", "B", "C", sep="-", end="***") # Output: A-B-C***

# f-string formatting

name = "Alice"

print(f"Welcome, {name}!") # Output: Welcome, Alice!

# format() method

age = 25

print("Age is {}".format(age)) # Output: Age is 25

11. Explain Datatypes of Python

Python has built-in datatypes used to store various kinds of data. These are:

●​ int: Integer numbers without decimals. Example: 5​

●​ float: Numbers with decimal points. Example: 3.14​

●​ str: Sequence of Unicode characters. Example: "hello"​

●​ bool: Boolean values, either True or False​

●​ list: Ordered, mutable collection. Example: [1, 2, 3]​

●​ tuple: Ordered, immutable collection. Example: (1, 2, 3)​

●​ set: Unordered collection of unique elements. Example: {1, 2, 3}​

●​ dict: Unordered collection of key-value pairs. Example: {"name": "Alice"}


a = 10 # int
b = 3.14 # float
c = "Hello" # str
d = True # bool
e = [1, 2, 3] # list
f = (4, 5, 6) # tuple
g = {1, 2, 3} # set
h = {"a": 1} # dict

12. Explain How to Identify Type, Value and Location of a Variable

●​ type(var) gives the data type.​

●​ id(var) gives the memory location (object ID).​

●​ The value is the variable itself.

x = 42
print("Type:", type(x)) # <class 'int'>
print("Value:", x) # 42
print("Location:", id(x)) # Memory address

13. How to Declare and Access Variables; Assign Multiple or Same Values

In Python, variables are declared simply by assigning a value.​


To access, just use the variable name.​
You can:

●​ Assign different values to multiple variables at once.​

●​ Assign the same value to multiple variables at once.

# Declaration and access


name = "Alice"
print(name)

# Assign multiple values


a, b, c = 1, 2, 3
print(a, b, c)

# Assign same value


x = y = z = 100
print(x, y, z)
14. Explain All Operators in Python

Categories of Operators:

●​ Arithmetic: + - * / % // **​

●​ Comparison: == != > < >= <=​

●​ Logical: and or not​

●​ Assignment: = += -= *= /=​

●​ Bitwise: & | ^ ~ << >>​

●​ Membership: in, not in​

●​ Identity: is, is not

a=5
b=2

# Arithmetic
print(a + b, a - b, a * b, a / b, a % b, a ** b, a // b)

# Comparison
print(a > b, a == b)

# Logical
print(a > 1 and b < 3)

# Assignment
a += 1
print(a)

# Membership
print(2 in [1, 2, 3])

# Identity
x = y = 10
print(x is y)

15. Input Function and Eval Function

●​ input(): Takes user input as a string.​


●​ eval(): Evaluates a string as Python code. Useful but dangerous if used with untrusted
input.

expr = "3 + 4"


print("Evaluated result of expression:", eval(expr))

16. User-Defined Function in Python

A user-defined function is created using the def keyword. It allows you to organize code into
reusable blocks. Functions can have parameters and return values.

def square(num):
return num * num

result = square(5)
print("Square is:", result)

17. Explain Decision statement in Python (Selection Conditional)

Used to execute code based on a condition:

●​ if: Single condition​

●​ if-else: Two conditions​

●​ if-elif-else: Multiple conditions

marks = 85

if marks >= 90:


print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")

18. Explain looping statement in Python (Iteration)

Used for repeating actions:


●​ for loop: Iterates over a sequence​

●​ while loop: Repeats as long as condition is true

# For loop
for i in range(3):
print("For loop:", i)

# While loop
count = 0
while count < 3:
print("While loop:", count)
count += 1

19. Explain Nested Loops.

A loop inside another loop. Useful for working with tables, grids, or combinations.

for i in range(2):
for j in range(3):
print(f"i={i}, j={j}")

20. Explain Nested If.

An if condition inside another if. Allows multiple levels of condition checking.

x = 20

if x > 10:
if x < 30:
print("x is between 10 and 30")
else:
print("x is 30 or more")
else:
print("x is 10 or less")

21. Explain range() Function in Python

The range() function generates a sequence of numbers. It is commonly used in loops.

Syntax:

range(start, stop, step)


●​ start: (optional) starting number (default is 0)​

●​ stop: required end value (not included)​

●​ step: (optional) increment (default is 1)

# range(stop)
for i in range(5):
print(i) # 0 to 4

# range(start, stop)
for i in range(2, 6):
print(i) # 2 to 5

# range(start, stop, step)


for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9

22. Explain Jump Statements in Python

Jump statements are used to change the normal flow of a program:

●​ break: Exits the loop immediately.​

●​ continue: Skips the current iteration.​

●​ pass: Does nothing, acts as a placeholder.

# break
for i in range(5):
if i == 3:
break
print(i)

# continue
for i in range(5):
if i == 3:
continue
print(i)

# pass
for i in range(5):
if i == 3:
pass # Placeholder
print(i)
23. Creation, Declaration, Accessing, Traversing String in Python

●​ Create: Assign text using quotes.​

●​ Access: Use indexing s[0]​

●​ Traverse: Use loops

s = "Python" # Declaration and creation


print(s[0]) # Accessing
for char in s: # Traversing
print(char)

24. Various String Operations

●​ Concatenation: Joining strings using +​

●​ Slicing: Extract part of a string using [start:end]​

●​ Repetition: Repeat string using *​

●​ Membership: Check using in​

●​ Reverse: Use slicing with step -1

s = "Hello"
print(s + " World") # Concatenation
print(s[1:4]) # Slicing: 'ell'
print(s * 2) # Repetition: 'HelloHello'
print('e' in s) # Membership: True
print(s[::-1]) # Reverse: 'olleH'

25. Built-in Functions in String

Common string methods:

●​ len(s): Length​

●​ lower(), upper(): Case conversion​

●​ strip(): Removes whitespace​


●​ replace(): Replaces text​

●​ find(): Finds substring index​

●​ split(): Splits string

s = " Hello Python "


print(len(s))
print(s.lower())
print(s.upper())
print(s.strip())
print(s.replace("Python", "World"))
print(s.find("Python"))
print(s.split())

26. Creation, Declaration, Accessing, Traversing List in Python

●​ Create: Use square brackets []​

●​ Access: Use index​

●​ Traverse: Use loops

lst = [10, 20, 30]


print(lst[0]) # Access
for item in lst: # Traverse
print(item)

27. Various Operations on List

●​ Append: append()​

●​ Insert: insert()​

●​ Extend: extend()​

●​ Indexing/Slicing: list[i], list[start:end]​

●​ Concatenate: +​

●​ Repeat: *

lst = [1, 2, 3]
lst.append(4)
lst.insert(1, 10)
lst.extend([5, 6])
print(lst)
print(lst[1:4]) # Slicing
print(lst + [7, 8]) # Concatenation
print(lst * 2) # Repetition

28. Built-in Functions in List

●​ len(): Length​

●​ max(), min(): Largest/smallest​

●​ sum(): Total​

●​ sorted(): Sorted version​

●​ list(): Convert iterable to list​

nums = [3, 1, 4, 2]

print(len(nums))

print(max(nums))

print(min(nums))

print(sum(nums))

print(sorted(nums))

29. How to Delete Elements from List (del, remove)

●​ del: Removes by index​

●​ remove(): Removes by value

lst = [1, 2, 3, 4, 2]

del lst[1] # Removes item at index 1

lst.remove(2) # Removes first occurrence of value 2

print(lst)
30. Creation, Declaration, Accessing, Traversing Dictionary

A dictionary stores data in key-value pairs.

●​ Create: Use {key: value}​

●​ Access: Use dict[key]​

●​ Traverse: Use loop

person = {"name": "Alice", "age": 25}

print(person["name"]) # Access

for key in person: # Traverse keys

print(key, ":", person[key])

31. Explain Common Dictionary Functions

Dictionaries in Python have various built-in functions for manipulation:

●​ dict.get(key): Returns the value for the key, or None if the key doesn't exist.​

●​ dict.keys(): Returns a list of all keys in the dictionary.​

●​ dict.values(): Returns a list of all values in the dictionary.​

●​ dict.items(): Returns a list of tuples with each key-value pair.​

●​ dict.pop(key): Removes the item with the specified key and returns the value.​

●​ dict.update(): Adds or updates items in the dictionary.​

person = {"name": "Alice", "age": 25}

# get

print(person.get("name")) # Alice
# keys, values, items

print(person.keys()) # dict_keys(['name', 'age'])

print(person.values()) # dict_values(['Alice', 25])

print(person.items()) # dict_items([('name', 'Alice'), ('age', 25)])

# pop

age = person.pop("age")

print(age) # 25

print(person)

# update

person.update({"age": 30})

print(person)

32. Explain Nested Dictionary

A nested dictionary is a dictionary inside another dictionary. It allows more complex data
structures.

students = {

"student1": {"name": "Alice", "age": 20},

"student2": {"name": "Bob", "age": 22}

# Accessing values in a nested dictionary

print(students["student1"]["name"]) # Alice

print(students["student2"]["age"]) # 22
33. How to Update, Insert, and Remove an Element from Dictionary

●​ Insert: Use dict[key] = value.​

●​ Update: Use dict.update() to modify existing key-value pairs.​

●​ Remove: Use del or dict.pop().

# Creating dictionary

person = {"name": "Alice", "age": 25}

# Insert new element

person["address"] = "New York"

# Update an existing element

person["age"] = 26

# Remove element using del

del person["address"]

# Remove element using pop

age = person.pop("age")

print(person) # {"name": "Alice"}

print(age) # 26

34. Explain Set with Various Operations

A set is an unordered collection of unique elements.


Operations:

●​ Add: set.add()​

●​ Remove: set.remove(), set.discard()​

●​ Union: set1 | set2​

●​ Intersection: set1 & set2​

●​ Difference: set1 - set2​

●​ Subset: set1 <= set2​

●​ Superset: set1 >= set2

s = {1, 2, 3}

s.add(4) # Add element

s.remove(2) # Remove element

s.discard(5) # No error if element does not exist

print(s)

s2 = {3, 4, 5}

print(s | s2) # Union

print(s & s2) # Intersection

print(s - s2) # Difference

print(s <= s2) # Subset

35. Explain Tuple with Indexing and Various Operators

A tuple is an immutable sequence of items, similar to a list but unchangeable after creation. You
can access elements using indexing and perform various operations like concatenation and
repetition.
Operations:

●​ Indexing: tuple[index]​

●​ Concatenation: tuple1 + tuple2​

●​ Repetition: tuple * n

t = (1, 2, 3, 4)

# Indexing

print(t[0]) # 1

print(t[-1]) # 4

# Concatenation

t2 = (5, 6)

t3 = t + t2

print(t3) # (1, 2, 3, 4, 5, 6)

# Repetition

t4 = t * 2

print(t4) # (1, 2, 3, 4, 1, 2, 3, 4)

36. Various Functions & Methods of Tuples in Python

Tuples have a few built-in methods:

●​ count(): Counts occurrences of an element.​

●​ index(): Returns the first index of an element.


t = (1, 2, 3, 1, 2)

# count

print(t.count(1)) # 2

# index

print(t.index(2)) # 1

37. Difference Between List and Tuple

●​ Mutability: Lists are mutable (can be changed), whereas tuples are immutable (cannot be
changed after creation).​

●​ Syntax: Lists use [], while tuples use ().​

●​ Performance: Tuples are generally faster for iteration due to immutability.

lst = [1, 2, 3] # List

t = (1, 2, 3) # Tuple

# Modifying list

lst[0] = 10

# Modifying tuple will raise an error

# t[0] = 10

38. What is Dynamic Typing in Python? Explain with Example

Dynamic typing means that variables in Python do not have a fixed type. The type of the variable
is determined at runtime.

x = 10 # x is an integer

x = "Hello" # Now x is a string

x = [1, 2, 3] # Now x is a list

print(x)
39. Explain Recursion in Python with Example

Recursion is a process in which a function calls itself. It’s useful for problems that can be broken
down into smaller sub-problems.

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

print(factorial(5)) # 120

40. Explain Similarity Between String and List

●​ Both strings and lists are ordered collections.​

●​ Both can be indexed and sliced.​

●​ Both support iteration and have similar operations such as len(), in, etc.

s = "hello"

lst = [1, 2, 3, 4]

# Indexing

print(s[1]) # 'e'

print(lst[1]) # 2

# Slicing

print(s[1:4]) # 'ell'
print(lst[1:4]) # [2, 3, 4]

# Length

print(len(s)) # 5

print(len(lst)) # 4

41. What is Module in Python? Explain Various Ways to Import Module

A module in Python is a file containing Python definitions and statements. The file name is the
module name with the suffix .py. Modules allow us to organize and reuse code.

Ways to Import a Module:

1.​ import module_name​

2.​ from module_name import function_name​

3.​ from module_name import * (imports all functions)​

4.​ import module_name as alias

# Importing the entire module

import math

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

# Importing specific functions

from math import sqrt

print(sqrt(16)) # Output: 4.0

# Importing all functions

from math import *

print(sin(30)) # Output: 0.49999999999999994


# Using alias for module

import math as m

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

42. Explain Various Features of OOP in Python

Object-Oriented Programming (OOP) features:

1.​ Encapsulation: Bundling data and methods that operate on data within one unit (class).​

2.​ Abstraction: Hiding complexity and showing only essential features.​

3.​ Inheritance: Ability of a class to derive properties and methods from another class.​

4.​ Polymorphism: Ability to take many forms, e.g., method overloading, operator
overloading.

43. What is Class and Object? Explain It with Suitable Example

●​ Class: A blueprint for creating objects (instances).​

●​ Object: An instance of a class containing attributes (data) and methods (functions).

class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

return f"{self.name} barks!"

# Creating object of Dog class

dog1 = Dog("Buddy", 3)
print(dog1.name) # Buddy

print(dog1.bark()) # Buddy barks!

44. Explain Default Constructor in Python with Suitable Example

A default constructor is a constructor that doesn’t take any arguments (except self). It is called
when an object is created without passing any arguments.

class Car:

def __init__(self):

self.model = "Toyota"

self.year = 2021

def display(self):

print(f"Model: {self.model}, Year: {self.year}")

# Creating object without arguments

car1 = Car()

car1.display() # Model: Toyota, Year: 2021

45. Explain Parameterized Constructor in Python with Suitable Example

A parameterized constructor allows passing parameters during object creation to initialize the
object with specific values.

class Car:

def __init__(self, model, year):

self.model = model

self.year = year
def display(self):

print(f"Model: {self.model}, Year: {self.year}")

# Creating object with arguments

car1 = Car("Honda", 2022)

car1.display() # Model: Honda, Year: 2022

46. What is Encapsulation? How Python Provides Its Functionality? Explain It with
Suitable Example

Encapsulation is the bundling of data and methods that operate on that data within a single unit
(class). It helps restrict direct access to some of the object’s components and prevents unintended
modification.

In Python, encapsulation is done using private attributes (prefix _ or __) and using getter and
setter methods to access private variables.

class Employee:

def __init__(self, name, salary):

self.name = name

self.__salary = salary # private variable

def get_salary(self):

return self.__salary

def set_salary(self, salary):

if salary > 0:

self.__salary = salary

else:

print("Salary can't be negative!")


# Object creation

emp = Employee("John", 50000)

print(emp.get_salary()) # 50000

emp.set_salary(55000)

print(emp.get_salary()) # 55000

47. What is Inheritance in Python?

Inheritance allows one class (child class) to inherit attributes and methods from another class
(parent class). It promotes code reusability and establishes a relationship between classes.

48. Explain Single Inheritance with Its Purpose, Syntax, Suitable Example, and Output

Single inheritance involves one parent class and one child class. The child class inherits all
attributes and methods from the parent class.

class Animal:

def speak(self):

print("Animal makes a sound")

class Dog(Animal):

def bark(self):

print("Dog barks")

# Creating object of Dog class

dog1 = Dog()

dog1.speak() # Animal makes a sound

dog1.bark() # Dog barks


49. Explain Multiple Inheritance with Its Purpose, Syntax, Suitable Example, and Output

Multiple inheritance allows a class to inherit from more than one parent class. It allows
combining functionalities from multiple classes.

class Animal:

def speak(self):

print("Animal makes a sound")

class Pet:

def play(self):

print("Pet plays")

class Dog(Animal, Pet):

def bark(self):

print("Dog barks")

# Creating object of Dog class

dog1 = Dog()

dog1.speak() # Animal makes a sound

dog1.play() # Pet plays

dog1.bark() # Dog barks

50. Explain Multilevel Inheritance with Its Purpose, Syntax, Suitable Example, and Output

Multilevel inheritance involves a chain of inheritance where a class inherits from a parent class,
and another class inherits from the child class.

class Animal:
def speak(self):

print("Animal makes a sound")

class Dog(Animal):

def bark(self):

print("Dog barks")

class Puppy(Dog):

def whine(self):

print("Puppy whines")

# Creating object of Puppy class

puppy1 = Puppy()

puppy1.speak() # Animal makes a sound

puppy1.bark() # Dog barks

puppy1.whine() # Puppy whines

51. Explain Hierarchical Inheritance with Its Purpose, Syntax, Suitable Example, and
Output

Hierarchical inheritance is when multiple classes inherit from the same parent class.

class Animal:

def speak(self):

print("Animal makes a sound")

class Dog(Animal):
def bark(self):

print("Dog barks")

class Cat(Animal):

def meow(self):

print("Cat meows")

# Creating objects of Dog and Cat

dog1 = Dog()

cat1 = Cat()

dog1.speak() # Animal makes a sound

dog1.bark() # Dog barks

cat1.speak() # Animal makes a sound

cat1.meow() # Cat meows

52. Explain Hybrid Inheritance with Its Purpose, Syntax, Suitable Example, and Output

Hybrid inheritance is a combination of multiple types of inheritance, such as single, multiple,


and multilevel inheritance.

class Animal:

def speak(self):

print("Animal makes a sound")

class Pet:

def play(self):
print("Pet plays")

class Dog(Animal, Pet):

def bark(self):

print("Dog barks")

class Puppy(Dog):

def whine(self):

print("Puppy whines")

# Creating object of Puppy class

puppy1 = Puppy()

puppy1.speak() # Animal makes a sound

puppy1.play() # Pet plays

puppy1.bark() # Dog barks

puppy1.whine() # Puppy whines

53. Explain Compile time polymorphism or static polymorphism with suitable examples.

Compile-time polymorphism (also known as method overloading in other languages) refers to


method overloading, but Python doesn’t directly support this. It can be emulated by defining
default parameters.

class Printer:

def print_msg(self, msg="Default message"):

print(msg)

printer = Printer()
printer.print_msg() # Default message

printer.print_msg("Hello, World!") # Hello, World!

54. Explain Run time polymorphism or dynamic polymorphism with suitable example.

Runtime polymorphism refers to method overriding where the method of the child class
overrides the parent class method at runtime.

class Animal:

def speak(self):

print("Animal makes a sound")

class Dog(Animal):

def speak(self):

print("Dog barks")

# Creating object of Dog class

dog1 = Dog()

dog1.speak() # Dog barks (runtime polymorphism)

55. Explain how python support Operator overloading. Explain it with suitable example.

Python allows us to define the behavior of operators for user-defined classes by using special
methods (magic methods).

class Complex:

def __init__(self, real, imag):

self.real = real

self.imag = imag
def __add__(self, other):

return Complex(self.real + other.real, self.imag + other.imag)

def __str__(self):

return f"{self.real} + {self.imag}i"

# Adding complex numbers

c1 = Complex(3, 4)

c2 = Complex(1, 2)

result = c1 + c2

print(result) # 4 + 6i

56. Operator Overriding

Operator overriding allows us to change the behavior of standard operators when applied to
objects.

class Rectangle:

def __init__(self, width, height):

self.width = width

self.height = height

def __eq__(self, other):

return self.width * self.height == other.width * other.height

# Creating objects
rect1 = Rectangle(5, 10)

rect2 = Rectangle(5, 10)

print(rect1 == rect2) # True (Operator overriding)

You might also like