Uday_codes_python_4
Uday_codes_python_4
Object : In general, anything that can be assigned to a variable in Python is referred to as an object. Strings, Integers, Floats,
Lists, Functions, Module etc. are all objects.
Namespaces : A namespace is a collection of currently defined names along with information about the object that the
name references. It ensures that names are unique and won’t lead to any conflict.
def greet_1 ():
a = "Hello"
print (a)
print (id(a))
print("Namespace - 1" )
greet_1 ()
print("Namespace - 2" )
greet_2 ()
# Output is:
Namespace - 1
Hello
140639382368176
Namespace - 2
Hey
140639382570608
Types of namespaces :
Built-in Namespace : Created when we start executing a Python program and exists as long as the program is running. This
is the reason that built-in functions like id(), print() etc. are always available to us from any part of the program.
Global Namespace : This namespace includes all names defined directly in a module (outside of all functions). It is created
when the module is loaded, and it lasts until the program ends.
Local Namespace : Modules can have various functions and classes. A new local namespace is created when a function is
called, which lasts until the function returns.
Scope of a Name :
In Python, the scope of a name refers to where it can be used. The name is searched for in the local, global, and built-in
namespaces in that order.
Global variables : In Python, a variable defined outside of all functions is known as a global variable. This variable name will
be part of Global Namespace.
x = "Global Variable"
print(x) # Global Variable
def foo():
print (x) # Global Variable
foo()
Local Variables : In Python, a variable defined inside a function is a local variable. This variable name will be part of the
Local Namespace.
def foo():
x = "Local Variable"
print (x) # Local Variable
foo()
print(x) # NameError: name 'x' is not defined
def foo():
x = "Local Variable"
print (x)
print(x)
foo()
print(x)
# Output is:
Global Variable
Local Variable
Global Variable
Modifying Global Variables : global keyword is used to define a name to refer to the value in Global Namespace.
x = "Global Variable"
def foo():
global x
x = "Global Change"
print (x)
print(x)
foo()
print(x)
# Output is:
Global Variable
Global Change
Global Change
The collection of predefined utilities is referred as the Python Standard Library. All these functionalities are organized into
different modules.
Module : In Python context, any file containing Python code is called a module.
Package : These modules are further organized into folders known as packages.
Importing module : To use a functionality defined in a module we need to import that module in our program.
import module_name
Importing from a Module : We can import just a specific definition from a module.
from math import factorial
print(factorial (5)) # 120
Aliasing Imports : We can also import a specific definition from a module and alias it.
from math import factorial as fact
print(fact (5)) # 120
Randint : randint() is a function in random module which returns a random integer in the given interval.
import random
random_integer = random .randint (1, 10)
print(random_integer ) # 8
Choice : choice() is a function in random module which returns a random element from the sequence.
import random
random_ele = random .choice (["A","B","C"])
print(random_ele ) # B
Classes
Classes : Classes can be used to bundle related attributes and methods. To create a class, use the keyword class
class className :
attributes
methods
Self: self passed to method contains the object, which is an instance of class.
Special Method : In Python, a special method __init__ is used to assign values to attributes.
class Mobile :
def __init__ (self , model):
self .model = model
Instance of Class : Syntax for creating an instance of class looks similar to function call. An instance of class is an Object.
class Mobile :
def __init__ (self , model):
self .model = model
a = Cart()
Cart.update_flat_discount(25)
print(Cart .flat_discount ) # 25
Static Method : Usually, static methods are used to create utility functions which make more sense to be part of the class.
@staticmethod decorator marks the method below it as a static method.
class Cart :
@staticmethod
def greet ():
print ("Have a Great Shopping" ) # Have a Great Shopping
Cart.greet ()
Can be accessed through object(instance of class) Can be accessed through class Can be accessed through class
OOPS
OOPS: Object-Oriented Programming System (OOPS) is a way of approaching, designing, developing software that is easy
to change.
Bundling Data : While modeling real-life objects with object oriented programming, we ensure to bundle related
information together to clearly separate information of different objects.
Encapsulation : Bundling of related properties and actions together is called Encapsulation. Classes can be used to bundle
related attributes and methods.
Inheritance : Inheritance is a mechanism by which a class inherits attributes and methods from another class. Prefer
modeling with inheritance when the classes have an IS-A relationship.
class Product :
def __init__ (self , name ):
self .name = name
e = ElectronicItem ("TV" )
e.display_product_details ()
class Product :
def __init__ (self , name):
pass
Inheritance Composition
Car is a vehicle Car has a Tyre
Syntax Errors : Syntax errors are parsing errors which occur when the code is not adhering to Python Syntax.
if True print ("Hello" ) # SyntaxError: invalid syntax
When there is a syntax error, the program will not execute even if that part of code is not used.
divide (5, 0)
# Output is:
ZeroDivisionError : division by zero
Raising Exceptions :
raise ValueError ("Unexpected Value!!" ) # ValueError:Unexpected Value
Handling Exceptions : Exceptions can be handled with try-except block. Whenever an exception occurs at some line in
try block, the execution stops at that line and jumps to except block.
try:
# Write code that
# might cause exceptions.
except :
# The code to be run when
# there is an exception.
Handling Specific Exceptions : We can specifically mention the name of exception to catch all exceptions of that specific
type.
try:
# Write code that
# might cause exceptions.
except Exception :
# The code to be run when
# there is an exception.
try:
result = 5/0
print (result )
except ZeroDivisionError :
print ("Denominator can't be 0" )
except :
print ("Unhandled Exception" )
# Output is:
Denominator can't be 0
Handling Multiple Exceptions : We can write multiple exception blocks to handle different types of exceptions differently.
try:
# Write code that
# might cause exceptions.
except Exception1 :
# The code to be run when
# there is an exception.
except Exception2 :
# The code to be run when
# there is an exception.
try:
result = 12/"a"
print (result )
except ZeroDivisionError :
print ("Denominator can't be 0" )
except ValueError :
print ("Input should be an integer" )
except :
print ("Something went wrong" )
# Output is:
Denominator can't be 0
Datetime : Python has a built-in datetime module which provides convenient objects to work with dates and times.
import datetime
Representing Date : A date object can be used to represent any valid date (year, month and day ).
import datetime
Today’s Date : Class method today() returns a date object with today’s date.
import datetime
Representing Time : A time object can be used to represent any valid time (hours, minutes and seconds ).
from datetime import time