Python 2
Python 2
Variables
1. Dynamic Typing:
Python uses dynamic typing. This means you don't need to explicitly declare the type of
a variable when assigning a value to it.
The variable type is inferred at runtime based on the value assigned to it.
3. Variable Assignment:
Assign values to variables using the = operator.
Multiple assignments can be done on a single line.
Variables can be reassigned to different data types during the execution of a program.
4. Variable Scope:
The scope of a variable defines where it can be accessed or referenced within the code.
Variables declared inside a function have local scope and are only accessible within that
function.
Variables declared outside functions or at the global level have global scope and can be
accessed from anywhere in the code.
6. Variable Types:
Python has various built-in data types for variables, including integers ( int ), floating-
point numbers ( float ), strings ( str ), lists ( list ), tuples ( tuple ), dictionaries
( dict ), sets ( set ), and more.
Type casting can be done using functions like int() , float() , str() , etc., to
convert variables from one type to another.
7. Deleting Variables:
Use the del keyword to delete a variable and free up the memory it occupies.
Example:
Variable assignment
x = 10 y = "Hello" z = [1, 2, 3]
Variable scope
def my_function(): local_var = "Local variable" print(local_var) # Accessible within the
function
Deleting variables
del z
In [22]: a = 10
b = 10
print(a+b)
20
In [23]: x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Python is awesome
myfunc()
print("Python is " + x)
Python is fantastic
# Variable scope
global_var = "Global variable"
def my_function():
local_var = "Local variable"
print("Inside function - local_var:", local_var) # Accessible within the funct
print("Inside function - global_var:", global_var) # Accessible within the fun
my_function()
print("Outside function - global_var:", global_var) # Accessible here
# Deleting variables
del z
x: 10
y: Hello
z: [1, 2, 3]
Type of x: <class 'float'>
Type of y: <class 'list'>
Inside function - local_var: Local variable
Inside function - global_var: Global variable
Outside function - global_var: Global variable
Datatypes
1. Built-in Data Types:
Python provides several built-in data types:
Numeric Types: Integers ( int ), Floating-point numbers ( float ), Complex
numbers ( complex )
Sequence Types: Strings ( str ), Lists ( list ), Tuples ( tuple )
Mapping Type: Dictionaries ( dict )
Set Types: Sets ( set ), Frozen sets ( frozenset )
Boolean Type: Boolean ( bool )
None Type: None
2. Dynamic Typing:
Python is dynamically typed, meaning you don't need to declare the data type explicitly.
The interpreter infers the data type based on the value assigned to the variable.
3. Mutable vs. Immutable:
Mutable Types: Can be modified after creation (e.g., lists, dictionaries, sets).
Immutable Types: Cannot be modified after creation (e.g., integers, floats, strings,
tuples).
4. Type Casting:
You can convert between different data types using built-in functions like int() ,
float() , str() , list() , tuple() , dict() , set() , etc.
5. Sequences:
Strings: Immutable sequences of characters enclosed in single or double quotes.
Lists: Mutable sequences of elements enclosed in square brackets [] .
Tuples: Immutable sequences of elements enclosed in parentheses () .
6. Mapping:
Dictionaries: Collection of key-value pairs enclosed in curly braces {} . Keys are unique
and immutable; values can be of any data type.
7. Sets:
Sets: Unordered collections of unique elements enclosed in curly braces {} . Sets do
not allow duplicate elements.
8. Boolean Type:
Represents truth values, True or False , used for logical operations and conditions.
9. None Type:
Represents absence of a value or null.
In [7]: a = 10
b = "vithu"
print(type(b))
print(type(a))
<class 'str'>
<class 'int'>
# Strings
string_var = "Hello, Python!"
print("String:", string_var)
# Lists
list_var = [1, 2, 3, 4, 5]
print("List:", list_var)
# Tuples
tuple_var = (10, 20, 30)
print("Tuple:", tuple_var)
# Dictionaries
dict_var = {'one': 1, 'two': 2, 'three': 3}
print("Dictionary:", dict_var)
# Sets
set_var = {1, 2, 3, 4, 5}
print("Set:", set_var)
# Boolean
bool_var = True
print("Boolean:", bool_var)
# None Type
none_var = None
print("None Type:", none_var)
Integer Number: 10
Float Number: 3.14
Complex Number: (2+3j)
String: Hello, Python!
List: [1, 2, 3, 4, 5]
Tuple: (10, 20, 30)
Dictionary: {'one': 1, 'two': 2, 'three': 3}
Set: {1, 2, 3, 4, 5}
Boolean: True
None Type: None
In [9]: #Operators(+ - * / %)
a = 5
b = 2
c = a + b
print(c)
Type Casting
1. Implicit Type Conversion:
Python performs implicit type conversion in certain situations automatically.
For example, adding an integer and a float results in a float, as Python automatically
converts the integer to a float.
Example:
Example:
Example:
invalid_int = int(invalid_str)
In [18]: # Implicit type conversion
x = 10 # Integer
y = 3.14 # Float
c = a + b
print(c)
30
Example: age = int(input("Enter your age: ")) print("Your age is:", age)
Example: while True: try: num = float(input("Enter a number: ")) print("You entered:", num)
break except ValueError: print("Invalid input. Please enter a number.")
5. Whitespace Trimming:
input() function returns the user's input with leading and trailing whitespace
removed.
To preserve leading or trailing whitespace, use raw_input() in Python 2 or
manipulate the input string directly.
x = int(input())
y = int(input())
z = x + y
print("With Conversion : ", z)
12
22
Without conversion : 1222
22
22
With Conversion : 44
mul = a * b * c
add = a + b + c
print(div)
2
34
4
6.8
if elase in python
1. Conditional Statements:
if statements are used for conditional execution in Python.
They allow you to execute a block of code only if a certain condition is true.
2. Syntax:
if statements have the following basic syntax: if condition:
# Code to execute if the condition is true
3. Indentation:
Python relies on indentation to define blocks of code.
The code to be executed under the if statement must be indented.
4. else Statement:
The else statement is used in conjunction with if to execute a block of code when
the if condition is false.
5. elif Statement:
Short for "else if", the elif statement allows checking multiple conditions sequentially
after an initial if .
It is used when there are multiple conditions to be evaluated.
6. Nested if Statements:
You can have if statements inside other if or else blocks, creating nested
conditional structures.
7. Boolean Expressions:
Conditions in if statements evaluate to boolean values ( True or False ).
Common operators used in conditions include == (equality), != (not equal), < (less
than), > (greater than), <= (less than or equal), >= (greater than or equal), and ,
or , not , etc.
9. Indentation Errors:
Improper indentation can lead to syntax errors or unexpected behavior in your code.
if num > 0:
print("Number is positive.")
elif num < 0:
print("Number is negative.")
else:
print("Number is zero.")
# Nested if statements
x = 10
y = 5
if x > 5:
if y > 3:
print("Both conditions are satisfied.")
else:
print("Only first condition is satisfied.")
else:
print("First condition is not satisfied.")
Yes
True
False
In [27]: a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In [30]: a = 2
b = 330
print("A") if a > b else print("B")
In [33]: a = 10
print(a % 3)
2. Syntax:
The basic syntax of a for loop in Python: for item in sequence:
# Code block to execute for each item in the sequence
4. range() Function:
The range() function generates a sequence of numbers that can be used in for
loops.
It's commonly used to iterate a specific number of times.
5. enumerate() Function:
The enumerate() function is used to loop over a sequence while keeping track of the
index.
9. Iterable Objects:
Any object that can be iterated over is considered iterable and can be used with a for
loop.
Example:
a
p
p
l
e
Values:
Alice
30
New York
Key-Value Pairs:
name : Alice
age : 30
city : New York
apple
banana
cherry
0
1
2
3
4
0
2
4
6
8
10
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8
5 x 2 = 10
6 x 2 = 12
7 x 2 = 14
8 x 2 = 16
9 x 2 = 18
10 x 2 = 20
In [56]: #Excercises
In [63]: sum = 0
sum = 0
5
5
In [ ]: numArray = []
sum = 0
for i in range(5):
num = int(input())
numArray.append(num)
2. Syntax:
The basic syntax of a while loop in Python: while condition:
# Code block to execute as long as the condition is true
3. Loop Continuation:
The loop continues to execute as long as the condition remains true.
It checks the condition before each iteration, and if the condition becomes false, the
loop stops.
4. Infinite Loops:
If the condition in a while loop always evaluates to True , it results in an infinite
loop.
Example:
In [78]: i = 0
while i < 5:
print(i)
i = i + 1
0
1
2
3
4
In [80]: i = 1
while i < 6:
print(i)
i += 1 #Assignment operator
1
2
3
4
5
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Value of i: 1
Value of i: 2
Value of i: 4
Value of i: 5
Python Collections
1. List:
Ordered: Lists maintain the order of elements as they are inserted.
Mutable: Elements in a list can be added, removed, or modified after creation.
Allows Duplicates: A list can contain duplicate elements.
Creation: Lists are created using square brackets [] .
2. Tuple:
Ordered: Tuples, like lists, maintain order.
Immutable: Once created, elements in a tuple cannot be changed.
Allows Duplicates: Similar to lists, tuples can contain duplicate elements.
Creation: Tuples are created using parentheses () .
3. Set:
Unordered: Sets don’t maintain order.
Unique Elements: Sets contain only unique elements; duplicates are automatically
removed.
Mutable (for the elements): Elements can be added or removed after creation, but the
set itself (as a whole) is immutable.
Creation: Sets are created using curly braces {} or the set() function.
my_set = {1, 2, 3}
4. Dictionary:
Key-Value Pairs: Dictionaries store data in key-value pairs.
Unordered: Prior to Python 3.7, dictionaries didn't maintain the order of elements, but
in modern Python versions, they maintain insertion order.
Keys are Unique: Each key in a dictionary must be unique.
Mutable: Elements (key-value pairs) can be added, removed, or modified after creation.
Creation: Dictionaries are created using curly braces {} with key-value pairs separated
by colons : .
1. List Methods:
Appending and Extending:
my_list.append(4)
extend() : Appends elements from another list to the end of the list.
my_list.insert(1, 'new_element')
my_list.remove('new_element')
popped_element = my_list.pop(2)
2. Tuple Operations:
Accessing Elements: Similar to lists, accessed by index.
Immutable: Cannot be modified after creation.
3. Set Methods:
Adding and Removing:
my_set.add(4)
remove() : Removes a specified element from the set. Raises an error if the
element doesn't exist.
my_set.remove(4)
discard() : Removes a specified element from the set if it exists; otherwise, does
nothing.
my_set.discard(4)
Operations:
union() : Returns the union of two sets.
intersection() : Returns the intersection of two sets.
difference() : Returns the difference between two sets.
update() : Updates the set with the union of itself and others.
4. Dictionary Methods:
Adding, Updating, and Deleting:
my_dict.update({'new_key': 'new_value'})
popped_value = my_dict.pop('new_key')
del my_dict['new_key']
Accessing Values:
In [ ]: #List
In [99]: a = [1, 2, 3, 4, 5]
extension = [6, 7]
my_list.extend(extension)
print("Extended:", my_list)
# Inserting and deleting elements
my_list.insert(2, 'inserted')
print("Inserted:", my_list)
my_list.remove('inserted')
print("Removed:", my_list)
popped_value = my_list.pop(3)
print("Popped:", popped_value, "List:", my_list)
my_list.sort()
print("Sorted:", my_list)
my_list.reverse()
print("Reversed:", my_list)
Appended: [1, 2, 3, 4, 5]
Extended: [1, 2, 3, 4, 5, 6, 7]
Inserted: [1, 2, 'inserted', 3, 4, 5, 6, 7]
Removed: [1, 2, 3, 4, 5, 6, 7]
Popped: 4 List: [1, 2, 3, 5, 6, 7]
First element: 1
Sliced: [2, 3, 5]
Index of 3: 2
Count of 4: 0
Sorted: [1, 2, 3, 5, 6, 7]
Reversed: [7, 6, 5, 3, 2, 1]
In [ ]: #Python Tuples
print(x)
print(thisset)
# Slicing
print("Sliced elements:", my_tuple[1:3])
# Tuple unpacking
a, b, c, d = my_tuple
print("Unpacked values:", a, b, c, d)
# Concatenating tuples
another_tuple = (4, 5)
concatenated_tuple = my_tuple + another_tuple
print("Concatenated tuple:", concatenated_tuple)
# Tuple repetition
repeated_tuple = my_tuple * 2
print("Repeated tuple:", repeated_tuple)
# Length of tuple
print("Length of tuple:", len(my_tuple))
First element: 1
Sliced elements: (2, 3)
Unpacked values: 1 2 3 apple
Concatenated tuple: (1, 2, 3, 'apple', 4, 5)
Repeated tuple: (1, 2, 3, 'apple', 1, 2, 3, 'apple')
Length of tuple: 4
my_set.discard(3)
print("Discarded:", my_set)
# Set operations
another_set = {3, 4, 5, 6}
union_set = my_set.union(another_set)
print("Union:", union_set)
intersection_set = my_set.intersection(another_set)
print("Intersection:", intersection_set)
difference_set = my_set.difference(another_set)
print("Difference:", difference_set)
Added: {1, 2, 3, 4, 5}
Discarded: {1, 2, 4, 5}
Union: {1, 2, 3, 4, 5, 6}
Intersection: {4, 5}
Difference: {1, 2}
In [112… thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
my_dict.update({'age': 31})
print("Age updated:", my_dict)
popped_value = my_dict.pop('age')
print("Popped age:", popped_value, "Dict:", my_dict)
Functions in Python
1. Definition:
Functions are blocks of reusable code designed to perform a specific task.
They enhance code readability, reusability, and modularity.
2. Syntax:
A basic function in Python:
def function_name(parameters):
# Code block
return value # Optional, returns a value
4. Return Statement:
return : Ends the function's execution and optionally returns a value to the caller.
If no return statement is specified, the function returns None by default.
5. Scope:
Functions create a local scope, meaning variables defined within a function are not
accessible outside it (unless specified otherwise).
6. Function Calling:
Functions are called by using their name followed by parentheses () containing
arguments (if any).
Example:
7. Types of Functions:
Built-in Functions: Predefined functions available in Python (e.g., print() , len() ,
max() ).
User-defined Functions: Functions defined by users to perform specific tasks.
8. Default Arguments:
Parameters in a function can have default values.
When an argument isn't passed for a parameter with a default value, the default value is
used.
9. Variable-Length Arguments:
Functions can accept a variable number of arguments using *args and **kwargs .
*args collects positional arguments into a tuple.
**kwargs collects keyword arguments into a dictionary.
10. Recursion:
Functions can call themselves, enabling a technique known as recursion.
Recursion is useful for solving problems that can be broken down into smaller, similar
sub-problems.
# Calling functions
greet() # Output: Hello, there!
result = add_numbers(5, 3)
print("Sum:", result) # Output: Sum: 8
fact = factorial(5)
print("Factorial of 5:", fact) # Output: Factorial of 5: 120
Hello, there!
Sum: 8
Hello, Alice!
Hello, Guest!
Total: 100
Factorial of 5: 120
helloWorld()
Hello world
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Emil Refsnes
Tobias Refsnes
Linus Refsnes
def add():
return 1 + 2
result = add()
print(result)
def name():
return "Vithu"
name()
getName = name()
print(getName)
3
Vithu
2. Objects (Instances):
Objects are instances of classes.
Each object created from a class has its own unique set of attributes and can perform
actions (methods) defined in the class.
3. Attributes:
Attributes are variables that belong to a class or an object.
They represent the state of the object and can be data variables or class variables.
4. Methods:
Methods are functions defined within a class.
They define the behavior or actions that objects of the class can perform.
Methods can interact with attributes of the class.
5. Constructor ( __init__ ):
__init__ is a special method used to initialize object attributes when the object is
created.
It's called automatically when creating a new instance of the class ( __init__(self,
...) ).
6. Encapsulation:
Classes help in encapsulating data and methods together.
Access to attributes and methods can be controlled using access specifiers ( public ,
private , protected ).
7. Inheritance:
Inheritance allows a new class (child class) to inherit properties and methods from an
existing class (parent class).
The child class can add new attributes or methods or override existing ones.
8. Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common
superclass.
It enables a single interface to be used for different data types or classes.
9. Abstraction:
Abstraction hides complex implementation details and only shows essential features of
an object.
It allows the user to focus on what an object does, rather than how it does it.
# Constructor
def __init__(self, name, age):
# Instance attributes
self.name = name
self.age = age
# Instance method
def make_sound(self):
pass # Placeholder method
def vithu(self):
print("I love you Nila...")
def nila(self):
print("I love you Vithu...")
baby1.vithu()
baby2.nila()
3. Syntax:
The __init__ method takes at least one parameter, commonly named self , which
refers to the object itself.
self is passed implicitly when calling methods or accessing attributes within the class.
4. Self Keyword:
self is the conventional name used for the first parameter of instance methods in
Python classes.
It refers to the instance of the class itself and allows access to its attributes and methods
within the class.
It distinguishes between the instance's attributes and local variables within methods.
5. Use of Self :
Inside the __init__ method and other instance methods, self is used to access
and modify the object's attributes.
It is not a reserved keyword in Python but a convention to use self as the first
parameter.
6. Example:
class Person: def init(self, name, age): self.name = name self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
7. Implicit Invocation:
When you create an instance of a class ( object = Class() ), Python implicitly passes
the object itself ( self ) to the __init__ method.
Therefore, you don’t need to explicitly pass self when creating objects; it's done
automatically by Python.
def display_info(self):
# Accessing instance variables using self within a method
print(f"Name: {self.name}, Age: {self.age}")
def display(self):
print("Ram:", self.ram)
print("Processor:", self.processor)
hp = Laptop()
hp.price = 160000
hp.ram = "32GB"
hp.processor = "i9"
hp.display()
Ram: 32GB
Processor: i9
self.instance_var = var
2. Class Variables:
Variables that are shared among all instances of a class.
Defined within the class but outside of any methods.
Accessed using the class name or an instance.
Example:
self.instance_var = var
obj1 = MyClass("First")
obj2 = MyClass("Second")
In [ ]: #Instance variables
def display_info(self):
print(f"Name: {self.name}, Salary: {self.salary}")
def display(self):
print("Brand : ", self.brand)
print("Price : ", self.price)
print("Charger Type : ", self.chargerType)
samsung.display()
Brand : Samsung
Price : 45000
Charger Type : Type-C
In [ ]: #Class variables
def display_info(self):
print(f"Name: {self.name}, Salary: {self.salary}, Company: {Employee.compan
XYZ Corp
XYZ Corp
Name: Alice, Salary: 50000, Company: XYZ Corp
Name: Bob, Salary: 60000, Company: XYZ Corp
def display(self):
print("Brand : ", self.brand)
print("Price : ", self.price)
print("Charger Type : ", self.chargerType)
2. Class Methods:
Definition: Class methods are methods that operate on the class itself rather than
instances.
Decorator: Defined using @classmethod decorator and take cls (class) as the first
parameter.
Purpose: Used for operations that involve the class itself or class variables shared
among all instances.
Example: class MyClass:
class_variable = "class_variable"
@classmethod
def class_method(cls):
return cls.class_variable
3. Static Methods:
Definition: Static methods are independent of class and instance variables.
Decorator: Defined using @staticmethod decorator.
Purpose: Used when a method does not require access to instance or class variables
within the class.
Example: class MyClass:
@staticmethod
def static_method():
return "This is a static method"
4. Special Note:
self , cls , and @staticmethod :
self : Refers to the instance of the class in instance methods.
cls : Refers to the class itself in class methods.
@staticmethod : Decorator used to define static methods, making them
independent of class and instance variables.
@classmethod
def class_method(cls):
return cls.class_variable
class_variable
pass
class Child(Parent):
pass
b. Multiple Inheritance:
A subclass inherits from multiple superclasses.
It allows inheriting attributes and methods from multiple classes.
Example: class ClassA:
pass
class ClassB:
pass
pass
c. Multilevel Inheritance:
A subclass inherits from another subclass.
It forms a chain of inheritance.
Example: class Grandparent:
pass
class Parent(Grandparent):
pass
class Child(Parent):
pass
d. Hierarchical Inheritance:
Multiple subclasses inherit from a single superclass.
Each subclass has its own set of attributes and methods.
Example: class Parent:
pass
class Child1(Parent):
pass
class Child2(Parent):
pass
e. Hybrid Inheritance:
Combination of different types of inheritance.
Example: class ClassA:
pass
class ClassB(ClassA):
pass
class ClassC:
pass
pass
3. Inheritance Terminology:
Superclass/Parent/Base Class: The class whose properties and behaviors are inherited.
Subclass/Derived Class/Child Class: The class that inherits from a superclass.
Method Overriding: Redefining a method in the subclass that already exists in the
superclass.
4. Use of super() :
super() is used to access the methods and properties of a superclass from a subclass.
5. Advantages:
Code Reusability: Avoids redundant code by inheriting attributes and methods.
Modularity: Divides the code into manageable and organized parts.
class Child(Parent):
def show_child(self):
return "Child class method"
class son(dad):
def laptop(self):
print("Sons phone")
vithu = son()
vithu.phone()
Dads phone
class ClassB:
def method_b(self):
return "Method from ClassB"
class mom:
def sweet(self):
print("Moms sweet")
vithu = son()
vithu.phone()
vithu.sweet()
Dads phone
Moms sweet
class Parent(Grandparent):
def method_p(self):
return "Method from Parent"
class Child(Parent):
def method_c(self):
return "Method from Child"
class dad(grandpa):
def money(self):
print("Dads money")
class son(dad):
def laptop(self):
print("sons laptop")
vithu = son()
vithu.laptop()
vithu.money()
d1 = dad()
d1.phone()
vithu.phone() #note it
sons laptop
Dads money
grandpa phone
grandpa phone
class Child1(Parent):
def method_c1(self):
return "Method from Child1"
class Child2(Parent):
def method_c2(self):
return "Method from Child2"
class son1(dad):
pass
class son2(dad):
pass
class son3(dad):
pass
vithu = son2()
vithu.money()
Dads money
class ClassB(ClassA):
def method_b(self):
return "Method from ClassB"
class ClassC:
def method_c(self):
return "Method from ClassC"
In [ ]: class dad:
def money(self):
print("Dads money")
class land():
def important(self):
print("important land")
vithu = son2()
vithu.money()
2. Syntax:
The general syntax for using super() is: super().method() .
In Python 3, you can simply use super().method() without passing the class name or
self explicitly.
3. Usage:
Calling Superclass Methods: Used to call a method defined in the superclass from a
method in the subclass.
Initiating the Parent Class: Often used in the __init__ method of a subclass to
initialize attributes from the parent class.
5. Example:
class Parent: def show(self): return "Hello from Parent"
class Child(Parent):
def show(self):
# Calling superclass method using super()
return super().show() + ", and Child"
def display(self):
print("you are class a")
class b(a):
def __init__(self):
super().__init__() #class the parent class constructure
print("B")
def display(self):
print("you are class b")
obj = b()
A
B
Polymorphism in Python
1. Definition:
Polymorphism refers to the ability of different objects to be used in a similar way, even
if they belong to different classes.
It allows methods to be written to handle objects of various classes that have a common
interface or superclass.
2. Types of Polymorphism:
a. Compile-Time Polymorphism (Static Binding):
Method Overloading: Defining multiple methods with the same name but different
parameters in the same class.
Python does not support traditional method overloading based on different argument
types due to its dynamic nature. However, it does support default arguments and
variable-length arguments.
3. Example of Polymorphism:
class Animal: def make_sound(self): pass
Creating instances
dog = Dog() cat = Cat()
In the example, animal_sound() can take any object that has a make_sound() method,
allowing the function to work with both Dog and Cat objects without changes,
showcasing the polymorphic behavior of Python.
4. Advantages:
Code Flexibility: Allows using objects of different classes interchangeably, enhancing
code flexibility.
Code Reusability: Methods written to handle a superclass can be reused for its
subclasses.
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
Woof!
Meow!
add(1,2)
add(1,2,3)
3
6
2. Access Modifiers:
Access modifiers define the accessibility or visibility of class members (attributes and
methods) from outside the class.
In Python, there are no explicit keywords like private , public , or protected as in
some other languages, but there are conventions and techniques to achieve similar
behavior.
b. Private:
Python uses a convention to denote private attributes or methods by prefixing them
with a single underscore _ .
They are intended to be private and should not be accessed directly from outside the
class.
Example: class MyClass:
def __init__(self):
self._private_var = 10 # Private variable
c. Protected:
Python uses a convention to denote protected attributes or methods by prefixing them
with a double underscore __ .
They are intended to be protected, although it's more about name mangling rather than
strict access control.
Example: class MyClass:
def __init__(self):
self.__protected_var = 20 # Protected variable
5. Purpose:
Encapsulation and access modifiers help in maintaining the integrity of the data within a
class by controlling its access from outside, promoting data security and preventing
accidental modification.
def get_price(self):
return self.__price
def getName(self):
print(self._companyName)
c1 = company()
c1.getName()
2. Try-Except Block:
try : The code that might raise an exception is placed within the try block.
except : If an exception occurs within the try block, the execution moves to the
corresponding except block that handles the exception.
Example: try:
# Code that might raise an exception
result = 10 / 0 # Division by zero
except ZeroDivisionError as e:
# Handling the ZeroDivisionError exception
print("Error:", e)
5. Raising Exceptions:
raise statement is used to raise a specific exception manually.
Example: x = 10 if x > 5:
raise ValueError("x should not be greater than 5")
In [95]: try:
# Code that might raise an exception
result = 10 / 0 # Division by zero
except ZeroDivisionError as e:
# Handling the ZeroDivisionError exception
print("Error:", e)
else:
# Executed if no exception occurs
print("Result:", result)
finally:
# Executed irrespective of an exception
print("Execution completed.")
try:
# Code that might raise exceptions
file = open("nonexistent_file.txt", "r")
result = 10 / 0 # Division by zero
except (FileNotFoundError, ZeroDivisionError) as e:
# Handling multiple exceptions
print("Error:", e)
try:
x = 10
if x > 5:
raise ValueError("x should not be greater than 5")
except ValueError as e:
# Raising an exception manually
print("Error:", e)
except Exception as e:
print(e)
finally:
print("Have you understood what what happens haha...")
Hi
Bye
name 'printt' is not defined
Have you understood what what happens haha...
File Handling
1. File Operations:
File: A named location on disk to store related information.
Python offers built-in functions and methods for creating, reading, updating, and
deleting files.
2. File Modes:
Read Mode ( 'r' ): Opens a file for reading. Raises an error if the file does not exist.
Write Mode ( 'w' ): Opens a file for writing. Creates a new file if it does not exist.
Truncates the file if it exists.
Append Mode ( 'a' ): Opens a file for appending. Creates a new file if it does not
exist. Preserves existing file content.
Read and Write Mode ( 'r+' ): Opens a file for both reading and writing.
Binary Mode ( 'b' ): Adds a binary mode to the existing modes, allowing
manipulation of binary files.
6. Examples:
Writing to a file
with open("new_file.txt", "w") as file: file.write("Hello, World!")
Appending to a file
with open("existing_file.txt", "a") as file: file.write("\nAppending new content.")
In [ ]: import os
f.write("Hi Vithu\n")
f.write("Hi Nila\n")
f.write("Happy Coding\n")
f.close()
#f.read()
#os.remove("fruits.txt")
Thank you
Happy Coding
by - Vithusan https://www.linkedin.com/in/vimalathasvithusan
In [ ]: