Python Notes 1
Python Notes 1
1. What is an Algorithm?
An algorithm is a step-by-step procedure or a finite set of instructions to solve a problem or perform
a computation. It is a logical approach for achieving a specific goal in a defined manner.
2. What is a tuple?
A tuple is an immutable, ordered collection of elements in Python. It is defined by placing elements
inside parentheses ( ), separated by commas. Example:
_
my_tuple = (1, 2, 3)
str.format():
print("My name is {} and I am {} years old.".format(name, age))
Percent formatting:
print("My name is %s and I am %d years old." % (name, age))
10. Need for continue and break statements (Prime number check).
break: Terminates the loop.
continue: Skips the current iteration.
if discriminant >= 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
print("Roots:", root1, root2)
else:
print("No real roots")
def circle_perimeter(radius):
return 2 * 3.14159 * radius
n = int(input("Enter n: "))
r = int(input("Enter r: "))
print("nPr:", nPr(n, r))
print("nCr:", nCr(n, r))
List Functions
3. List Functions:
o len(): Returns the number of elements in a list.
Example: len([1, 2, 3]) → Output: 3
o sum(): Returns the sum of elements in a list (numeric only).
Example: sum([1, 2, 3]) → Output: 6
o any(): Returns True if any element in the list is True.
Example: any([0, 1, 0]) → Output: True
o all(): Returns True if all elements in the list are True.
Example: all([1, 2, 3]) → Output: True
o sorted(): Returns a sorted version of the list.
Example: sorted([3, 1, 2]) → Output: [1, 2, 3]
4. List Methods:
o append(x): Adds x at the end of the list.
Example: [1, 2].append(3) → Output: [1, 2, 3]
o extend(iterable): Appends elements of an iterable to the list.
Example: [1, 2].extend([3, 4]) → Output: [1, 2, 3, 4]
o insert(i, x): Inserts x at index i.
Example: [1, 3].insert(1, 2) → Output: [1, 2, 3]
o index(x): Returns the first index of x.
Example: [1, 2, 3].index(2) → Output: 1
o sort(): Sorts the list in ascending order.
Example: [3, 1, 2].sort() → Output: [1, 2, 3]
def check_order(lst):
if lst == sorted(lst):
print("List is sorted in ascending order.")
elif lst == sorted(lst, reverse=True):
print("List is sorted in descending order.")
else:
print("Items in list are not sorted.")
def unique_chars(*strings):
for s in strings:
print(f"Unique characters in '{s}': {set(s)}")
unique_chars("hello", "world", "")
def most_frequent(s):
frequency = {}
for char in s:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
sorted_frequency = sorted(frequency.items(), key = lambda x: x[1], reverse=True)
for char, freq in sorted_frequency:
print(char, freq)
most_frequent("abracadabra")
File Operations
10. Access Modes:
o 'r': Read mode (default).
o 'w': Write mode (overwrites the file).
o 'a': Append mode.
o 'rb', 'wb': Read/Write in binary mode.
11. File Methods:
o read(): Reads the entire content.
o readline(): Reads a single line.
o readlines(): Reads all lines into a list.
o tell(): Returns the current position.
o seek(): Moves the cursor to the specified position.
o write(): Writes to the file.
12. Reverse Words in File:
Inheritance
15. Inheritance and super():
class Parent:
def show(self):
print("Parent method")
class Child(Parent):
def show(self):
super().show()
print("Child method")
obj = Child()
obj.show()
16. Overriding Base Class Method:
class Base:
def display(self):
print("Base class")
class Derived(Base):
def display(self):
print("Derived class")
obj = Derived()
obj.display()
Loop Theory
1. Purpose of Loops:
print(i)
i=0
while i < 5:
print(i)
i += 1
3. range() Function:
o Generates sequences.
print(i) # Outputs: 1, 3, 5, 7, 9
4. break Statement:
for i in range(10):
if i == 5:
break
5. continue Statement:
for i in range(5):
if i == 3:
continue
print(i)
6. Nested Loops:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
print(char)
8. Infinite Loops:
lst = [1, 2, 3, 4]
total = sum(lst)
print(total)
for i in range(5):
print(i)
else:
If-Else Statements
if x > 5:
print("Greater")
else:
print("Smaller")
o Strings are sequences of characters enclosed within single (' '), double (" "), or triple
quotes (''' ''').
Answer Example:
s = "Hello, World!"
print(s[0]) # H
print(s[-1]) # !
Answer Example:
s = ""
print(s[0]) # Output: P
print(s[-1]) # Output: n
print(s[1:4]) # Output: yth
4. What does it mean that strings in are immutable? Why is this important?
o Strings cannot be changed once created. Any modification creates a new string.
Example:
s = "hello"
Answer Example:
▪ \n: Newline
▪ \t: Tab
▪ \\: Backslash
Example:
print("Hello\nWorld") # Newline
for i in range(3):
print(i) # 0, 1, 2
x=0
while x < 3:
print(x)
x += 1
Example:
print(i) # 1, 3, 5, 7, 9
Example:
for i in range(5):
if i == 3:
break
print(i)
Example:
for i in range(3):
print(i)
else:
Answer:
class Parent1:
def feature1(self):
class Parent2:
def feature2(self):
def feature3(self):
obj = Child()
obj.feature1()
obj.feature2()
obj.feature3()
7. Given the Coordinates (x, y) of a Center of a Circle and Its Radius, Write Program to Determine
Whether the Point Lies Inside the Circle, on the Circle, or Outside the Circle.
Answer:
import math
if distance < r:
elif distance == r:
else:
xc, yc, r = map(float, input("Enter circle center (x, y) and radius: ").split())
Answer:
class Parent1:
def display(self):
class Parent2:
def display(self):
def display(self):
obj = Child()
obj.display()
• Strings are immutable, indexed, iterable, and support many built-in methods.
Example:
s = "Hello, World!"
print(s[0]) # H
print(s[-1]) # !
Example:
s = ""
print(s[0]) # Output: P
print(s[-1]) # Output: n
4. What does it mean that strings in are immutable? Why is this important?
Example:
s = "hello"
Example:
• Escape sequences allow using special characters like newline (\n), tab (\t), etc.
Example:
print("Hello\nWorld") # Newline
for i in range(3):
print(i) # 0, 1, 2
x=0
while x < 3:
print(x)
x += 1
Example:
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
Example:
for i in range(5):
if i == 3:
break
print(i)
Example:
for i in range(5):
if i == 3:
continue
print(i)
Example:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Example:
s = ""
for char in s:
print(char)
Example:
break
Example:
for i in range(3):
print(i)
else:
Example:
x = 10
if x > 15:
elif x > 5:
else:
print("5 or less")
2. What are nested if-else statements, and when are they useful?
• Nested if-else: An if or else inside another if or else. Useful for checking multiple conditions
hierarchically.
Example:
x = 20
if x > 10:
if x < 25:
else:
else:
print("10 or less")
Example:
x, y = 5, 10
Example (Correct):
x=5
if x > 0:
print("Positive number")
Example (Incorrect):
x=5
if x > 0:
Incorrect Example:
else:
Example:
x=5
7. How can you use if-else statements to check for even or odd numbers?
Example:
if x % 2 == 0:
print("Even")
else:
print("Odd")
Example:
x = 5 # Assignment
if x == 5: # Comparison
print("Largest:", a)
elif b > c:
print("Largest:", b)
else:
print("Largest:", c)
1. What are math functions in Python, and where are they found?
• Provides advanced mathematical functions like trigonometry, logarithms, and constants like
π.
Example:
import math
print(math.pi) # 3.141592653589793
• abs(): Built-in function for absolute values. Works for integers and floats.
Example:
print(abs(-5)) # 5
import math
print(math.fabs(-5)) # 5.0
Example:
import math
print(math.sqrt(16)) # 4.0
Example:
import math
print(math.sin(angle)) # 0.5
6. Describe the pow() function and how it differs from the ** operator.
Example:
print(pow(2, 3)) # 8
print(2 ** 3) # 8
Math Functions Basics Theory Questions
Example:
import math
2. Explain how to find the greatest common divisor (GCD) of two numbers in .
Example:
import math
Example:
import math
radius = 5
4. How does handle rounding of numbers, and what functions are available for this purpose?
• provides functions for rounding:
Example:
import math
print(math.floor(3.7)) # Output: 3
print(math.ceil(3.3)) # Output: 4
1. What is a list in Python, and how is it different from other data types?
my_list = [1, 2, 3]
my_list[0] = 10
print(my_list[1]) # Output: 20
my_list = [1, 2, 3, 4, 5]
6. Explain how to add elements to a list using append(), extend(), and insert().
Example:
my_list = [1, 2]
my_list = [1, 2, 3]
print(len(my_list)) # Output: 3
my_tuple = (1, 2, 3)
• Tuples cannot be modified after creation, making them safer for fixed data.
4. How do you access elements in a tuple by index?
Example:
print(my_tuple[1]) # Output: 20
• Use in.
Example:
my_tuple = (1, 2, 3)
a, b, c = (1, 2, 3)
# Packing
my_tuple = 1, 2, 3
# Unpacking
x, y, z = my_tuple
my_tuple[1].append(4)
• Keys must be unique and immutable, while values can be of any data type.
• Unlike lists and tuples, dictionaries allow for quick lookup using keys instead of indices.
• Each element in a dictionary is stored as a pair, where the key is used to uniquely identify the
value.
Example:
my_dict = {"name": "Alice"}
5. What happens if you try to access a key that does not exist in a dictionary?
• A KeyError is raised.
Example:
• pop(key): Removes the specified key-value pair and returns the value.
• popitem(): Removes and returns the last inserted key-value pair as a tuple.
9. Explain the purpose of the keys(), values(), and items() methods in a dictionary.
12. Explain the difference between shallow and deep copies of a dictionary.
dict1 = {"a": 1}
dict2 = {"b": 2}
dict1.update(dict2)
14. Describe how to iterate over a dictionary’s keys, values, and items.
Example:
• No, keys must be immutable (e.g., strings, numbers, or tuples) to maintain their hash value.
• Use clear().
Example:
my_dict = {"name": "Alice"}
my_dict.clear()
print(my_dict) # Output: {}
18. What is the purpose of the get() method in a dictionary, and how does it differ from direct key
access?
• get() retrieves a value by key, returning a default value if the key does not exist instead of
raising a KeyError.
Example:
1. Explain how nested dictionaries work and how to access nested values.
nested_dict = {
• Data Storage: Storing structured data, such as user profiles or configuration settings.
Functions in
def function_name(parameters):
# function body
return value
Example:
def greet(name):
return a + b
8. How does handle variable scope within functions (local vs. global scope)?
• Function overloading allows multiple functions with the same name but different
parameters.
• does not directly support overloading but can achieve similar behavior using default
arguments or *args.
10. How do anonymous functions (lambda functions) work with map(), filter(), and reduce()?
• Examples:
11. What is a lambda function, and how does it differ from a regular function?
12. When would you use a lambda function over a standard function?
13. How do you call a function in , and what does function calling mean?
• Function calling involves executing a function by its name and passing arguments.
Example:
greet("Alice")
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
class Person:
self.name = name
19. What are attributes in a class, and how are they defined?
class Car:
wheels = 4 # Attribute
20. What are methods in a class, and how do they differ from functions?
• Methods are functions defined within a class that act on object data.
person = Person("Alice")
person.name = "Bob"
26. What are class methods and static methods, and how do they differ?
class MyClass:
@classmethod
def class_method(cls):
pass
@staticmethod
def static_method():
pass
class Person:
self.name = name
p = Person("Alice")
• Classes group related data and functionality into a single unit, making code more organized.
class Person:
o Duck typing: If an object behaves like a specific type, it is treated as that type.
• Definition: Having multiple methods with the same name but different parameters.
• does not directly support method overloading but can simulate it using default parameters
or variable-length arguments.
Example:
class Calculator:
return a + b
• Definition: A derived class provides a new implementation for a method from the base class.
• How it works: The method in the derived class has the same name as in the base class.
Example:
class Parent:
def show(self):
print("Parent method")
class Child(Parent):
def show(self):
print("Child method")
• Functions and methods accept various data types without strict parameter signatures.
class Vector:
self.x = x
self.y = y
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
print(animal.sound())
Abstraction
• Focuses on relevant data and operations, improving clarity and reducing complexity.
15. What are abstract classes, and how are they defined in ?
class Animal(ABC):
@abstractmethod
def sound(self):
pass
16. What are the key differences between abstraction and encapsulation?
Inheritance
• Inheritance allows one class (derived) to inherit attributes and methods of another class
(base).
• Reuse base class methods and attributes in derived classes without rewriting code.
19. What is a base class (or superclass) and a derived class (or subclass)?
• Private attributes (prefixed with __) are not directly inherited but can be accessed through
name mangling.
• Reusability.
• Maintainability.
• Extensibility.
class Parent:
def greet(self):
return "Hello!"
class Child(Parent):
def greet(self):
Encapsulation
• Bundling data and methods into a single unit while restricting direct access to internal
components.
25. What is the difference between public, protected, and private attributes?
• Protected: Accessible within the class and its subclasses (prefix _).
27. What is name mangling, and how does it work with private attributes?
• Name mangling changes the attribute name to include the class name.
Example:
class MyClass:
__private = 42
class SubClass(ParentClass):
pass
class A:
pass
class B(A):
pass
class C(B):
pass