PYTHON ASSIGNMENT - CA-3 - Ayushhmaan
PYTHON ASSIGNMENT - CA-3 - Ayushhmaan
ASSIGNMENT - CA-3
012301000005004014
AYUSHHMAAN SINGH THAKUR
1. Token in Python
Example:
python
2. Rules of Identifier
Rules:
python
name = "John"
_age = 25
● \n → newline
● \t → tab
● \\ → backslash
Example:
python
Example:
python
# Mutable
my_list = [1, 2, 3]
my_list[0] = 9 # Allowed
# Immutable
my_str = "hello"
# my_str[0] = 'H' # Error!
Functions used:
Example:
python
a = "123"
b = int(a) # b becomes 123 (integer)
print(type(b)) # <class 'int'>
6. Rules and Convention for Writing Python Program Comments
Rules:
Example:
python
"""
This is a
multi-line comment
"""
Types of Errors:
Example:
python
# SyntaxError
# if x = 5 # incorrect
# NameError
# print(y) # y is not defined
8. Features of Python
● High-level language
● Cross-platform
● Extensive libraries
Advantages:
● Easy to learn
● Rich libraries
● Huge community
● Versatile (web, AI, scripting, etc.)
Disadvantages:
Syntax:
python
Examples:
python
Main categories:
● Mapping: dict
Example:
python
a = 10 # int
b = 3.14 # float
c = "Hello" # str
d = [1, 2, 3] # list
e = {"x": 5} # dict
Example:
python
x = 100
print(type(x)) # <class 'int'>
print(x) # 100
print(id(x)) # Memory address (varies)
python
a, b, c = 1, 2, 3
python
x = y = z = 100
Accessing variables:
python
print(a, b, c) # 1 2 3
print(x, y) # 100 100
14. Operators in Python
Example:
python
a = 10
b = 3
print(a + b) # 13
print(a // b) # 3 (floor division)
print(a > b) # True
python
Syntax:
python
def function_name(parameters):
# code block
return value
Example:
python
def greet(name):
return "Hello " + name
print(greet("Ayush"))
Example:
python
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Example:
python
# for loop
for i in range(5):
print(i)
# while loop
x = 0
while x < 5:
print(x)
x += 1
19. Nested Loops
Example:
python
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
20. Nested If
Example:
python
x = 10
if x > 0:
if x % 2 == 0:
print("Positive even")
else:
print("Positive odd")
21. range() Function in Python
Syntax:
python
Example:
python
Example:
python
for i in range(5):
if i == 3:
break
print(i) # 0 1 2
python
for i in range(5):
if i == 2:
continue
print(i) # 0 1 3 4
Example:
python
s = "Python"
print(s[0]) # P
for ch in s:
print(ch)
24. String Operations
● Concatenation: +
● Slicing: s[start:end]
● Repetition: *
● Reverse: s[::-1]
Example:
python
s = "Hello"
print(s + " World") # Hello World
print(s[1:4]) # ell
print(s * 2) # HelloHello
print('e' in s) # True
print(s[::-1]) # olleH
● lower(), upper()
● strip(), replace()
● find(), index()
● split(), join()
● startswith(), endswith()
Example:
python
Example:
python
lst = [1, 2, 3, 4]
print(lst[0]) # 1
● Concatenation: +
● Repetition: *
● Slicing: list[start:end]
Example:
python
lst = [1, 2]
lst.append(3) # [1, 2, 3]
lst.insert(1, 5) # [1, 5, 2, 3]
● sort(), reverse()
● count(), index()
Example:
python
nums = [4, 1, 3]
print(len(nums)) # 3
nums.sort()
print(nums) # [1, 3, 4]
29. Delete Elements from List
Example:
python
lst = [1, 2, 3, 4]
del lst[1] # [1, 3, 4]
lst.remove(3) # [1, 4]
Example:
python
Example:
python
d = {"a": 1, "b": 2}
print(d.keys()) # dict_keys(['a', 'b'])
print(d.get("a")) # 1
d.update({"c": 3}) # {'a': 1, 'b': 2, 'c': 3}
d.pop("b") # {'a': 1, 'c': 3}
Example:
python
students = {
"John": {"age": 20, "grade": "A"},
"Alice": {"age": 22, "grade": "B"}
}
print(students["John"]["grade"]) # A
Example:
python
d = {"x": 1}
d["y"] = 2 # Insert
d["x"] = 100 # Update
del d["y"] # Remove using del
d.pop("x") # Remove using pop
Operations:
python
s1 = {1, 2, 3}
s2 = {3, 4}
print(s1.union(s2)) # {1, 2, 3, 4}
print(s1 & s2) # {3}
s1.add(5) # {1, 2, 3, 5}
Example:
python
Built-in functions:
● count(), index()
Example:
python
t = (1, 2, 3, 2)
print(t.count(2)) # 2
print(t.index(3)) # 2
Example:
python
x = 10 # x is int
x = "hello" # x becomes str (valid in Python)
print(type(x)) # <class 'str'>
python
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Example:
python
s = "abc"
l = ['a', 'b', 'c']
print(s[1], l[1]) # b b
print(s[:2], l[:2]) # ab ['a', 'b']
41. What is a Module in Python? Ways to Import
Example:
python
import math
print(math.sqrt(16)) # 4.0
import math as m
print(m.factorial(5)) # 120
● Encapsulation
● Inheritance
● Polymorphism
● Abstraction (indirectly)
● A class is a blueprint.
Example:
python
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
s1 = Student("Ayush")
s1.greet() # Hello Ayush
Example:
python
class Demo:
def __init__(self):
print("Default constructor called")
Example:
python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Riya", 22)
print(p.name, p.age) # Riya 22
Example:
python
class Car:
def __init__(self):
self.__engine = "Petrol"
def show(self):
print("Engine:", self.__engine)
c = Car()
c.show()
# print(c.__engine) # Error (private)
Inheritance allows one class (child) to inherit properties/methods from another (parent).
python
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
def display(self):
print("Child class")
c = Child()
c.show() # Parent class
c.display() # Child class
49. Multiple Inheritance
Example:
python
class A:
def m1(self):
print("Class A")
class B:
def m2(self):
print("Class B")
obj = C()
obj.m1() # Class A
obj.m2() # Class B
Example:
python
class A:
def a(self):
print("A")
class B(A):
def b(self):
print("B")
class C(B):
def c(self):
print("C")
obj = C()
obj.a() # A
obj.b() # B
obj.c() # C
51. Operator Overloading in Python
Operator Overloading allows you to define how operators like +, -, * behave for
user-defined objects (classes).
python
class Point:
def __init__(self, x):
self.x = x
def __str__(self):
return str(self.x)
p1 = Point(10)
p2 = Point(20)
p3 = p1 + p2 # Calls p1.__add__(p2)
print(p3) # 30
● __add__ → +
● __sub__ → -
● __mul__ → *
● __eq__ → ==
● __lt__ → <
52. Operator Overriding in Python
Operator Overriding is not an official Python term like overloading. However, it usually
refers to method overriding in inheritance (especially when operator-related methods are
redefined).
In context of inheritance:
python
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self): # Overrides Animal's method
print("Dog barks")
a = Dog()
a.sound() # Dog barks (overridden method called)
Key Point: Operator overriding is essentially method overriding when those methods define
operator behavior (like redefining __add__ or __eq__ in a subclass).