Python Documentation


Python indentation
Python is an interpreter, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python’s design philosophy emphasizes code readability with its notable use of significant whitespace

 Python Variables
 Python Data types
 Python Operators
 Python Namespace
 Python If else
 Python for Loop
 Python While Loop
 Python break and continue
 Python pass
 Python Function
 Python Argument
 Python Modules
 Python Package
 Python Number
 Python List
 Python Tuple
 Python Strings
 Python Set
 Python Dictionary
 Python Exception
 Python Object & Class
 Python Date & Time

Python Variable
A variable is a named location used to store data in the memory. It is helpful to think of variables as a container that holds data which can be changed later throughout programming.
Note: In Python, we don’t assign values to the variables, whereas Python gives the reference of the object (value) to the variable.

Python Data type
Every value in Python has a data type. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex class in Python.
Ex: a = 2
>>> 2
b = 3.5
>>> 3.5
C = 1+2j
>>> 1+2j
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
Ex: >>> 2+3
Arithmetic operation
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.
Add two operands or unary plus X + Y
Subtract right operand from the left or unary minus X - Y
Multiply two operands X * Y
Divide left operand by the right one (always results into float) X / Y
Modulus-remainder of the division of left operand by the right X%y
Exponent - left operand raised to the power of right X ** Y

Python If else
An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else statement following if.
Syntax for if else
If expression:

Python for Loop
The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary.
Syntax of for loop
for iterating_var in sequence

                                                                              if no item is left in
                                                                                the sequence

                                                                  Next item

I = 1
n=int(input(“Enter the number up to which you want to print the natural num?”))
for i in range(0,10)
print(I,end = “”)
output: 0 1 2 3 4 5 6 7 8 9

Python while Loop
The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed as long as the given condition is true.
It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.
Syntax of for loop
While expression:

                                                                     if condition is false

                                                       If condition is true                                                                                                              

while i<=10:

output : 1 2 3 4 5 6 7 8 9 10

Python break statement
The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. In other words, we can say that break is used to abort the current execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.
Syntax of the break
list =[1,2,3,4]
Count = 1;
for i in list:
if i == 4:
print(“item matched”)
count = count + 1;
print(“found at”,count,“location”)
item matched
found at 2 location

Python continue statement
The continue statement in python is used to bring the program control to the beginning of the loop. The continue statement skips the remaining lines of code inside the loop and start with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular condition.
Syntax of the break
i = 0;
while i!=10:

Python Pass
In Python, pass keyword is used to execute nothing; it means, when we don’t want to execute code, the pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by without executing any code. If we want to bypass any code pass statement can be used.
Syntax of the pass
for i in [1,2,3,4,5]:
if i==3:
print “Pass when value is”,i
print i,
output >>>
1 2 Pass when value is 3
3 4 5
Python Function
Functions are the most important aspect of an application. A function can be defined as the organized block of reusable code which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the python program.
In other words, we can say that the collection of functions creates a program. The function is also known as procedure or subroutine in other programming languages.
Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions which can be called user-defined functions.
Advantage of functions in python
There are the following advantages of C functions.
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call python functions any number of times in a program and from any place in a program.
We can track a large python program easily when it is divided into multiple functions.
Reusability is the main achievement of python functions.
However, Function calling is always overhead in a python program.
Syntax of the function
def hello_world():
print(“hello world”)

Python Argument
The Python supports the programs that can be run on the command line, complete with command line arguments. It is the input parameter that needs to be passed to the script when executing them.
It means to interact with a command-line interface for the scripts.
It provides a get opt module, in which command line arguments and options can be parsed.
Syntax of the Argument

                             >python hello
                               Argument:  hello

                             >python hello world
                               Argument:  hello
                               Argument:  world

Python Module
A python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.
Syntax of the Module
In this example, we will create a module named as which contains a function func that contains a code to print some message on the console.
Let’s create the module named as

             def displayMsg(name)  
                   print("Hi "+name); 

Python Package
Packages are a way of structuring many packages and modules which helps in a well-organized hierarchy of data set, making the directories and modules easy to access. Just like there are different drives and folders in an OS to help us store files, similarly packages help us in storing other sub-packages and modules, so that it can be used by the user when necessary.
Syntax of the Package
def greet(name,msg):
“”“This function greets to
the person with the provided message”""
print(“Hello”,name + ', ’ + msg)
greet(“Monica”,“Good morning!”)
Hello Monica, Good morning!
Python Number
Python supports integers, floating point numbers and complex numbers. They are defined as int, float and complex class in Python.
Integers and floating points are separated by the presence or absence of a decimal point. 5 is integer whereas 5.0 is a floating point number.
Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class.
Syntax of the Number
a = 5
# Output: <class ‘int’>
# Output: <class ‘float’>
# Output: (8+3j)
c = 5 + 3j
print(c + 3)
# Output: True
print(isinstance(c, complex))
Python List
In Python, list is a type of container in Data Structures, which is used to store multiple data at the same time. Unlike Sets, the list in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility.
Syntax of the Number
List =[0, 1, 2, 3, 4, 5]
0 1 2 3 4 5
0 1 2 3 4 5

              -6       -5        -4       -3        -2        -1


                              List = [1, 2, 3, 4, 5, 6]   
                              List[2] = 10;  
                              List[1:3] = [89, 78]   
                            [1, 2, 3, 4, 5, 6]
                            [1, 2, 10, 4, 5, 6]
                            [1, 89, 78, 4, 5, 6]

Python Tuple
Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists since the value of the items stored in the list can be changed whereas the tuple is immutable and the value of the items stored in the tuple can not be changed.
A tuple can be written as the collection of comma-separated values enclosed with the small brackets. A tuple can be defined as follows.
Syntax of the Tuple
tuple1 = (10, 20, 30, 40, 50, 60)
count = 0
for i in tuple1:
print(“tuple1[%d] = %d”%(count, i));
(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[0] = 20
tuple1[0] = 30
tuple1[0] = 40
tuple1[0] = 50
tuple1[0] = 60
Python String
Till now, we have discussed numbers as the standard data types in python. In this section of the tutorial, we will discuss the most popular data type in python i.e., string.
In python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax of the String
str = “HELLO”
str = “hello”
Python Set
The set in python can be defined as the unordered collection of various items enclosed within the curly braces. The elements of the set can not be duplicate. The elements of the python set must be immutable.
Unlike other collections in python, there is no index attached to the elements of the set, we cannot directly access any element of the set by the index. However, we can print them all together or we can get the list of elements by looping through the set
Syntax of the Set
Days = {“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”}
print("looping through the set elements … ")
for i in Days:
{‘Friday’, ‘Tuesday’, ‘Monday’, ‘Saturday’, ‘Thursday’, ‘Sunday’, ‘Wednesday’}
<class ‘set’>
looping through the set elements …
Python Dictionary
Dictionary is used to implement the key-value pair in python. The dictionary is the data type in python which can simulate the real-life data arrangement where some specific value exists for some particular key.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any python object whereas the keys are the immutable python object, i.e., Numbers, string or tuple.
Syntax of the Dictionary
Employee = {“Name”: “John”, “Age”: 29, “salary”:25000,“Company”:“GOOGLE”}
print("printing Employee data … ")
<class ‘dict’>
printing Employee data …
{‘Age’: 29, ‘salary’: 25000, ‘Name’: ‘John’, ‘Company’: ‘GOOGLE’}

Python exception
An exception can be defined as an abnormal condition in a program resulting in the disruption in the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code is not executed. Therefore, an exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can be executed without any disruption. However, if we do not handle the exception, the interpreter doesn’t execute all the code that exists after the that.
Common Exceptions
A list of common exceptions that can be thrown from a normal python program is given below.
ZeroDivisionError: Occurs when a number is divided by zero.
Name Error: It occurs when a name is not found. It may be local or global.
Indentation Error: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet operations are being performed.

Python Objects & Class
As we have already discussed, a class is a virtual entity and can be seen as a blueprint of an object. The class came into existence when it instantiated. Let’s understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the floor, doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the building can be seen as a class, and we can create as many objects of this class.
On the other hand, the object is the instance of a class. The process of creating an object can be called as instantiation.
Syntax of the objects & class
class Employee:
id = 10;
name = “ayush”
def display (self):
Python Date & time

      In Python, date, time and datetime classes provides a number of function to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. Whenever you manipulate dates or time, you need to import datetime function.

The datetime classes in Python are categorized into main 5 classes.
date – Manipulate just date ( Month, day, year)
time – Time independent of the day (Hour, minute, second, microsecond)
datetime – Combination of time and date (Month, day, year, hour, second, microsecond)
timedelta— A duration of time used for manipulating dates
tzinfo— An abstract class for dealing with time zone