Python 3 - A Comprehensive Guide
Python 3 - A Comprehensive Guide
Python, the brainchild of Guido van Rossum, is interpreted and not compiled. What do these
two fancy words mean? Now that’s a typical interview question pals.
● Compiler : Converts the whole code into machine language and gives the error at the
end. C++ is a compiler based language.
● Interpreter : Executes the code line by line. It shows the error as and when it meets it,
this makes debugging super easy. Python is a language that is interpreted.
Basics
➔ Note : Python takes indentation very seriously. Instead of using
curly brackets to mark blocks, it uses indentation (or a tab
space) to mark the beginning of a new block.
Print statements
Let’s start by doing our favorite thing, greeting the world.
print("Hello world")
# a use of input()
Variables
A variable can be thought of as an empty container that holds your information. Think of an
empty box. Now you want to keep the number 3 in it. How do you do this in python? Using
variables! We create a variable, assign it a number and we’re done.
Here we create a variable, assign it number 3 and then print the contents of the variable.
num = 3
print(num)
Data Structures
Now, let’s talk about the various important data structures available in python. What are data
structures? Well, they’re types of containers where you can store data. Just like boxes can be
big, small, straight, curvy, data structures can be varied.
1. Lists
Lists in Python are one of the most versatile collection object types available. The other two
types are dictionaries and tuples, but they are really more like variations of lists.
● Python lists do the work of most of the collection data structures found in other
languages and since they are built-in, you don’t have to worry about manually creating
them.
● Lists can be used for any type of object, from numbers and strings to more lists.
● They are accessed just like strings (e.g. slicing and concatenation) so they are simple to
use and they’re variable length, i.e. they grow and shrink automatically as they’re used.
● In reality, Python lists are C arrays inside the Python interpreter and act just like an array
of pointers.
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s
# Declaring a list
L = [1, "a" , "
string" , 1+2]
print L
# check again
print "xyz" in d
3. Tuple
Python tuples work exactly like Python lists except they are immutable, i.e. they can’t be
changed in place. They are normally written inside parentheses to distinguish them from lists
(which use square brackets), but as you’ll see, parentheses aren’t always necessary. Since
tuples are immutable, their length is fixed. To grow or shrink a tuple, a new tuple must be
created.
Here’s a list of commonly used tuples:
● () An empty tuple
● t1 = (0, ) A one-item tuple (not an expression)
● t2 = (0, 1, 2, 3) A four-item tuple
● t3 = 0, 1, 2, 3 Another four-item tuple (same as prior line, just minus the parenthesis)
● t3 = (‘abc’, (‘def’, ‘ghi’)) Nested tuples
● t1[n], t3[n][j] Index
● t1[i:j], Slice
● len(tl) Length
Decision statements
If statement
if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, condition after evaluation will be either true or false. if statement accepts boolean values –
if the value is true then it will execute the block of statements below it otherwise not. We can
use condition with bracket ‘(‘ ‘)’ also.
# Python program to illustrate If statement
i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")
If - else statements
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Loops
When you want to repeat your statements until a following condition is reached, you use loops.
For example, if you wish to print 0 to 100, you will need 8 minutes to write a print statement with
all the numbers, however, you will be able to write a loop to do the same in a minute!
While loop
# prints Hello Geek 3 Times
count = 0
while (count < 3):
count = count+1
print("Hello Geek")
For loop
# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s
Functions
A function is a set of statements that take inputs, do some specific computation and produces
output. The idea is to put some commonly or repeatedly done task together and make a
function, so that instead of writing the same code again and again for different inputs, we can
call the function.
Python provides built-in functions like print(), etc. but we can also create your own functions.
These functions are called user-defined functions.
# Driver code
evenOdd(2)
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s
evenOdd(3)
Recursive Functions
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called recursive function. Using recursive algorithm, certain problems
can be solved quite easily.
In the recursive program, the solution to the base case is provided and the solution of the bigger
problem is expressed in terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n -1);
}
In the above example, base case for n < = 1 is defined and larger value of number can be
solved by converting to smaller one till base case is reached.
The idea is to represent a problem in terms of one or more smaller problems, and add one or
more base conditions that stop the recursion. For example, we compute factorial n if we know
factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0.
# A Python 3 program to
# demonstrate working of
# recursion
def printFun(test):
test = 3
printFun(test)
Modules
A module is a file containing Python definitions and statements. A module can define functions,
classes and variables. A module can also include runnable code. Grouping related code into a
module makes the code easier to understand and use.
Import
# importing module calc.py
import calc
print add(10, 2)
File Handling
Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files.
# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s
Numpy
Numpy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays. It is the fundamental
package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional
container of generic data.
Basic operations
import numpy as np
# Defining Array 1
a = np.array([[1, 2],
[3, 4]])
# Defining Array 2
b = np.array([[4, 3],
[2, 1]])
Pandas
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data
structure with labeled axes (rows and columns). A Data frame is a two-dimensional data
structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame
consists of three principal components, the data, rows, and columns.
Creating a dataframe
# import pandas as pd
import pandas as pd
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s
import pandas as pd
# Create DataFrame
df = pd.DataFrame(data)
Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a
multi-platform data visualization library built on NumPy arrays and designed to work with the
broader SciPy stack. It was introduced by John Hunter in the year 2002.
Line plot:
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x,y)
Bar Plot
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s
y = [10, 5, 8, 4, 2]
Histogram
# importing matplotlib module
from matplotlib import pyplot a
s plt
# Y-axis values
, 8, 4, 2]
y = [10, 5
Scatter Plot
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
If you code daily, almost in a ritualistic manner, you will definitely become an expert. Your
competitive coding skills will also improve, which means you’ve got 25 L per annum starting
salary moving towards you (or that’s what everyone says!)
Thank you!
Happy Coding!
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s