Python Honey's
Python Honey's
Integer: All the numbers (positive, negative and zero) without any
fractional part come under Integers.
...-3, -2, -1, 0, 1, 2, 3,...
Conditional Statements
Conditional Statement: Conditional Statement allows you to
execute a block of code only when a specific condition is True.
if True:
print("If Block")
print("Inside If")
# Output is:
If Block
Inside If
if Condition A:
block of code
elif Condition B:
block of code
else:
block of code
Identation:
1. Space(s) in front of the conditional block is called indentation. 2.
Indentation(spacing) is used to identify the Conditional Blocks. 3.
Standard practice is to use four spaces for indentation.
Strings - working with strings
String Concatenation: Joining strings together is called string
concatenation.
a = "Hello" + " " + "World"
print(a) # Hello World
String Repetition: * operator is used for repeating strings any
number of times as required.
a = "$" * 10
print(a) # $$$$$$$$$$
not in: By using the, not in operator, one can determine if a value
is not present in a sequence or not.
language = "Python"
result = "P" not in language
print(result) # False
Calculations in Python
Addition: Addition is denoted by + sign.
print(2 + 5) # 7
print(1 + 1.5) # 2.5
String Methods
Name Syntax Usage
isdigit() str.isdigit() Gives True if all the characters are
digits. Otherwise, False.
strip() str.strip() Removes all the leading and trailing
spaces from a string.
strip() with str.strip(separator) We can also specify
separator separator(string) that need to be
removed.
replace() str.replace(old, new) Gives a new string after replacing
all the occurrences of the old
substring with the new substring.
startswith() str_var.startswith(valu Gives True if the string starts with
e) the specified value. Otherwise,
False.
Name Syntax Usage
endswith() str.endswith(value) Gives True if the string ends with
the specified value. Otherwise,
False.
upper() str.upper() Gives a new string by converting
each character of the given string to
uppercase.
lower() str.lower() Gives a new string by converting
each character of the given string to
lowercase.
split() str.split() The split() method splits a string
into a list.
split() with str.split(separator, Specifies the separator to use when
separator maxsplit) splitting the string. By default any
whitespace is a separator.
join() str.join(iterable) The join() method takes all items in
an iterable and joins them into one
string.
String Formatting: String Formatting simplifies the concatenation.
It increases the readability of code and type conversion is not
required.
Add Placeholders: Add placeholders {} where the string needs to
be formatted.
name = "Raju"
age = 10
msg = "Hi {}. You are {} years old."
print(msg.format(name, age)) # Hi Raju. You are 10 years old.
Reversing a List: -1 for step will reverse the order of items in the
list.
list_a = [5, 4, 3, 2, 1]
list_b = list_a[::-1]
print(list_b) # [1, 2, 3, 4, 5]
List Methods
Name Syntax Usage
append( list.append(value) Adds an element to the end of the list.
)
extend( list_a.extend(list_b) Adds all the elements of a sequence to the end
) of the list.
insert( list.insert(index,val Element is inserted to the list at specified
) ue) index.
pop() list.pop() Removes last element.
function_name(args)
def sum_of_two_number(a, b):
total = a + b
return total
result = sum_of_two_number(2, 3)
print(result) # 5
function_name(arg_1, arg_2)
Default Values:
def greet(arg_1="Hi", arg_2="Ram"):
print(arg_1 + " " + arg_2) # Hi Ram
more_args(1, 2, 3, 4)
more_args(a=1, b=2)
def function_2():
function_1()
a = int(input()) # 5
increment(a)
print(a) # 5
list_a = [1,2]
add_item(list_a)
print(list_a) # [1, 2, 3]
def add_item(list_x=[]):
list_x += [3]
print(list_x)
add_item()
add_item([1,2])
add_item()
# Output is:
[3]
[1, 2, 3]
[3, 3]
Nested Loops
Nested Loops: An inner loop within the repeating block of an outer
loop is called a Nested Loop. The Inner Loop will be executed one
time for each iteration of the Outer Loop.
Syntax:
for item in sequence A:
Block 1
for item in sequence B:
Block 2
Syntax of while in for loop:
for item in sequence:
Block 1
while Condition:
Block 2
Dictionaries
Dictionaries: Unordered collection of items. Every dictionary item
is a Key-value pair.
Creating a Dictionary: Created by enclosing items within {curly}
brackets. Each item in the dictionary has a key-value pair separated
by a comma.
dict_a = {
"name": "Teja",
"age": 15
}
Accessing Items - Get: The get() method returns None if the key
is not found.
dict_a = {
'name': 'Teja',
'age': 15
}
print(dict_a.get('name')) # Teja
print(dict_a.get('city')) # None
Membership Check: Checks if the given key exists.
dict_a = {
'name': 'Teja',
'age': 15
}
result = 'name' in dict_a
print(result) # True
Sets
Sets: Unordered collection of items. Every set element is Unique (no
duplicates) and Must be immutable.
No Duplicate Items: Sets contain unique elements
set_a = {"a", "b", "c", "a"}
print(set_a) # {'b', 'a', 'c'}
def greet_2():
a = "Hey"
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()
foo()
print(x) # NameError: name 'x' is not defined
print(x)
foo()
print(x)
# Output is:
Global Variable
Local Variable
Global Variable
def foo():
global x
x = "Global Change"
print(x)
print(x)
foo()
print(x)
# Output is:
Global Variable
Global Change
Global Change
Classes
Classes: Classes can be used to bundle related attributes and
methods. To create a class, use the keyword class
class className:
attributes
methods
def get_model(self):
print(self.model) # iPhone 12 Pro
Class Attributes: Attributes whose values stay common for all the
objects are modelled as Class Attributes.
Accessing Class Attributes:
class Cart:
flat_discount = 0
min_bill = 100
def __init__(self):
self.items = {}
print(Cart.min_bill) # 100
Instance Methods
Class Methods
Static Methods
a = Cart()
a.add_item("book", 3)
a.display_items()
Cart.update_flat_discount(25)
print(Cart.flat_discount) # 25
Cart.greet()
Instance Methods Class Methods Methods
self as parameter cls as parameter No cls or self as parameters
No decorator required Need decorator Need decorator
@classmethod @staticmethod
Can be accessed through Can be accessed through Can be accessed through
object(instance of class) class 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
def display_product_details(self):
print("Product: {}".format(self.name)) # Product: TV
class ElectronicItem(Product):
pass
e = ElectronicItem("TV")
e.display_product_details()
class Product:
def __init__(self, name):
self.name = name
def display_product_details(self):
print("Product: {}".format(self.name)) # Product: TV
class ElectronicItem(Product):
def set_warranty(self, warranty_in_months):
self.warranty_in_months = warranty_in_months
e = ElectronicItem("TV")
e.display_product_details()
class ElectronicItem(Product):
def set_warranty(self, warranty_in_months):
self.warranty_in_months = warranty_in_months
def display_electronic_product_details(self):
self.display_product_details()
e = ElectronicItem("TV")
e.display_electronic_product_details()
Composition: Modeling instances of one class as attributes of
another class is called Composition. Prefer modeling with
inheritance when the classes have an HAS-A relationship.
class Product:
def __init__(self, name):
self.name = name
self.deal_price = deal_price
def display_product_details(self):
print("Product: {}".format(self.name)) # Product: Milk
def get_deal_price(self):
return self.deal_price
class GroceryItem(Product):
pass
class Order:
def __init__(self):
self.items_in_cart = []
def display_order_details(self):
for product, quantity in self.items_in_cart:
product.display_product_details()
milk = GroceryItem("Milk")
order.add_item(milk, 2)
order.display_order_details()
Overriding Methods: Sometimes, we require a method in the
instances of a sub class to behave differently from the method in
instance of a superclass.
class Product:
def __init__(self, name):
self.name = name
def display_product_details(self):
print("Superclass Method")
class ElectronicItem(Product):
def display_product_details(self): # same method name as
superclass
print("Subclass Method")
e = ElectronicItem("Laptop")
e.display_product_details()
# Output is:
Subclass Method
def display_product_details(self):
print("Product: {}".format(self.name)) # Product: Laptop
class ElectronicItem(Product):
def display_product_details(self):
super().display_product_details()
print("Warranty {}
months".format(self.warranty_in_months)) # Warranty 10 months
e = ElectronicItem("Laptop")
e.set_warranty(10)
e.display_product_details()
class ElectronicItem(Product):
pass
class Laptop(ElectronicItem):
pass
Syntax Errors
Exceptions
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
divide(5, 0)
# Output is:
ZeroDivisionError: division by zero
date_object = datetime.date.today()
print(date_object) # 2022-12-17
dt1 = datetime.datetime(2021, 2, 5)
dt2 = datetime.datetime(2022, 1, 1)
duration = dt2 - dt1
print(duration) # 330 days, 0:00:00
print(type(duration)) # <class 'datetime.timedelta'>
mm/dd/yyyy
dd-mm-yyyy
now = datetime.now()
formatted_datetime_1 = now.strftime("%d %b %Y %I:%M:%S %p")
print(formatted_datetime_1) # 05 Feb 2021 09:26:50 AM