Chapter 4: Introduction to Python Programming.
Python is the most popular and most widely used scripting language . Its syntax is easy to use and is written to make coding easy.
4.1: Python Installation
Step 1: Go to https://www.python.org/downloads/ and download the latest Python version available.
Step 2: Click on Customize installation.
For your Python download, it is important to give your own desirable path location which is short and easy to remember. This is because we will be using this path location again for Django installation .
Step 3: Click Next
Step 4: Then browse for your install location.
Step 5: C lick install
Step 6: Now go to Control panel -> System and Security -> System -> Advanced system settings -> Environment Variables -> Add Python Installation location into your PATH variables.
Step 7: Open command prompt and with the help of python command check whether installation is done correctly or not.
Now let’s code..
Open Notepad++ and create a new file (hello_world ) and save the file with .py extension
Inside hello_world.py file , write one line of code:
What is print( ) function in Python?
Print( ) function displays the output to the screen
Now let’s run the Python file.
Open command prompt -> Go the hello_world.py file location and write the following command:
python file_name .py
4.2 : Python variables, Datatypes & Operators
Important points to note are:
But in Python, you do not have to declare the data type of a variable. Python understands the data type of any variable simply from its value.
Let us consider the example below:
Output
When we run the above piece of code, Python shows the data types of variable x , y and z .
What is type( ) function?
type( ) function is used to determine the data type of a variable.
Apart from data types like int , float and string , Python also has list , tuple and dictionaries .
4.2.1 : Python String
Important points to note are:
What is String Slicing in Python?
Python String slicing is the process of obtaining a sub string of the given string.
Syntax:
string [ index_number_start (including its value) : index_number_stop (excluding its value) ]
Example:
Open Notepad++ and create a new python file and write the following lines of code.
Now run the above piece of code:
Code explanation:
Let’s look into the message “Health is wealth”.
Index number always starts from 0. Letter H is present at index number 0, letter e is present at index number 1, letter a is present at index number 2, letter l is present at index number 3, letter t is present at index number 4, letter h is present at index number 5. Then whitespace is present at index number 6. Letter i is present at index number 7, letter s is present at index number 8. Then again whitespace is present at index number 9. Letter w is present at index number 10, Letter e is present at index number 11, Letter a is present at index number 12, Letter l is present at index number 13, Letter t is present at index number 14, Letter h is present at index number 15.
In the above piece of code, the output of message[2:12] is : print values from 2 (including its value at index position 2) to 12 (excluding its value at index position 12) alth is we
The output of message[:6] is : print values from start (index position 0, including its value) to 6 (excluding its value at index position 6) Health
The output of message[7:] is : print values from 7 (including its value at index position 7) to end is wealth
To print letters or values from the end of a string, minus sign is used. For example: message[-1] will return h , message[-2] will return t and so on.
Important and commonly used String methods
  1. len( ) function returns the length of the string.
Syntax: len(string)
  1. lower( ) function returns the string with lower case characters.
Syntax: string.lower()
  1. upper( ) function returns the string with upper case characters.
Syntax: string.upper()
  1. strip( ) function gets rid of left or right whitespace.
Syntax: string.strip()
  1. lstrip( ) function gets rid of left whitespace.
Syntax: string.lstrip()
  1. rstrip( ) function gets rid of right whitespace.
Syntax: string.rstrip()
  1. index( ) function returns the index number of the given element.
Syntax: string.index(element )
Output:
  1. split( ) function returns the list of substrings separated by whitespace.
Syntax: string.split( )
Output:
  1. replace(old,new) function replaces the old with new.
Syntax: string.replace(old,new)
Output:
  1. join( ) string method returns a string by joining all the elements of an iterable (lists, tuples and string) with the delimiter.
Syntax: delimiter.join(iterable)
Output:
 
String formatting
format( ) method is used to format a string.
Rules for string formatting:
  1. Create a placeholder with the help of curly brackets {}.
  2. Call the format method and pass variables as parameters. When program executes, the values passed to these parameters will replace the curly brackets placeholders.
Example 1:
In the above example, the values passed to variable animal will fill the first placeholder and the value passed to variable legs will fill the second placeholder.
Output:
Example 2:
If you want to display a float number with two digits after the decimal dot, formatting expression {:.2f} is used.
Output:
4.2.2 : Python List
     A Python List is very similar to an Array . It contains a list of elements separated by commas and its elements are written with square brackets [ …. ] .
     Python list are mutable meaning that we can modify list elements.
     A value from a List can be accessed from its index value.
Syntax for accessing the values from a List is:
List_name [ index_num ]
What is an Array?
An Array is a collection of items or elements all having the same datatype. An element from an array can only be accessed from its index value. Example:
Let’s create an array of cars.
cars = [“Kia”, “Toyota”, “Ford”, “Tesla”]
In order to get the value Ford as output, we need to write  print ( cars [ 2 ] )
Example:
Create a new Python file (variables.py ) and write the following lines of code:
After running the above piece of code, we get an output of:
Code explanation:
     In the above piece of code, fruits is a List containing 6 elements. The value at position 0 is “apple ”, at position 1 is “orange ” and so on.
     x is a variable holding a string value. The value at position 0 is “t” , at position 1 is “h ” and so on.
     len( ) function is used to get the length of the list .
     In Line 4 and 5 we are performing Slicing operation .
Output: [‘banana’, ‘mango’]
Output: is app
Important and commonly used List methods
  1. append( ) method inserts the element at the end of the list.
Syntax: list.append(element )
Output:
  1. insert( ) method inserts an element at the specified index number.
Syntax: list.index(index_num , element )
Output:
  1. remove( ) method removes the first occurrence of element specified.
Syntax: list.remove(element )
Output:
4.2.3 : Python Tuple
     A Tuple is very much like a List . It contains elements separated by commas within open and close parenthesis ( …. ) .
     Python tuple are immutable meaning once a tuple is declared, it cannot be modified.
Difference between Tuple and List
Tuple
List
Tuple contains elements within (… ) parenthesis
List contains elements within [ …] square brackets
Once a tuple is created, no item can be added, updated or deleted
List gives us the ability to add, update and delete items.
Example:
After running the above piece of code, we get an output of:
Code explanation:
del ( ) function is used to delete element from a certain position. When applying delete function to fruits list , the value at position 1 (orange ) was deleted successfully. But in case of tuple , when we tried to delete an element at position 2, it threw an error.
What is unpacking a tuple mean?
When we create a tuple and assign new values into it. This is called packing a tuple.
When we extract those values and store them into a variable. This is called unpacking a tuple.
Output:
4.2.4 : Python Dictionary
Example:
After running the above piece of code, we get an output of:
Important Dictionary operations and methods
  1. Now let’s insert some new records.
To insert new records into the dictionary, the syntax is:
dictionary_name [ key ] = value
Output:
  1. Update a record
To update a record, the syntax is same as insert a new record.
Output:
In the above piece of code, we see the new value (70 ) assigned to key John replaces the old value (95 ).
  1. Delete a record
To delete a record from a dictionary, del keyword is used. Syntax:
del dictionary_name [ key ]
Important Dictionary Methods:
1. To iterate through dictionary, items( ) method is used. Syntax: dictionary.items( ) (example present in chapter 5 )
2. To display only dictionary keys, key( ) method is used.
Syntax: dictionary.keys( )  
3. To display only dictionary values, values( ) method is used.
Syntax: dictionary.values( ).
4.2.5 : Python Operators
Commonly used Arithmetic operators
Operator
Description
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus. This sign returns the remainder.
**
Exponentiation. For example: 2 ** 3 means 2 to the power of 3 and that is equal to 8
//
Floor division. This operator returns only the whole integer number. For example: 23 // 2 will give 11
Commonly used Comparison Operators
Operator
Description
= =
Equals: x = = y
!=
Not Equals: x != y
<
Less than: x < y
<=
Less than or equal to: x <= y
>
Greater than: x > y
>=
Greater than or equal to: x >= y
Commonly used Logical Operators
Operator
Description
and
Example:
x = 123 and y = “John” executes certain block of code if both statements are TRUE
or
Example:
x = 123 or y = “John” executes certain block of code if one of the statements is TRUE
in
Example:
x = [ 123 , 345 ]
if 123 in x returns TRUE, then executes certain block of code
not in
Example:
x = [ 123 , 345 ]
if 12 not in x returns TRUE, then executes certain block of code
Commonly used Assignment Operators
Operator
Description
=
Example: x = 2, this means value 2 is assigned to x
+=   
(x += 1)
This is same as x = x + 1. If value of x = 3, then the new value of x is 3 + 1 = 4
-=    
(x -= 2)
This is same as x = x – 2. If value of x = 5, then the new value of x is 5 – 2 = 3
*=   
(x *= 5)
This is same as x = x * 5. If value of x = 2, then the new value of x is 2 * 5 = 10
/=    
(x /= 2)
This is same as x = x / 2. If value of x is 10, then the new value of x is 10 / 2 = 5
%=
(x %= 2)
This is same as x = x % 2. If value of x is 10, then the new value of x is 10 % 2 = 0
4.3 : Python Control Statements
The concept of control statements in Python is similar to any other programming languages but it has some minor differences. They are:
  1. The syntax is different.
  1. In other programming languages, the control statements block of codes is written within curly braces { …}, whereas in Python, indentation marks the beginning and end of a block of code.
4.3.1 : Python If ..Elif ..Else
The syntax is:
if condition :
……..
elif condition :
……..
else :
…………
Execution flow:
Example 1:
Create a new Python file (test.py ) and write the following lines of code:
Python Indentation Explanation:
Now let’s run the above piece of code.
Open command prompt -> navigate to the Python file location and run the script using python command.
Output
In the above Python code, fruits is a List of 4 elements. Since the value at position 1 is indeed “orange ”, the if statement is satisfied and the elif and else block of code are not checked anymore.
Example 2:
Code explanation:
The Line 2 of the above piece of code checks whether there is value present in stocks List or not. If TRUE, execute the if block of code, else execute the else block of code.
Output
4.3.2 : Python For Loop
Important points to note are :
cars = [“Kia”, “Toyota”, “Ford”]
The length of the above cars list is 3, so the loop will go on for 3 times.
First it will take the element at index number 0 (“Kia ”) and perform the checking operation by traversing down the loop -> then it will check the element at index number 1 (“Toyota ”) and perform the checking operation by traversing down the loop -> then it will check the element at index number 2 (“Ford ” ).
The syntax is:
for each_element in elements :
………
Execution flow of for loop:
Example:
Create a new Python file (loops.py ) and write the following lines of code:
After running the above piece of code, we get an output of:
Important points to note are:
  1. colon( : ) marks the beginning of the block of codes.
  1. After initiating the for loop, we gave an indentation and then started our if loop. That one indentation signifies that the if block of code belongs to the for loop.
Now within if block of code, I gave two indentation to signify that the line  print("I wish to own tesla one day") belongs to if statement which in turn belongs to the for loop.
We followed the same above process for elif and else block of codes.
  1. The loop will go on till the length of the List car . The length of the above List is 4, so the loop will happen 4 times.
Execution flow of the above piece of code:
Nested for loop
Nested for loop means that a for loop is present within a for loop.
Output:
Code explanation:
In the above piece of code we created a list of groceries and stored it in a variable groceries . The list is a collection of mini lists.
In line for record in groceries: , we capture the mini lists. Then in line for grocery_item in record: we loop and get the grocery items present in the mini list.
4.3.3 : Python While loop
while loop keeps on executing a block of code as long as the condition is true.
The syntax is :
while condition :
……..
Example:
Code explanation:
     In Line 1 , we declared the value of variable x .
      In Line 2 , the while loop is initiated.
Since the value of x is less than 100, then the while loop condition is satisfied and the print statement at Line 3 executes.
     In Line 4 , we increment the value of x by 10 and assign that increment value back to variable x . The while loop starts again with the incremented value and goes on unless and until the value of x becomes equal to or less than 100.
Now let’s run above piece of code.
NOTE: In while loop it is very important to initialize a variable and then increment the variable as we did in the above example. If proper initialization and incrementation is not done, the while loop will keep on looping and will not stop.
4.3.4 : Python Break and Continue
Python Break and Continue statements are used to alter the normal flow of a loop.
Break
Break statements are used to break out of a loop if certain condition is satisfied.
Example:
In the above example, the for loop will go on until the if condition is satisfied. Once the if condition is satisfied the execution will stop because it will encounter the break statement.
Now let’s run the above piece of code,
Continue
When a certain condition executes the Continue statement, the control returns to the beginning of the loop and skips the rest of the code.
Note that the loop does not get terminated.
Example:
In the above piece of code, you will notice that once the continue statement was encountered, the code at Line 9 was not printed and the control moved back to the beginning of the loop.
Now let’s run the above piece of code,
Except “Tesla” , all other values were printed.
4.4 : Python functions.
Functions are block of codes performing certain task. The syntax for declaring a function is:
def function_name ( ) :
……..
Code Explanation:
Output
4.5 : Python class
      Python is an object oriented programming language .
     A class is a “blueprint” for creating an object and like any other programming language Python class contains attributes and methods.
class class_name :
def __init__(self) :
….
def method1 :
….
What is def __init__ (self)?
“__init__” is a reserved method in Python classes initializing the object ’s state. In Object Oriented concepts, it refers to the constructor of the class . This method initializes the attributes of a class when an object is created.
Output:
Important points to note from the above piece of code are:
  1. A Python Class name should start with a capital letter.
  1. Within the __init__method we declared different attributes of our class Employee and passed those values to self . id_num , self . name and so on.
  1. In our validation ( ) method we pass the argument self which helps to access all the attributes of the class Employee .
  1. str( ) function helps to convert an integer value to a string value.
  1. and keyword is the logical and operator in Python.
  1. In line 15 of our above code, we declared an object e and passed values into it.
Please note: In this chapter, I have covered only few important Python topics essential for the development of our Django project. To gain in-depth and through knowledge of all Python topics, please visit website https://www.w3schools.com/