Blog Python Tutorial For Beginners A Complete Guide
Blog Python Tutorial For Beginners A Complete Guide
Ho me Business Analyt ics Analyt ics Tut o rials Pyt ho n Tut o rial Fo r Beginners – A Co mplet e
Guide | Learn Pyt ho n Easily
Business Analytics Analytics Tutorials Artificial Intelligence Data Science Videos Data Science Videos
1. What is Python?
4. Why Python?
5. R vs. Python
11. Comments
12. Variables
13. Operators
22. Lambda
23. Arrays
24. Classes
25. Inheritance
26. Iterators
27. Scope
28. Modules
29. Dates
31. JSON
33. PIP
Learn the high demand technologies in a world-class learning platform for free
What is Python ?
Contributed by – python.learning
Web Development
Internet of Things
For the sake of simplicity, let us consider the Internet of T hings to be the
‘physical objects connecting an embedded system to the internet’. It plays a
vital role in projects that involve big dat a, machine learning, dat a
analyt ics, wireless dat a net works, and cyber-physical syst ems. IoT
projects also deal with real-time analytics.
Everything Python
Let’s help you explore Python more!
OR
Machine Learning
If you are a Windows user and if you have installed Python using Anaconda
distribution package which is available at Anaconda.org, you need to go to
“Download Anaconda” and then download the latest version f or Python 3.6.
Once you download this, it is a pretty simple and straightf orward process to
f ollow, and you will have Python installed f or you. T he next step is to power up
an IDE to start coding in Python.
So once you install Python, you can have multiple IDEs or text editors on top of
your Python installation.
For text editors, you can use something like Sublime or Notepad++. If you are
comf ortable using an Integrated Development Environment, then you can use
Jupyter. Also, there are other options like Wingware, Komodo, Pycharm, and
Spyder.
Python is also very easy to integrate with other platf orms and other
programming languages. It has a common object-oriented programming
architecture wherein existing IT developers, IT analysts, and IT programmers
f ind it very easy to transition to the analytics domain.
Because the structure of coding in Python is object-oriented programing
architecture, it has excellent documentation support.
R vs Python?
Read more about the dif f erence between R and Python, and which is a better
alternative.
One would require 6-8 weeks to learn the basics of Python. T his will include
learning the syntax, key-words, f unctions and classes, data types, basic coding,
and exception handling.
Advanced Python skills are not necessary f or all Python prof essionals.
Depending on the nature of your work, you can learn skills such as database
programming, socket programming, multithreading, synchronisation techniques
etc.
Read our blog on top 50 interview questions f or Python to test your knowledge.
It will give you an idea about how much you know about Python and what else is
there to learn.
2. PyCharm
3. T honny
4. Atom
5. Jupyter
6. Komodo
7. Wingware
1. Open the Anaconda prompt. T his is available to you if you have done the
installation through the Anaconda installer.
2. Once you open the Anaconda Command Prompt, you will see a def ault path
assigned to you. T his is the username f or the computer that you are using.
3. Add the f older paths to this def ault path (e.g., cd Desktop → cd Python),
where you want to open the notebook
4. Once you set the path, add the Jupyter notebook using the command
jupyt er not ebook
5. Hit enter. T his will open the notebook in your local host, i.e., your system
6. T he path described in the Anaconda prompt will now come on your jupyter
notebook home page
T here are multiple options on the toolbar, i.e., File, Edit , View, Insert , Cell,
Kernel, Widget s and Help. Let us have a look at some of the f eatures and
f unctionalities one by one.
File Options
Download as – T here are dif f erent ways in which you can download a Jupyter
Notebook. First is the Classic Notebook, which is the ipynb extension. Bef ore
being called a jupyter notebook, it was an Ipython notebook. T hat is why this
extension.
T hen you have your .py extension. Save the f ile with .py extension, and you can
import the same to a dif f erent IDE f or easier use.
Close and Halt – T his command closes whatever kernel is running at this
particular point in time and halts all the processes.
Edit Options
It includes Cut Cells, Copy Cells, Past e, Delet e, Split t ing a Cell, Moving up,
down, so on and so f orth.
Cells are nothing but the code that you type in the dialogue box present on the
window. T his is a cell, where you type in your code — each cell when run will give
you an output.
T o run this particular piece of code, you can either click the specif ic option
which says, Run cell or the shortcut key f or the same is Shift + Ent er.
If you want to explore the other available shortcut options, you can get under
Help in Keyboard Short cut s.
You can cut these cells, paste them later on. You can merge, split, so
on and so forth. T hese are simple items.
View Options
You can T oggle your Headers, T oolbars, and Line numbers as well.
Insert Options
T hese are basic insert operations. You can insert a cell above or below as per
the requirement of your code.
Cell Options
If you hit Run All, it runs all the cells that are present in this entire workbook.
When you click ‘Run All Above’, it runs all the cells above the selected cell.
Similarly, if you click ‘Run All Below’, it runs all the cells that are below the
selected cell.
T he dif f erent types of cells, i.e., Code, Markdown and Raw Convert Files.
One exciting f eature that we will be using much in our code f iles is something
called Markdown f ile. A markdown is nothing but converting whatever you have
typed in a cell into a text message.
T he cells that you have converted as a Markdown will not be run or considered
as a line of code. When you run this cell, it is taken as a text f ield, and the
output is text too. No computation is carried out on this cell.
Help Options
Here you can see the usual libraries and packages that are available.
You can click on these options, and it will open a guidebook or the ref erence
book, where you can have a look at the various methods that are available
within the selected package.
T here are various other options you can experiment with when you are working
with Jupyter.
Comments
Comments are usef ul to describe the program logic and purpose of various
modules. People other than the coder can understand the code by looking into
the meaningf ul comments.
While testing the program, comments can be used to disable portions of code
and are excluded f rom execution.
Python comment starts with the # symbol. T he comment may be its own or
the comment may start af ter a code in the same line. Both cases are explained
in the below image.
When # is placed inside quotes, then it is part of the string and not a comment.
For example,
Variables
Python variables are containers to hold data. T hese assigned data value to a
variable can be changed at a later stage.
numOf Boxes = 7
ownerName = "Karthik"
In the above example, two variables with numeric and string data are created.
Print statements are used to display those variables.
# valid names
numOf Boxes = 7
_num_of _boxes = 10 # this is a dif f erent variable than numOf Boxes
ownerName = "Karthik"
# invalid names
Here we have listed out some of the possible variable names and f ew invalid
names.
In python, you can assign multiple values to many variables. Also assign the
same value to multiple variables. Please see this example.
print(width)
print(depth)
print(width)
print(depth)
Operators
Contributed by – papaprogrammer
Operators help in processing variables and values. For example, if we can two
numeric variables, they can be added or subtracted, multiplied or divided.
T hese operations change the value and give out new values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators
Mathematical operations like addition, subtraction are perf ormed using
arithmetic operators. Let us go through them.
a = 10
b= 6
print (a + b) # addition
print (a - b) # subtraction
print (a * b) # multiplication
print (a / b) # division
print (a % b) # modulus
print (a ** b) # exponentiation
All the operations are easy to understand. Modulus operation returns the
remainder of dividing two numbers (in our example, 4 is the reminder). Similarly,
f loor division is integer division, which returns the result of division as whole
integer (10 // 6 = 1).
Assignment operators
Values or variable content can be assigned to another variable using
assignment operators. T he right-hand side can also be an expression
(assignment to c in the f ollowing example). Here are a f ew examples.
a = 7 # assign value to a
b = a # assign value of a into b
b += 2 # equivalent to b = b + 2
b -= 2 # equivalent to b = b - 2
b *= 2 # equivalent to b = b * 2
b /= 2 # equivalent to b = b / 2
b %= 2 # equivalent to b = b % 2
b //= 2 # equivalent to b = b // 2
b **= 2 # equivalent to b = b ** 2
b ^= 2 # equivalent to b = b ^ 2
Comparison operators
T wo values are compared and the result is a Boolean value T rue or False. Used
in if and loop statements to make decisions.
a= 3
b= 7
a= 3
b= 7
if (a < b):
print("f irst number is less than second one");
else:
Logical operators
T wo or more comparison operations can be combined using logical operators.
T hese logical operators return Boolean value.
a= 5
b= 8
Identity operators
Identity operators compare if two objects are the same. T hey need to point to
the same location.
a = ["hello", "world"]
b = ["hello", "world"]
c=a
print(a is b)
print(a == b)
print(a is not c)
print(a is not b)
Membership operators
Checks if an element is present in a given list.
a = ["hello", "world"]
Bitwise operators
While dealing with binary numbers, we need bitwise operators to manipulate
them. Binary numbers are zeros and ones, which are named as bits.
a = 1 # binary equivalent of 1 is 1
b = 2 # binary equivalent of 2 is 10
print(a & b)
print(a | b)
# 1 ^ 1 = 0, 0 ^ 0 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1
print(a ^ b)
# NOT 0 = 1, NOT 1 = 0
# while negating b, all preceeding zeros are turned to one
# this leads to a negative number
print(~ b)
# zeros are f illed f rom right, bits are shif ted to lef t
print(b << 2)
# shif t the bits to the right, copy lef tmost bits to the right
# right most bits f all of f
# when we shif t b (10) once to the right, it becomes 1
print(b >> 1)
Ternary Operator
Int roduct ion Pyt hon T ernary Operat or
We all know the dif f erent operators in python, i.e., Unary operators and Binary
operators.
An operator that can be used to negate a positive value with one operand is
called the unary operator; f or example, x = -4, here we are negating a value 4
with operator –, so operator — acts as a unary operator.
Now we know what the Unary and Binary operator is, so what is this ternary
operator? Guess what? Yes, you are correct; an operator that works with three
operands (components) is called a ternary operator.
T he three components are (1) A condition (2) T rue value (3) False value.
Let’s write a simple if condition that evaluates a person’s age and tells whether
the person is major or minor.
Age = 21
if (Age > 18):
print("Major")
else:
print("Minor")
We declared Age variable equal to 21; we then have an if /else statement that
evaluates the Age value if age is greater than 18 then prints ”Major” else
“Minor”.
Yes, with the help of a ternary operator we can achieve this. T his operator is
available f rom Python version 2.4.
As I said above, the ternary operator requires 3 components and the structure
of these components as below:
So, the f ollowing code shows how can we transf orm the above lengthy code
into a lesser number of lines using the ternary operator:
Age = 21
"Major" if (Age > 18) else "Minor"
#'Major'
Age = 15
"Major" if (Age > 18) else "Minor"
#'Minor'
T hat’s it! Component 2 is our condition ( if (Age > 18) ), which is evaluated f irst. If
it evaluates to T rue, then “Major” is the output; otherwise, “Minor” is the output.
In this case, Age > 18 evaluates to T RUE, so the output is “Major”.
Let’s decompose our improved code to match the structure of the ternary
operator:
We can use ternary operators in the f unction’s return statement. For example,
writing a f unction that expects a person’s Age as input and returns the person
is either “Major” or “Minor”.
def is_major(Age):
is_major(21)
# 'Major'
is_major(15)
'Minor'
T he above code shows how we can use the ternary operator in a return
statement; we have used the ternary operator structure directly in the return
statement.
Short Hand T ernary operat or
T rue or NULL
# T rue
False or 1
#1
T he f irst statement (T rue or “NULL”) will return T rue, and the second statement
(False or “1”) will return 1.
known_number = None
print(msg)
#Unknown number
known_number = 5634
print(msg)
# 5634
T his will be usef ul when you quickly test a user input in a f unction:
print(display_name)
#Jospeh
# Joe
T he above f unction takes the person name and nickname as arguments and
use the shorthand ternary operator syntax and results in displaying the
person’s name; this will become handier to test the two variables and results in
the only T RUE values.
Let’s write a f unction that evaluates multiple if conditions and return the result.
f loors = 12
print('Mid-rise building')
else:
T he above If …elif code evaluates a number of f loors value and result is the
category of building, i.e., if the f loors are greater less than or equal to three
f loors, then it is categorized a “Low rise building” else if the f loors are greater
than three but less than or equal to 7 then its is categorized as “Mid-rise
building ” else it is categorized as “High rise building”.
With the help of a ternary operator, we can write this code in a small number of
lines, But how? T he ternary operator structure says only 3 components, but
here we have multiple conditions, don’t worry, we also nest the ternary
operator just like nested if .
f loors = 12
'Low rise building' if (f loors <= 3) else 'Mid-rise building' if (f loors >3 and f loors
<=7) else 'High rise building'
f loors = 7
'Low rise building' if (f loors <= 3) else 'Mid-rise building' if (f loors >3 and f loors
<=7) else 'High rise building'
#'Mid-rise building'
f loors = 2
'Low rise building' if (f loors <= 3) else 'Mid-rise building' if (f loors >3 and f loors
<=7) else 'High rise building'
Lambda
Earlier we saw f unction def inition and f unction calls. Lambdas are anonymous,
small f unctions. T he body of the lambda can have only one expression. Lambda
can take any number of arguments.
print(growth(25)) # prints 27
Let us take another example with many parameters:
def growth(n):
return lambda a : a + n
strechT wo = growth(2)
print(strechT wo(7))
print(strechT hree(7))
In the above example, using the same f unction growth, we spawn dif f erent
f unctions strechT wo and strechT hree. T his is possible with the lambda
f unction declared inside the growth f unction. We get the output 9 and 10 by
running this code.
Arrays
Arrays are used to store a list of values in a variable. Here is the syntax to
create an array. Square brackets are used to def ine a list.
print (f ruits)
Arrays allow us to access the array elements using index. T he index are zero
based, they start f rom zero.
f irstFruit = f ruits[0]
print (f irstFruit)
Similar to accessing the element, we can modif y the element using index.
f ruits[0] = "melon"
print (f ruits)
f or f ruit in f ruits:
print(f ruit)
f ruits.append("guava")
print(f ruits)
T wo methods are usef ul to remove elements f rom the array. pop() method
takes the array index and removes the element in the particular position
(remember the elements are zero based). remove() accepts the value of the
element and removes it. Let us see these two methods in action.
f ruits.pop(1)
print(f ruits)
f ruits.remove("grapes")
print(f ruits)
Classes
Objects are entities that possess properties and methods. T hese objects can
be created by declaring classes. Classes are blueprints of objects.
In this example, we see how to def ine a class, create objects out of the class
and access the property of the object.
class Fruit:
name="mango"
oneFruit = Fruit()
print(oneFruit.name)
We can write usef ul initialization code in this f unction, so that variables are set
at the time of object instantiation.
class Fruit:
print(oneFruit.name)
print(oneFruit.color)
In the above example, we used a parameter “self ”. T here are three parameters
def ined in the init f unction, however we passed only two arguments in the class
invocation. T he self -parameter is automatically passed to the class’s method.
T he name “self ” is not f ixed, you may use any name. It has to be the f irst
parameter.
Apart f rom the inbuilt methods, the class can have other user def ined
methods. Let us create a makeJuice() method inside the class.
class Fruit:
def makeJuice(self ):
oneFruit.makeJuice()
oneFruit.color = "red"
Inheritance
Inheritance is a concept where we extend the f unctionality of a class to create
new classes. T here are many benef its of doing this. Foremost is to reuse
existing code.
T he existing class has generic code that can be reused. T his class is called
parent or base class.
We create a child class that would receive the def inition f rom the parent class.
Let us consider a parent class, Vehicle. T his has properties and methods
suitable to describe any vehicle.
class Vehicle:
def __init__(self , make, color):
def display(self ):
print("make= " + self .make + " color= " + self .color)
v = Vehicle("2015", "green")
v.display()
T wo properties, make and color, are def ined in the Vehicle property.
class Vehicle:
def __init__(self , make, color):
def display(self ):
print("make= " + self .make + " color= " + self .color)
# v = Vehicle("2015", "green")
# v.display()
class Car(Vehicle):
super().__init__(make, color)
def display(self ):
super().display()
def wipeWindshield(self ):
print("turned on wiper")
newCar.display()
newCar.wipeWindshield()
Line 12 def ines a class, Car. T his is an extended Vehicle (mentioned in the
paranthesis).
Line 15 initializes an object property, numOf Seats. T his property belongs to Car
and does not exist in Vehicle class.
Line 17 redef ines the method display(). In the method’s code, parent method is
called, as well as code is there to express f unctionality of the Car object.
Line 24 to 26 creates a Car object, handles Car properties and invokes various
methods.
Iterators
Iterator is a container of values, with which we can traverse through all the
values.
Lists, tuples, dictionaries, and sets are iterable and implement an iterator
protocol. T hese containers have iter() method that are used to traverse the
values.
Here is an example.
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))
f ruitStr = "mango"
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter)) # last call throws error
Note that the f irst f ive next () call print each character of “mango”. T he f inal
next () throws an error saying the iteration has stopped.
print(f ruit)
We can create our own iterator class. We need to implement __iter__() and
__next__() methods.
class Fibonacci:
def __iter__(self ):
return self
def __next__(self ):