The complete guide for Python and Django-Part1 Python

Note: In this tutorial, we will be using Python3 instead of Python2. The reason for this choice is that Python2 is slowly getting deprecated from the development world and the developers are developing new libraries strictly for the use with Python3.

Starting with Python3

Content:

  1. Installation
  2. DataTypes
  3. Comparison operators
  4. Control flow:
    1. IF ELIF and ELSE statements
    2. WHILE
    3. FOR loop statements
  5. Functions
  6. Object-Oriented Programming
  1. Installations:

Mac installation: https://docs.python-guide.org/starting/install3/osx/

Linux Installation: https://docs.python-guide.org/starting/install3/linux/

Windows Installation: https://docs.python.org/3/using/windows.html#installation-steps

2. Data Types:

Integer

In Python 3, there is effectively no limit to how long an integer value can be. Of course, it is constrained by the amount of memory your system has, as are all things, but beyond that an integer can be as long as you need it to be:

a = 123123123123123123123123123123123123123

Notice that we don’t have to specify the type of the variable ‘a’ in the above code. type of the variable will be dynamically handled by python on the basis of the value being stored in the variable.


Floating Point:

The float type in Python designates a floating-point number. float values are specified with a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specific scientific notation:

a=2.513
print( type(a) )

In the above code, the last line will print ‘float’ , which is the type of variable ‘a’.

Complex:

We need to import “cmath” to use this data type.

Let us look at the code below and try to understand how it works.

#importing cmath 
import cmath 

#initialising the variable 'z' with the value '2+3i'
z=complex(2,3)

#accessing the real part of variable 'z'
print("real part of z is: " + ,end="")
print(z.real)

#accessing the imag part of 'z'
print("imaginary part of z is: " + ,end="")
print(z.imag)

Sets:

Sets represent the mathematical notion of sets. Sets are mutable, iterable and don’t have any duplicate value. Python provides us, along with ‘set’ datatype, the mathematical functions associated with the sets such as intersection, union, difference, etc.

Let us look at the following code to understand the sets better.

#creating a set 'mySet' with values 1, 2 , and 3
mySet = set([1, 2, 3]) 
  
# Adding an element to mySet by the function 'add()' 
mySet.add(6) 

print("mySet") 
print(mySet) 

#creating another set with the name 'anotherSet'
anotherSet = set([3,4,5])


union_of_sets = mySet.union(anotherSet)

#this will print {1, 2, 3, 4 ,5 ,6}
print(union_of_sets)

intersection_of_sets = mySet.intersect(anotherSet)

#this will print the set {3}
print(intersection_of_sets)

difference_of_two_sets = mySet.difference(anotherSet)

#this will print {1, 2 , 6}
print(difference_of_sets)

Dictionary:

In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

# Creating an empty Dictionary 
Dict = {} 
print("Empty Dictionary: ") 
print(Dict) 
  
# Adding elements into the dictionary 
Dict[2] = 'alpha'
Dict[3] = 1

#this will print { 2: 'alpha'  , 3: 1}
print(Dict) 
  
# Updating existing Key's Value 
Dict[2] = 'Welcome'

the following line will print { 2: 'welcome'  , 3: 1}
print(Dict) 
  
# Adding Nested Key value to Dictionary 
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}} 
print("\nAdding a Nested Key: ") 
print(Dict) 

List:

A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc).


# creating a empty list
my_list = []


my_list = [1, 2, 3]

#overwriting the privious list [1 , 2 ,3 ] with the new list [1,"Hello",3.4]
my_list = [1, "Hello", 3.4]

#adding values to the list
my_list.append(5)

#now the new list is [1,"Hello",3.4, 5]
print (my_list)

my_list = ['a','b','c','d','e']

# Output: e
print(my_list[-1])

# Output: a
print(my_list[-5])

Negative indexing:

Tuple:

A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas, in a list, elements can be changed. In other words, tuples are immutable.

A tuple is created by placing all the items (elements) inside parentheses(), separated by commas. The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). Let us look at the following code to understand tuples in a better way:

# Empty tuple
myTuple = ()
print(myTuple)  # Output: ()

# Tuple having integers
myTuple = (1, 2, 3)
print(myTuple)  # Output: (1, 2, 3) 

# tuple with mixed datatypes
myTuple = (1, "Hello", 3.4)
print(myTuple)  # Output: (1, "Hello", 3.4)  

# nested tuple
myTuple = ("mouse", [8, 4, 6], (1, 2, 3))

# Output: ("mouse", [8, 4, 6], (1, 2, 3)) 
print(myTuple)

A tuple can also be created without using parentheses. This is known as tuple packing. For instance:

my_tuple = "Hello", 1.2, 6
print(my_tuple)   # Output: "hello", 1.2, 6 

Tuple unpacking is also possible

my_tuple = "Hello", 1.2, 6

# unpacking the tuple
a, b, c = my_tuple

print(a)      # 3
print(b)      # 4.6 
print(c)      # dog 

Strings:

Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Slicing in a string:

String1 = "PythonIsFun"
  
print(String1) 

# Printing 3rd to 12th character  using slicing
print("\nSlicing characters from 3-12: ") 
print(String1[3:12]) 
  
# Printing characters between  
# 3rd and 2nd last character 
print("\nSlicing characters between " +
    "3rd and 2nd last character: ") 
print(String1[3:-2]) 

Boolean

The bool() method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.

x=1
y=2
z=bool(x==y) #this statement will assign False to z as x is not equal to y

x=True
print( bool(x)) #this statement will print 'True' as x is true

x=None
print( bool(x)) #this statement will print 'False' as x is None

x={}
print( bool(x)) #this statement will print 'False' as x is None
#using bool() to find if the number is less than 5 or not
num=7
if(bool(num<5)):
    print('num is less than 5')
else:
    print('num is not less than 5')

3. Comparison Operator/Relational Operators

Comparison operators are used to compare the two values and establish a relationship between them. The expression always evaluates to True or False.

These are the following types of comparison operators used in Python3:

  • == (equal to)
  • != (not equal to)
  • < (less than)
  • > (greater than)
  • >= (greater than or equal to)
  • <= (less than or equal to)


a = 21
b = 10

# '==' operator 
if ( a == b ):
   print ("a is equal to b")
else:
   print ("a is not equal to b")

# '!=' operator
if ( a != b ):
   print ("a is not equal to b")
else:
   print ("a is equal to b")

# '<' operator
if ( a < b ):
   print ("a is less than b" )
else:
   print ("a is not less than b")

# '>' operator
if ( a > b ):
   print ("a is greater than b")
else:
   print ("a is not greater than b")


#swapping of values
a,b = b,a 

# '<=' operator
if ( a <= b ):
   print ("a is either less than or equal to  b")
else:
   print ("a is neither less than nor equal to  b")

# '>=' opeartor
if ( b >= a ):
   print ("b is either greater than  or equal to b")
else:
   print ("b is neither greater than  nor equal to b")

4. Control Flow

(a) IF ELIF ELSE

Syntax:

if expression:
   statement(s)
elif expression:
   statement(s)
else:
   statement(s)

We can add as many elif as we want in-between if and else block. The count of elif blocks can also be zero. In that case, the else block will immediately follow the if block.

The following code illustrates the use of if elif and else

amount = int(input("Enter amount: "))

if amount<1000:
   discount = amount*0.05
   print ("Discount",discount)
elif amount<5000:
   discount = amount*0.10
   print ("Discount",discount)
else:
   discount = amount*0.15
   print ("Discount",discount)
    
print ("Net payable:",amount-discount)

Output:

Enter amount: 3000
Discount 300.0
Net payable: 2700.0

(b) WHILE LOOP

In Python, while loops are constructed like so:

while [a condition is True]:
    [do something]

The something that is being done will continue to be executed until the condition that is being assessed is no longer true.

Here is the code to illustrate the use of a while loop:

count = 0
while (count < 3):     
    print(count)
    count = count + 1

Output:

0
1
2

(c) FOR LOOP

Syntax:

for iterator_var in sequence:
    statements(s)

Let us look at the following code to see understand the for loop better:

s = "HelloWorld"
for i in s : 
    print(i) 

Output:

H
e
l
l
o
W
o
r
l
d

Here is another piece of code to traverse the dictionary

print("\nDictionary traversal")    
d = dict()  
d['first'] = 100
d['second'] = 200
for i in d : 
    print("%s  %d" %(i, d[i]))

Output:

first  100
second  200

5. Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Here is a syntax to declare a function:

def function_name( parameters ):
   #some statements
   return [expression] #the return statement is optional

For example, let us create a simple function which computes the sum of two values which are passed to it (as a parameter). We will name that function ‘sum’.

def sum(x , y):
    ans=x+y
    return ans

Calling the defined function

We can call the defined function, like the above , as follows:

result = sum(4, 5) # the function 'sum' will return 9 which will be stored in 
                   # the variable 'result'  
print(result)      # this statement will print '9'

Output:

9

6. Object-Oriented Programming / OOP

To understand OOP, we need to understand what is class and object.

Classes are like a blueprint or a prototype that you can define to use to create object.

We define classes by using the class keyword, similar to how we define functions by using the def keyword.

Learn about advantages of python over other leading languages

Syntax:

class Class_name:
    # statements to define data members and methods of this class 

Let us create an empty class ‘Person’ for now.

class Person():
    pass

Important terms related to Class:

  • The Constructor Method: This is the method that executes first when we create a new instance of that class. We always have to name this function as ‘__init__‘.
class Person():
    def __init__(self):
        print('This is the constructor method')
  • Self: The argument to the __intit__ () functions is the keyword ‘self‘, which is a reference to objects that are made based on this class. To reference instances (or objects) of the class, self will always be the first parameter, but it need not be the only one.
  • Methods: Method is a special kind of function that is defined within a class. A class can have any number of methods. __init__() is also one of the methods.
  • Attributes: Attributes are data stored inside a class or instance and represent the state or quality of the class or instance. In short, attributes store information about the instance.

Let us add two attributes ‘name’ and ‘age’ to our class ‘Person’. We can do that using the __init__() function. Here is the code:

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

Now, as the __init__() function is receiving ‘name’ and ‘age’ attribute, it becomes compulsory to pass the name and age while creating the instance /object ‘Person’ object. This is how we can create an object of class Person

#Creating the Person 'p' with the name 'Susan' and age 22
p=Person('Susan' , 22)
print(p.name)
print(p.age)

As we can notice from the above code, we can access the attributes associated with the object using the . operator.

Let us now add a method to our class ‘Person’ which increments the age of that person by one.

We will call that method ‘IncreaseAge()’.

class Person():
    def __init__(self, name , age):
        self.name=name
        self.age=age
    def IncrementAge(self ):
        self.age= self.age+1;
        
p=Person('Susan' , 22)
print('The age before calling the method IncrementAge')
print(p.age)

print('The age after calling the method IncrementAge')
p.IncrementAge();
print(p.age)

Output:

The age before calling the method IncrementAge
22
The age after calling the method IncrementAge
23

Inheritance in classes

Inheritance is one of the mechanisms to achieve the same. In inheritance, a class (usually called superclass or Base Class) is inherited by another class (usually called subclass or Derived Class). The subclass adds some attributes to a superclass.

Let us understand it by extending our Person class by creating a Student class. A student is also a person with a name and the age but also has some additional properties such as roll number.

So basically, the Student class will inherit the ‘name’ and ‘age’ attribute from its base class which is Person.

This is the code to illustrate the concept of inheritance:

class Person():
    def __init__(self, name , age):
        self.name=name
        self.age=age
    def IncrementAge(self ):
        self.age= self.age+1;


#the Student class inherits the Person class
class Student(Person):
    def __init__(self,name , age ,RollNo ):
        Person.__init__(self , name , age)
        self.rollNumber= RollNo
    


print("student's information")

s=Student('Madara' , 10 , 123)
print(s.rollNumber)
print(s.name)
print(s.age)
s.IncrementAge()
print(s.age)

Output:

student's information
123
Madara
10
11

Notice that, the Student class has acquired the ‘name’ and ‘age’ property from the Person class. The ‘IncrementAge()‘ method can also be used with the Student object.

Part 2 of this article will be published soon.

Leave a Comment

Your email address will not be published. Required fields are marked *