0% found this document useful (0 votes)
22 views32 pages

PYTHON ASSIGNMENT - CA-3 - Ayushhmaan

The document provides an extensive overview of Python programming concepts, including tokens, identifiers, escape sequences, mutable and immutable objects, type casting, and more. It covers various data types, control structures, functions, and object-oriented programming features. Additionally, it discusses advantages and disadvantages of Python, debugging techniques, and built-in functions for strings, lists, and dictionaries.
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)
22 views32 pages

PYTHON ASSIGNMENT - CA-3 - Ayushhmaan

The document provides an extensive overview of Python programming concepts, including tokens, identifiers, escape sequences, mutable and immutable objects, type casting, and more. It covers various data types, control structures, functions, and object-oriented programming features. Additionally, it discusses advantages and disadvantages of Python, debugging techniques, and built-in functions for strings, lists, and dictionaries.
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/ 32

PYTHON

ASSIGNMENT - CA-3

012301000005004014
AYUSHHMAAN SINGH THAKUR
1. Token in Python

Tokens are the smallest individual units in a Python program.​


Types of tokens:

●​ Keywords: reserved words (e.g., if, else)​

●​ Identifiers: names of variables, functions, etc.​

●​ Literals: constant values like 10, "Hello"​

●​ Operators: symbols like +, -, *, /​

●​ Punctuators: symbols like (), {}, [], ,, :​

Example:

python

x = 5 # Tokens: x (identifier), = (operator), 5 (literal)

2. Rules of Identifier

Identifiers are names used to identify variables, functions, etc.

Rules:

●​ Must begin with a letter (A–Z, a–z) or underscore (_)​

●​ Followed by letters, digits (0–9), or underscores​

●​ Cannot use keywords (for, while, etc.)​

●​ Case-sensitive (Var ≠ var)​


Example:

python

name = "John"
_age = 25

3. Escape Sequences in Python

Escape sequences allow the insertion of special characters in strings.

Common escape sequences:

●​ \n → newline​

●​ \t → tab​

●​ \\ → backslash​

●​ \" → double quote​

●​ \' → single quote​

Example:

python

print("Hello\nWorld") # Output in two lines


print("She said: \"Hi\"")

4. Mutable and Immutable Objects


●​ Mutable: Can be changed after creation (e.g., lists, dictionaries).​

●​ Immutable: Cannot be changed (e.g., strings, tuples, integers).​

Example:

python

# Mutable
my_list = [1, 2, 3]
my_list[0] = 9 # Allowed

# Immutable
my_str = "hello"
# my_str[0] = 'H' # Error!

5. Type Casting in Python

Type casting is converting one data type to another.

Functions used:

●​ int(), float(), str(), list(), tuple()​

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:

●​ Comments start with # (single line)​

●​ Use triple quotes for multi-line comments​

●​ Help others understand your code​

Example:

python

# This is a single-line comment

"""
This is a
multi-line comment
"""

7. Debugging in Python / Types of Errors

Types of Errors:

●​ SyntaxError: invalid Python code​

●​ IndentationError: wrong indentation​

●​ NameError: undefined variable​

●​ TypeError: wrong type operation​

Example:
python

# SyntaxError
# if x = 5 # incorrect

# NameError
# print(y) # y is not defined

8. Features of Python

●​ Simple and easy syntax​

●​ Interpreted and dynamically typed​

●​ High-level language​

●​ Cross-platform​

●​ Extensive libraries​

●​ Supports OOP and functional programming​

9. Advantages and Disadvantages of Python

Advantages:

●​ Easy to learn​

●​ Rich libraries​

●​ Huge community​
●​ Versatile (web, AI, scripting, etc.)​

Disadvantages:

●​ Slower than compiled languages (like C++)​

●​ Not ideal for mobile development​

●​ High memory usage​

10. Syntax of Print Function

The print() function outputs data to the console.

Syntax:

python

print(object, sep=' ', end='\n', file=sys.stdout)

Examples:

python

print("Hello", "World", sep=", ") # Hello, World


print("Hello", end="!") # Hello!
11. Data Types in Python

Python has several built-in data types.

Main categories:

●​ Numeric: int, float, complex​

●​ Sequence: str, list, tuple​

●​ Set: set, frozenset​

●​ Mapping: dict​

●​ Boolean: bool (True, False)​

●​ None Type: None​

Example:

python

a = 10 # int
b = 3.14 # float
c = "Hello" # str
d = [1, 2, 3] # list
e = {"x": 5} # dict

12. Identify Type, Value, and Location of a Variable

●​ Use type() for data type​

●​ Directly access the value​


●​ Use id() for memory location​

Example:

python

x = 100
print(type(x)) # <class 'int'>
print(x) # 100
print(id(x)) # Memory address (varies)

13. Variable Declaration and Multiple Assignments

●​ No keyword needed; just assign a value​

Assign multiple values to multiple variables:

python

a, b, c = 1, 2, 3

Assign same value to multiple variables:

python

x = y = z = 100

Accessing variables:

python

print(a, b, c) # 1 2 3
print(x, y) # 100 100
14. Operators in Python

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

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

●​ Logical: and, or, not​

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

●​ Assignment: =, +=, -=, etc.​

●​ Membership: in, not in​

●​ Identity: is, is not​

Example:

python

a = 10
b = 3
print(a + b) # 13
print(a // b) # 3 (floor division)
print(a > b) # True

15. Input and Eval Function

input(): Takes user input as a string​


eval(): Evaluates a string as a Python expression
Example:

python

name = input("Enter name: ")


print("Hello", name)

x = eval("5 + 3") # Evaluates to 8


print(x)

16. User-defined Function

Function created by the user using def keyword.

Syntax:

python

def function_name(parameters):
# code block
return value

Example:

python

def greet(name):
return "Hello " + name

print(greet("Ayush"))

17. Decision Statement (Conditional Statements)


Used for decision-making: if, if-else, if-elif-else

Example:

python

x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

18. Looping Statements (Iteration)

●​ for loop: Iterates over a sequence​

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

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

Loop inside another loop.

Example:

python

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

20. Nested If

if statement inside another if

Example:

python

x = 10
if x > 0:
if x % 2 == 0:
print("Positive even")
else:
print("Positive odd")
21. range() Function in Python

The range() function generates a sequence of numbers.

Syntax:

python

range(start, stop, step)

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

●​ stop: end (exclusive)​

●​ step: increment (default is 1)​

Example:

python

for i in range(1, 6):


print(i) # 1 2 3 4 5

22. Jump Statements in Python

Used to control the flow inside loops:

●​ break: exit the loop​

●​ continue: skip the current iteration​

●​ pass: placeholder (does nothing)​

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

23. String: Creation, Declaration, Accessing, Traversing

●​ Strings are created using quotes (', ", or ''').​

●​ Strings are indexed (0-based).​

●​ Traversal is done using loops.​

Example:

python

s = "Python"
print(s[0]) # P

for ch in s:
print(ch)
24. String Operations

●​ Concatenation: +​

●​ Slicing: s[start:end]​

●​ Repetition: *​

●​ Membership: in, not in​

●​ 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

25. Built-in String Functions

Some useful string methods:

●​ lower(), upper()​

●​ strip(), replace()​

●​ find(), index()​
●​ split(), join()​

●​ startswith(), endswith()​

Example:

python

s = " Hello Python "


print(s.strip()) # "Hello Python"
print(s.lower()) # " hello python "
print(s.find("Python")) # 7

26. List: Creation, Declaration, Accessing, Traversing

Lists are ordered, mutable collections.

Example:

python

lst = [1, 2, 3, 4]
print(lst[0]) # 1

for item in lst:


print(item)

27. List Operations

●​ Concatenation: +​

●​ Repetition: *​
●​ Slicing: list[start:end]​

●​ Membership: in, not in​

●​ Append, insert, extend​

Example:

python

lst = [1, 2]
lst.append(3) # [1, 2, 3]
lst.insert(1, 5) # [1, 5, 2, 3]

28. Built-in List Functions

●​ len(), max(), min(), sum()​

●​ 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

●​ del: deletes by index​

●​ remove(): deletes by value​

Example:

python

lst = [1, 2, 3, 4]
del lst[1] # [1, 3, 4]
lst.remove(3) # [1, 4]

30. Dictionary: Creation, Declaration, Accessing, Traversing

Dictionaries store key-value pairs.

Example:

python

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


print(student["name"]) # John

for key in student:


print(key, student[key])
31. Common Dictionary Functions

Useful functions and methods for dictionaries:

●​ len() – number of items​

●​ keys() – returns all keys​

●​ values() – returns all values​

●​ items() – returns key-value pairs​

●​ get() – gets value by key (returns None if key doesn’t exist)​

●​ update() – adds/updates items​

●​ pop() – removes item by key​

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}

32. Nested Dictionary

A dictionary inside another dictionary.

Example:

python
students = {
"John": {"age": 20, "grade": "A"},
"Alice": {"age": 22, "grade": "B"}
}
print(students["John"]["grade"]) # A

33. Update, Insert, Remove from Dictionary

●​ Update/Insert: Use dict[key] = value​

●​ Remove: Use pop() or del​

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

34. Set with Various Operations

Sets are unordered, mutable collections of unique elements.

Operations:

●​ add(), remove(), discard()​

●​ union(), intersection(), difference(), symmetric_difference()​


Example:

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}

35. Tuple with Indexing and Various Operators

Tuples are immutable sequences.

Example:

python

t = (10, 20, 30)


print(t[0]) # 10
print(t + (40,)) # (10, 20, 30, 40)
print(20 in t) # True

36. Functions & Methods of Tuples

Built-in functions:

●​ len(), max(), min(), sum()​

●​ count(), index()​

Example:

python
t = (1, 2, 3, 2)
print(t.count(2)) # 2
print(t.index(3)) # 2

37. Difference Between List and Tuple

Feature List Tuple

Mutabilit Mutable Immutabl


y e

Syntax [1, 2] (1, 2)

Methods Many Fewer

Use case Frequent Fixed


updates data

38. Dynamic Typing in Python

Python allows variables to change types during runtime.

Example:

python

x = 10 # x is int
x = "hello" # x becomes str (valid in Python)
print(type(x)) # <class 'str'>

39. Recursion in Python

A function that calls itself.


Example: Factorial using recursion

python

def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5)) # 120

40. Similarity Between String and List

Feature String List

Indexing Yes Yes

Slicing Yes Yes

Iteration Yes Yes

Concatenatio With + With +


n

Immutability Immutabl Mutabl


e e

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

A module is a file containing Python code (functions, classes, variables).

Ways to import a module:

1.​ import module_name​

2.​ from module_name import function_name​

3.​ import module_name as alias​

Example:

python

import math
print(math.sqrt(16)) # 4.0

from math import pi


print(pi) # 3.14159...

import math as m
print(m.factorial(5)) # 120

42. Features of OOP in Python

Python supports Object-Oriented Programming (OOP) with these features:

●​ Class & Object​

●​ Encapsulation​

●​ Inheritance​
●​ Polymorphism​

●​ Abstraction (indirectly)​

43. Class and Object with Example

●​ A class is a blueprint.​

●​ An object is an instance of a class.​

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

44. Default Constructor in Python

A constructor is a special method __init__() called when the object is created.

A default constructor has no arguments except self.

Example:

python
class Demo:
def __init__(self):
print("Default constructor called")

obj = Demo() # Default constructor called

45. Parameterized Constructor in Python

Constructor that accepts arguments.

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

46. Encapsulation in Python

Encapsulation = wrapping data + methods into one unit (class).​


Python uses _ (protected) and __ (private) to control access.

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)

47. What is Inheritance in Python

Inheritance allows one class (child) to inherit properties/methods from another (parent).

Types: Single, Multiple, Multilevel, Hierarchical, Hybrid.

48. Single Inheritance

Purpose: Reuse code from one parent class.

Syntax & Example:

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

Purpose: Inherit from more than one parent class.

Example:

python

class A:
def m1(self):
print("Class A")

class B:
def m2(self):
print("Class B")

class C(A, B):


pass

obj = C()
obj.m1() # Class A
obj.m2() # Class B

50. Multilevel Inheritance

Purpose: Inherit from a class which itself inherits another class.

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).

Example: Overloading + operator

python

class Point:
def __init__(self, x):
self.x = x

def __add__(self, other):


return Point(self.x + other.x)

def __str__(self):
return str(self.x)

p1 = Point(10)
p2 = Point(20)
p3 = p1 + p2 # Calls p1.__add__(p2)
print(p3) # 30

Common Magic Methods:

●​ __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:

Example: Method Overriding (Runtime Polymorphism)

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).

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy