fbpx
Python Classes – Objects – Modules & Functions

Python Classes – Objects – Modules & Functions

Python Classes – Objects – Modules & Functions

Let us see Python Classes, Objects, Modules and Functions

  1. Classes and Objects
  2. Modules
  3. Functions

Watch on YouTube: https://youtu.be/YUz1XDbJDlI

Learn Python in Tamil | பைதான் மொழியைக் கற்றுக்கொள்ளுங்கள் – Python type casting and operators.

Classes & Objects

Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a “blueprint” for creating objects.

Creating Class

class MyClass:
    empid = 1001
    empname = "John"

Creating object for the class

obj1 = MyClass()
print(obj1.empid)
print(obj1.empname) 

The __init__() Function

This is kind of Python’s standard initialize method which is invoked during object creation of the class. consider you want to pre-initialize the properties of the class ahead of object creation, then you need to use this method.

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name
        self.age = age

# -------------------------------------------

student1 = Student(100,"Bob", 22)
print(student1.sid)
print(student1.name)
print(student1.age)

In the above class we have “init” method which gets initialized along with the constructor while creating an object and we have self as our first parameter, which is used for identifying the current/own object.

Note: The \__init\__() function is called automatically every time the class is being used to create a new object.

The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class and It doesn’t need to be named like “self”.

We can call it whatever we want, but it should be the first parameter of any function in the class, see below example..

class Car:
    def __init__(myownobjectref, carid, carmake):
        myownobjectref.carid = carid
        myownobjectref.carmake = carmake

Note: In the above example we have used myownobjectref as first parameter and it refers the current object of Car class.

Modify object properties

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name

# -------------------------------------------

student1 = Student(100,"Bob")
student1.sid = 101

Delete object properties

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name

# -------------------------------------------

student1 = Student(100,"Bob")
del student1.sid

Delete object

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name

# -------------------------------------------

student1 = Student(100,"Bob")
del student1

Modules

Python Modules

Python modules are .py files that consist of Python code. Any Python file can be referenced as a module.

Some modules are available through the Python Standard Library and are therefore installed with your Python installation. Others can be installed with Python’s package manager pip. Additionally, you can create your own Python modules since modules are comprised of Python .py files.

Writing and Importing Modules

Writing Modules

Writing a module is just like writing any other Python file. Modules can contain definitions of functions, classes, and variables that can then be utilized in other Python programs.

From our Python 3 local programming environment or server-based programming environment, let’s start by creating a file hello.py that we’ll later import into another file.

To begin, we’ll create a function that prints Hello, World!:

# math_operations.py (Located under my-own-modules directory)

# Maths Operation

def add(a, b):
    print(a + b)

If we run the program on the command line with python math_operations.py nothing will happen since we have not invoked the functions add.

Importing Modules

Let’s create a second file called main_program.py so that we can import the module we just created, and then call the function.

main_program.py
# Import math_operations module - which is nothing but the math_operations.py file
import math_operations


# Call function
math_operation.add(1, 2)

Because we are importing a module, we need to call the function by referencing the module name in DOT " . " notation.

We could instead import the module as from hello import world and call the function directly as world(). You can learn more about this method by reading how to using from … import when importing modules.

Functions

Python Functions

Python functions are written inside .py files which performs the instruction or action written in Python. each method/function performs set of instruction or operations we wanted to perform. like adding two numbers, checking if the user is admin or not etc.,

Creating Function

In order to create python functions/methods you need to use def key word prefixed. lets see the below example.

# functions.py
# def -> key word tells us this is a method.
# display_app_name(): this is our method name with no parameters, because with in the brackets we have not passes any variable.
def display_app_name():
    print("My App Name")

Calling Function

Calling a medhod in Python is easy, just need to use the method name with the brackets. (If method has any parameters, we need to just pass it inside the brackets.)

# calling the function
display_app_name()

Returning data from Function

# functions.py
def get_current_username(user):
    return user["name"]

userobj = {
    "name": "John",
    "id": 100}

print(get_current_username(userobj))

Calling function inside another function.

# functions.py
def is_admin(user_param):
    return user_param["admin"]

def append_usertype(old_user_id, user_type):
    return f"{old_user_id}_{user_type}"


def regenerate_userid(user_param):
    new_userid = user_param["id"]
    if is_admin(user_param):
        new_userid = append_usertype(new_userid,"ADM")
    else:
        new_userid = append_usertype(new_userid,"USR")

    user_param["id"] = new_userid
    return user_param

#-----------------------------------------

user = {
    "name": "John",
    "id": 100,
    "admin": False
}
print(user)
print(regenerate_userid(user))
Python decision making & loops – Learn Python in Tamil www.aryanz.co.in

Python Decision making and Loops

Python Decision making and Loops

Python Decision making and Loops

Let us see about Python decision making and loops

  1. Decision making
  2. Loops

Watch on YouTube: https://youtu.be/A2qoypUV-ZE

Learn Python in Tamil | பைதான் மொழியைக் கற்றுக்கொள்ளுங்கள் – Python type casting and operators.

Decision making

Decision making evaluates multiple expressions which produce TRUE or FALSE as an outcome.

Which defines action to take and what statements has to execute when the outcome is TRUE or FALSE otherwise.

Note: Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value

Decision making statements are as follows:

  1. If statement
  2. If-else statement
  3. Nested if statement

If Statement

# if statement

# When you want to check some logical condition and perform actions based on positive result.

x = 8
y = 10

if x > y:
    print("X is greater")
    print(f"{x}")

print("Program ended")

If-else statement

# if-else statement

# An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.

x = 80
y = 10

if x > y:
    print("X is greater")
else:
    print("Y is greater")

print("Program Ended")

Nested if-else statement

# nested/multiple if-else statement

# When you want to check multiple conditions and perform actions based on the result (TRUE or FALSE).

x = 80
y = 10
z = 90

# Multiple if

if x > y:
    print("X is greater")
elif x > z:
    print("X is greater")
elif y > z:
    print("Y is greater")
else:
    print("Z is greater")

# Nested If

if x > y:
    if x > z:
        print("x is greater")
    else:
        print("z is greater")
elif y > z:
    print("y is greater")
else:
    print("z is greater")

print("Program Ended")

Loops

A loop statement allows us to execute a statement or group of statements multiple times.

Along with above loops, we also have the following 3 keywords used during Loops.

  1. Break
  2. Continue
  3. Pass

While loop

# While loop repeatedly executes a target statement as long as a given condition becomes true.

# Example 1 (Simple while loop)
count = 1

while count < 4:
    print(count)
    count = count + 1

print("Out of while loop")
print("------------------------------")

# Example 2 : Using else Statement with While Loop

count = 0
while count < 4:
    print(count)
    count = count + 1
else:
    print("count is less than 4")

For loop

# For loop
# it has the ability to iterate over the items of any sequence,
# such as a list or a string.

# We can iterate Collection items
# Such as List, Tuple, Set and so on.

# Example 1 : looping list
blog_websites = ["aryanz.co.in", "balamt.in", "wecancode.live"]

for x in blog_websites:
    print(x)


# Example 2 : looping string value
name = "John"
for letter in name:
    print(letter)


# Example 3: Using else in For loop

for i in range(1,4):
    print(i)
else:
    print(f"Reached the max range")

Nested loop

# Nested loop
# looping inside another loop is called nested loop

# What is the output of the following code? - Comment your answer here > https://youtu.be/A2qoypUV-ZE

for x in range(1, 5):
    for y in range(x-1, x): # 1, 4
        print(f"{y}")
    print(f"\t")
Python decision making & loops - Learn Python in Tamil www.aryanz.co.in
Python decision making & loops – Learn Python in Tamil www.aryanz.co.in
Python type casting and operators

Python type casting and operators

Python type casting and operators

Let us see about Python type casting and operators.

  1. Python Type casting
  2. Python Operators

Watch on YouTube: https://youtu.be/cit6jKwKY1o

Learn Python in Tamil | பைதான் மொழியைக் கற்றுக்கொள்ளுங்கள் – Python type casting and operators.

Python type casting

We know Python is not strict with the data type declaration of variables. What makes the need of type casting? Let us see below

# weather.txt
{
  "id": 2345,
  "city": "Chennai",
  "weather": "20",
  "unit": "Celsius"
}

Consider there is a weather API, upon calling it whose response will be in JSON (JavaScript Object Notation) format.

The JSON response has key & value for "weather":"20" Which is of type text/string.

But in the python program, we need it to be number so that we can convert it from Celsius to Fahrenheit or vice-versa.
In such cases we have to go for casting the data type.

# Program to read file containing JSON object for weather

# In order to read and parse JSON, we need to use the json module from python
import json

weathers = []  # declaring empty list
weather_value = None # Will be using this variable to store the type casted value

print("Started Reading JSON file")
with open('weather.txt') as f:  # Reading file
    for jsonObj in f:   # reading lines from the file
        weather = json.loads(jsonObj)   # parsing and storing the line
        weathers.append(weather)    # adding the line to the list

print("Printing each JSON Decoded Object")
for weather in weathers:    # Traversing through the list
    print(weather)
    print(f"Type of weather is: {type(weather['weather'])}")
    weather_value = int(weather["weather"]) # Type casting from string to int
    # print(weather["id"], weather["city"], weather["weather"], weather["unit"])


print(f"{weather_value}° C")
print(type(weather_value))


fahrenheit = (weather_value * 9/5) + 32

print(f"Fahrenheit {fahrenheit}")


Python Operators

Following are the types of operators available in Python programming.

Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations.

"""
Python Arithmetic Operators
Arithmetic operators are used with numeric values
    to perform common mathematical operations:
--------------------------------------------------------------
|   Operator    |   Name             |       Example         |
|---------------|--------------------|-----------------------|
|       +       |   Addition         |       x + y           |
|       -       |   Subtraction      |       x - y           |
|       *       | Multiplication     |       x * y           |
|       /       |   Division         |       x / y           |
|       %       |   Modulus          |       x % y           |
|       **      |Exponential (power) |       x ** y          |
|       //      | Floor division     |       x // y          |
--------------------------------------------------------------
"""

Relational operators

Relational or Comparison operators, which compares the value on either side and decide the relation among them.

"""
--------------------------------------------------------------------------------------------
|    Operator    |    Description                                                       |
|       ==       | equals operator check if both sides are same.                        |
|       !=       | not equals operator check if both sides are not same.                |
|       <>       | not equals operator check if both sides are not same. same as !=     | Python3 Does not Support <>
|       >        | if left side value is greater than right.                            |
|       <        | if left side value is lesser than right.                             |
|       >=       | if left side value is greater and equal to the right.                |
|       <=       | if left side value is lesser and equal to the right.                 |
------------------------------------------------------------------------------------------
Lets see some examples below
Assume variable x holds 3 and variable y holds 6,
"""

Assignment Operators

Assignment operators are used to assign value to a variable.

"""
-----------------------------------------------------
|   Operator        |   Example     |   Similar to  |
|-------------------|---------------|---------------|
|       =           |   x = 5       |   x = 5       | Assign value from right to left side
|       +=          |   x += 5      |   x = x + 5   | It adds right & left operand and assign to left side
|       -=          |   x -= 5      |   x = x - 5   | It subtracts right & left operand and assign to left side
|       *=          |   x *= 5      |   x = x * 5   | It multiplies right & left operand and assign to left side
|       /=          |   x /= 5      |   x = x / 5   | It divides left with right operand and assign to left side
|       %=          |   x %= 5      |   x = x % 5   | It takes modulo using two operand and assign to left
|       //=         |   x //= 5     |   x = x // 5  | It performs floor division on operands and assign to left
|       **=         |   x **= 5     |   x = x ** 5  | It performs exponential (power) calc on operands & assign to left
|       &=          |   x &= 5      |   x = x & 5   | Bitwise AND
|       |=          |   x |= 5      |   x = x | 5   | Bitwise OR
|       ^=          |   x ^= 5      |   x = x ^ 5   | Bitwise XOR
|       >>=         |   x >>= 5     |   x = x >> 5  | Bitwise right shift
|       <<=         |   x <<= 5     |   x = x << 5  | Bitwise left shift
----------------------------------------------------------
"""

Logical Operators

Logical operators are used in combining conditional statements.

"""
------------------------------------------------------------------------------------------
|   Operator    |                    Description                    |   Example            |
|---------------|---------------------------------------------------|----------------------|
|     and       | Returns True if both statements are true          |  x < 5 and  x < 10   |
|     or        | Returns True if one statements is true            |  x < 5 or  x < 10    |
|     not       | Returns False if the result is true or vice-versa |not(x < 5 and x < 10) |
|------------------------------------------------------------------------------------------|
"""

Bitwise Operators

Bitwise operators are used for comparing Binary (i.e., 0’s and 1’s) numbers. See below table for the available bitwise operators.

"""
Bitwise Operators
-----------------------------------------------------------------
|   Operator        |   Example     |   Operator name           |
|-------------------|---------------|---------------------------|
|       &           |   x = x & y   |  Bitwise AND              |
|       |           |   x = x | y   |  Bitwise OR               |
|       ~           |   x = x ~ y   |  Binary Ones Complement   |
|       ^           |   x = x ^ y   |  Bitwise XOR              |
|       >>          |   x = x>>y    |  Bitwise right shift      |
|       <<          |   x = x<<y    |  Bitwise left shift       |
-----------------------------------------------------------------
"""
AND Truth Table
AND Truth Table

When x and y value is 1 or True then the result will be 1 or True.

OR Truth table
OR Truth Table

When any one (x or y) values are True the result will also be True.

Membership Operators

Membership operators, checks for membership in a sequence (strings, lists, or tuples).

There are two membership operators, See below.

Membership Operators (in and not in)
Membership Operators (in and not in)

Identity Operators

Identity operators compare the memory location of two objects.

There are two types of Identity Operators (is and not is), See below

Identity Operators (is and is not)
Identity Operators (is and is not)
Python type casting and Operators

https://youtu.be/cit6jKwKY1o 
Learn Python in Tamil www.aryanz.co.in
Python type casting and Operators – Learn Python in Tamil www.aryanz.co.in
Python type casting and operators

Python comments and variables

Python comments and variables

Let us see about Python comments and variables which covers the below topics.

  1. Python Comments
    • Single line comment
    • End of the line comments
    • Multi line comments using # (Pound or Sharp)
    • Multi line comments using """ (3 double quotes a.k.a Multi line string)
  2. Variables
    • Declaring variables
    • Assign variables
    • re-assign variables
    • Nullify variables using None Keyword

Code Repo : https://git.io/JtnlX

Slides: https://git.io/Jtckd

We have the below topics covered as part of Python learning course.

  1. Python introduction in Tamil Part 1
  2. Python introduction in Tamil Part 2
  3. Writing your first python program and how to execute it?
  4. Python syntax, indentation and data types

Watch on YouTube: https://youtu.be/aRWq1UMYgXU

Learn Python in Tamil | பைதான் மொழியைக் கற்றுக்கொள்ளுங்கள் – Python comments and variables.

Python Comments

Comments in Python

  1. Documentation using comments – It helps anyone reading the code along with the comments can easily understand the code easily and how it works. (Logical and Functional explanation).
  2. (mostly this will be used for debugging your code, if the code is not working as expected and to find the line which cause the bug).

How to comment and what are all the ways we can comment in Python?

Lets see what all ways we can comment in Python.

  • Single line comments
  • End of the line comments
  • Multi line comments using # (Pound or Sharp)
  • Multi line comments using """ (3 double quotes a.k.a Multi line string)
Single line comments

It is writing in one single line and These lines are prefixed using # (Pound or Sharp).

# This is Single line comment
# Sample program to print hello world.
print("Hello, World")
# End of my python program
End of the line comments

End of line comments, as name says it is written at end of the line along with the Python code.

Lets see an example below,

amt1 = 20
amt2 = 5
final_amt = amt1 + amt2  # Adding amt1 and amt2.
Multi line comments using #

Multi line comments using #, it is similar to Single line comment, but it is written on multiple lines prefixed with the # (Pound or Sharp) symbol.

Primarily used for documenting python code or explaining the block of code below,

Its written at the top of a class or function.

Lets see an example below

#  Author: aryanz.co.in
#  Class name: calculator
#  Description:  This class is used for performing add, sub, multiply and divide. each action requires two parameters.

#  Add operation
#  Two parameters x and y
#  prints the result on the screen
def add(x, y)
          print(x + y)
Multi line comments using “””

It is same as Multi line comment using # but it is prefixed with the """ (3 double quotes).

Similar to the Multi line using #, even here we can use this for documentation.

Lets see an example below

"""  
Author: aryanz.co.in
Class name: calculator
Description:  This class is used for performing add, sub, multiply and divide. each action requires two parameters.
"""

""" Add operation
Two parameters x and y
prints the result on the screen
"""
def add(x, y)
          print(x + y)
Python comments and its types


Single line comments
End of the line comments
Multi line comments using # (Pound or Sharp)
Multi line comments using """ (3 double quotes a.k.a Multi line string)

www.aryanz.co.in

Python Variables

What is a variable?

Variables, a placeholder or container or a memory location to store values of any type, such as string, int, float, list and etc.,

  • A variable is a container for storing data/values.
  • Values are assigned at the beginning of the program.
  • It does not need to be declared with any particular type.
  • Type can be changed at any time, after they have been initialized at the beginning. (x = 5, after few line of code assign x = “Hello”, it is possible in Python)
  • Before assigning values to variables, it can be typecast to a specific type. (x = str(4))
  • Most importantly variables are case sensitive. (Msg = “Hello” and msg = “Hello” both are different variables)

Variable declarations (see below).

Python variable declarations
Python Variables Declaration
https://youtu.be/aRWq1UMYgXU
Python comments and variables - Learn Python in Tamil www.aryanz.co.in
Subscribe to out channel for more videos – https://bit.ly/aryanz-youtube
Python Syntax and Data types

Python Syntax and Data types

Python Syntax and Data types

Today we are going to see about Python Syntax and Data types which consist of the following

  1. Python Syntax
  2. Indentation in Python
  3. Best practices while writing Python program
  4. Data types (In build data types in Python)

Code Repo : https://git.io/JtUqQ

Slides : https://git.io/JtUZM

In case if you have missed our previous topics

  1. Python introduction in Tamil Part 1
  2. Python introduction in Tamil Part 2
  3. Writing your first python program and how to execute it?

Watch in youtube: https://youtu.be/ftaMRl8gdZ0

Learn Python in Tamil | பைதான் மொழியைக் கற்றுக்கொள்ளுங்கள் – Writing first program in Python and executing them using Python Interpreter

Syntax, Indentation and Best practice

Indentation is it really needed for Python?

Well to answer for it, Yes Its is very important for us to know about the indentation. because Python does not uses the curley braces ‘{‘ or ‘}’ for enclosing the statements. where as it used the indentations for it.

Key points to remember about Indentation

  • Giving space or tab space at beginning of a line, is called indentation.
  • In Python Indentation plays important role.
  • It uses the space to determine the block of statements.
  • The first line of Python code should not have indentation.(it will throw IndentationError)

Python coding best practices

Lets us see some best practices to be followed while writing Python, these best practices are followed so that your code does not end up having errors, easy to read and understand the code or the logic.

Python Indentation Rules

  • We can’t split indentation into multiple lines using backslash.
  • The first line of Python code can’t have indentation, it will throw IndentationError.
  • You should avoid mixing tabs and white spaces to create indentation. It’s because text editors in Non-Unix systems behave differently and mixing them can cause wrong indentation.
  • It is preferred to use white-spaces for indentation than the tab character.
  • The best practice is to use 4 white-spaces for first indentation and then keep adding additional 4 white-spaces to increase the indentation.

We will have another exclusive video coming up on the topic “Python coding best practices”.

Save the above file in any folder with the name helloworld.py

.py is the file extension used to identify the file is Python script

Python Data types

In Python we have the following in-built data types.

CategoryData typesNotes/Description
Text typestrString type, which is enclosed with double quotes
Example "Hello", "Python", "Programming"
Numeric typeint, float, complexnumbers, decimal and real numbers
Sequence/Collection typelist, tuple, rangeCollections, group of items.
Mapping typedictdictionary type which has key and value pair combination.
Example: {"virus_id":20190101, "virus_name":"COVID19", "isSpreadable":True}
Set typeset, frozensetSimilar to the list, just that it excludes any duplicates and it sorts the items using natural sorting order i.e., ascending order.
Boolean typeboolTrue or False its that simple.
Binary typebytes, bytearray, memoryviewFile reading and writing we can use the bytes or bytearrays.
memory view is to view the byte location in the memory.
Python in-built data types

Watch youtube video for Python datatype and syntax in tamil https://youtu.be/ftaMRl8gdZ0

Topics discussed in the Video:
1. Python Syntax
2. Indentation in Python
3. Best practices while writing Python program
4. Data types (In build data types in Python)
------------------------------------------------------------------
Demo code : https://git.io/JtUqQ
Slides : https://git.io/JtUZM

-------------------------------------------------------
Syntax, Indentation and Best practice
------------------------------------------------------
1) Giving space or tab space at beginning of a line, is called indentation.
2) In Python Indentation plays important role.
3) It uses the space to determine the block
of statements.
4) The first line of Python code should not have indentation.(it will throw IndentationError)

Python Indentation Rules

1) We can’t split indentation into multiple lines using backslash.
2) The first line of Python code can’t have indentation, it will throw IndentationError.
3) You should avoid mixing tabs and white spaces to create indentation. It’s because text editors in Non-Unix systems behave differently and mixing them can cause wrong indentation.
4) It is preferred to use white-spaces for indentation than the tab character.
5) The best practice is to use 4 white-spaces for first indentation and then keep adding additional 4 white-spaces to increase the indentation.
-------------------------------------------------------------------------------
Python Data types:

In Python we have the following in-built data types
----------------------------------------------------------------------
Data types                                       Category
str                                                    # Text Type
int, float, complex                         # Numeric Types
list, tuple, range                            # Sequence Types / Collection
dict                                                 # Mapping Type (Key, Value Pair)
set, frozenset                               # Set Types
bool                                                # Boolean Type True | False
bytes, bytearray, memoryview   # Binary Types

#Python #Syntax #Indentation #BestPractice #PythonDataTypes
https://bit.ly/aryanz-youtube
Subscribe to out channel for more videos – https://bit.ly/aryanz-youtube