4. PYTHON NOTES
4. PYTHON NOTES
Dictionaries:
Dictionaries store collection of items in the form of key-value pairs. Keys and
values are for each item is separated with a colon ‘:’. Each element is separated
from the other by a comma. The comma separated list of items is enclosed by
braces. Dictionaries are mutable, which means that you can update or delete an
item from a dictionary and can also add new items to a dictionary.
Creating a Dictionary
type(cars)
model = cars['model']
print(model)
You can also access all the keys and values within a dictionary using keys and
values function as shown below:
You can also get items from a dictionary in the form of key-value pairs using items
function.
The ‘items’, ‘keys’ and ‘values’ functions return sequences that can be iterated
using for loops.
print(item)
# for keys
print(key)
# for Values
print(value)
You simply have to pass new key in index and assign it some value.
cars['capacity'] = 500
print(cars)
Updating a Dictionary
To update the dictionary, use the key for which you want to change the meaning
as the index and add a new value to it
print(cars)
cars['model'] = 2015
print(cars)
print(cars)
del cars['model']
print(cars)
You can also delete all the items in a dictionary using clear function.
print(cars)
cars.clear()
print(cars)
print(len(cars))
print('color' in cars)
print('model' not in cars)
Copying Dictionaries
To copy one dictionary to the other, you can use copy function
cars2 = cars.copy()
print(cars2)
Lists
Creating a List:
The easiest way to make a list is to enclose a comma-separated list of things
within square brackets and assign it to a variable,
you can also access range of items from a list using slice operator.
colors = ['Red', 'Green', 'Blue', 'Yellow', 'White']
sublist = colors[2:4]
print(sublist)
Concatenating List
nums1 = [2, 4, 6, 8, 10]
nums2 = [1, 3, 5, 7, 9]
result = nums1 + nums2
print(result)
Parameter:
expression: Represents the operation you want to execute on every item within
the iterable.
element: The term “variable” refers to each value taken from the iterable.
iterable: specify the sequence of elements you want to iterate through.(e.g., a
list, tuple, or string).
condition: (Optional) A filter helps decide whether or not an element should be
added to the new list.
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared)
# Displaying list
print(List)
print(matrix)
List Comprehensions translate the traditional iteration approach using for loop into a
simple formula hence making them easy to use.
# Displaying list
print(List)
Output
['G', 'e', 'e', 'k', 's', ' ', '4', ' ', 'G', 'e', 'e', 'k', 's', '!']
# Define a dictionary
person = {
"name": "John",
"age": 30,
"gender": "Male"
In this example, the dictionary person contains three key-value pairs. The keys are
“name”, “age”, and “gender”, and the values are “John”, 30, and “Male”, respectively.
You can access the values of a dictionary by using the keys, like this:
# Accessing values
print(person["age"]) # Output: 30
To add a new key-value pair to a dictionary, you can simply assign a value to a new
key
# Adding a new key-value pair
person["occupation"] = "Engineer"
print(person) # Output: {'name': 'John', 'age': 30, 'gender': 'Male', 'occupation': 'Engineer'}
person["age"] = 35
print(person) # Output: {'name': 'John', 'age': 35, 'gender': 'Male', 'occupation': 'Engineer'}
To remove a key-value pair from a dictionary, you can use the del keyword
# Removing a key-value pair
del person["gender"]
You can also use various dictionary methods to manipulate dictionaries, such
as keys(), values(), items(), get(), pop(), clear(), and others. These methods allow you
to access the keys, values, and items (key-value pairs) of a dictionary, get the value of
a key (with a default value if the key does not exist), remove a key-value pair from a
dictionary and return its value, and clear all key-value pairs from a dictionary,
respectively.
# Using dictionary methods
person.clear()
print(person) # Output: {}
Python Object Oriented Programming
Python is a versatile programming language that supports various
programming styles, including object-oriented programming (OOP) through
the use of objects and classes.
An object is any entity that has attributes and behaviors. For example,
a parrot is an object. It has
attributes - name, age, color, etc.
behavior - dancing, singing, etc.
Similarly, a class is a blueprint for that object.
class Parrot:
# class attribute
name = ""
age = 0
# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Output
In the above example, we created a class with the name Parrot with two
attributes: name and age .
Then, we create instances of the Parrot class. Here, parrot1 and parrot2 are
references (value) to our new objects.
We then accessed and assigned different values to the instance attributes
using the objects name and the . notation.
Python Inheritance
Inheritance is a way of creating a new class for using details of an existing
class without modifying it.
The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
def eat(self):
print( "I can eat!")
def sleep(self):
print("I can sleep!")
# derived class
class Dog(Animal):
def bark(self):
print("I can bark! Woof woof!!")
Output
I can eat!
I can sleep!
I can bark! Woof woof!!
Here, dog1 (the object of derived class Dog ) can access members of the base
class Animal. It's because Dog is inherited from Animal .
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
Output
c.__maxprice = 1000
Here, we have tried to modify the value of __maxprice outside of the class. However, since __maxprice is a private
variable, this modification is not seen on the output.
As shown, to change the value, we have to use a setter function i.e setMaxPrice() which takes price as a parameter.
Polymorphism
Polymorphism is another important concept of object-oriented programming. It simply means more than one form.
That is, the same entity (method or operator or object) can perform different operations in different scenarios.
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")
class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")
class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
Output
Rendering Square...
Rendering Circle...