Python Tutorial
Python Tutorial
Python is a simple, general purpose, high level, and object-oriented programming language.
Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of
Python programming.
7.6M
184
Features of Java -
What is Python
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for
Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
Python is not intended to work in a particular area, such as web programming. That is why it is
known as multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.
1. Python 2 uses print as a statement and used as print "something" to print some string on
the console. On the other hand, Python 3 uses print as a function and used as
print("something") to print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the string
representing the value, which is typed by the user. To convert it into the integer, we need to
use the int() function in Python. On the other hand, Python 3 uses input() function which
automatically interpreted the type of input entered by the user. However, we can cast this
value to any type by using primitive functions (int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit string type is
Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is the variant of
range() function which returns a xrange object that works similar to Java iterator. The range()
returns a list for example the function range(0,3) contains 0, 1, 2.
5. There is also a small change made in Exception handling in Python 3. It defines a
keyword as which is necessary to be used. We will discuss it in Exception handling section of
Python programming tutorial.
Python History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of Python
programming language has taken from the ABC programming language or we can say that ABC is
a predecessor of Python language.
There is also a fact behind the choosing name Python. Guido van Rossum was a fan of the
popular BBC comedy show of that time, "Monty Python's Flying Circus". So he decided to pick
the name Python for his newly created programming language.
Features of python:
o Easy to use and Learn
o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Open Source Language
o Extensible
o Learn Standard Library
o GUI Programming Support
o Integrated
o Embeddable
o Dynamic Memory Allocation
o Wide Range of Libraries and Frameworks
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
def func():
statement 1
statement 2
…………………
…………………
statement N
In the above example, the statements that are same level to right belong to the function.
Generally, we can use four whitespaces to define indentation.
public class HelloWorld {
public static void main(String[] args){
// Prints "Hello, World" to the terminal window.
System.out.println("Hello World");
}
}
print("Hello World")
Both programs will print the same result, but it takes only one statement without using a
semicolon or curly braces in Python.
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.
Unlike the other programming languages, Python print() function is most unique and versatile
function.
1. print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
o objects - An object is nothing but a statement that to be printed. The * sign represents that
there can be multiple statements.
o sep - The sep parameter separates the print values. Default values is ' '.
o end - The end is printed at last in the statement.
o file - It must be an object with a write(string) method.
o flush - The stream or file is forcibly flushed if it is true. By default, its value is false.
print("Welcome to python.")
a = 10
# Two objects are passed in print() function
print("a =", a)
b = a
# Three objects are passed in print function
print('a =', a, '= b')
Example - 2: Using sep and end argument
a = 10
print("a =", a, sep='dddd', end='\n\n\n')
print("a =", a, sep='0', end='$$$$$')
Example -
name = input("Enter a name of student:")
print("The student name is: ", name)
By default, the input() function takes the string input but what if we want to take other data types
as an input.
For example -
Example -
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a+b)
Python Operators
Operators are the symbols which perform various operations on Python objects. Python operators
are the most essential to work with the Python data types. In addition, Python also provides
identify membership and bitwise operators. We will learn all these operators with the suitable
example in following tutorial.
o Python Operators
Python Loops
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times. For this purpose, the programming languages
provide various types of loops capable of repeating some specific code several times. Consider
the following tutorial to understand the statements in detail.
o Python Loops
o Python For Loop
o Python While Loop
Python List
Python list holds the ordered collection of items. We can store a sequence of items in a list.
Python list is mutable which means it can be modified after its creation. The items of lists are
enclosed within the square bracket [] and separated by the comma. Let's see the example of list.
1. L1 = ["John", 102, "USA"]
2. L2 = [1, 2, 3, 4, 5, 6]
If we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.
1. print(type(L1))
2. print(type(L2))
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The 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 cannot be changed.
Example -
tup = ("Apple", "Mango" , "Orange" , "Banana")
print(type(tup))
print(tup)
Example -
# Creating string using double quotes
str1 = "Hi Python"
print(str1)
# Creating string using single quotes
str1 = 'Hi Python'
print(str1)
# Creating string using triple quotes
str1 = '''Hi Python'''
print(str1)
Python doesn't support the character data-type. A single character written as 'p' is treated as a
string of length 1.
Dictionaries
Python Dictionary is a most efficient data structure and used to store the large amount of data. It
stores the data in the key-value pair format. Each value is stored corresponding to its key.
Keys must be a unique and value can be any type such as integer, list, tuple, etc.
It is a mutable type; we can reassign after its creation. Below is the example of creating dictionary
in Python.
Example
employee = {"Name": "John", "Age": 29, "salary":250000,"Company":"GOOGLE"}
print(type(employee))
print("printing Employee data .... ")
print(employee)
If Statement The if statement is used to test a specific condition. If the condition is true, a block of
code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides the
Statement block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer if statement.
Statement
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
How to find Nth Highest Salary in SQL
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical expression
which can be either evaluated to true or false.
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
if condition:
#block of statements
else:
#another block of statements (else-block)
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Example 2
marks = int(input("Enter the marks? "))
f marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
lif marks > 60 and marks <= 85:
print("You scored grade B + ...")
lif marks > 40 and marks <= 60:
print("You scored grade B ...")
lif (marks > 30 and marks <= 40):
print("You scored grade C ...")
lse:
print("Sorry you are fail ?")
Python Loops
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times.
Advantages of loops
There are the following advantages of loops in Python.
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part of the code until
the given condition is satisfied. The for loop is also called as a per-tested loop. It is
better to use for loop if the number of iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also called a pre-tested loop.
do-while The do-while loop continues until a given condition satisfies. It is also called post
loop tested loop. It is used when it is necessary to execute the loop at least once (mostly
menu driven programs).
for iterating_var in sequence:
statement(s)
str = "Python"
for i in str:
print(i)
list = [1,2,3,4,5,6,7,8,9,10]
n = 5
for i in list:
c = n*i
print(c)
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
range(start,stop,step size)
o The start represents the beginning of the iteration.
o The stop represents that the loop will iterate till stop-1. The range(1,5) will generate
numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to
use. By default, the step size is 1. It is optional.
for i in range(10):
print(i,end = ' ')
Program to print table of given number.
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
n= int(input("Enter the number "))
for i in range(2,n,2):
print(i)
list = ['Peter','Joseph','Ricky','Devansh']
for i in range(len(list)):
print("Hello",list[i])
Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.
while expression:
statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
1. Continue Statement - When the continue statement is encountered, the control transfer to
the beginning of the loop. Let's understand the following example.
Example:
# prints all letters except 'a' and 't'
i = 0
str1 = 'welcome'
while i < len(str1):
if str1[i] == 'a' or str1[i] == 't':
i += 1
continue
print('Current Letter :', a[i])
i += 1
2. Break Statement - When the break statement is encountered, it brings control out of the loop.
Example:
# The control transfer is transfered
# when break statement soon it sees t
i = 0
str1 = 'welcome'
while i < len(str1):
if str1[i] == 't':
i += 1
break
print('Current Letter :', str1[i])
i += 1
Pass Statement - The pass statement is used to declare the empty loop. It is also used to define
empty class, function, and control statement. Let's understand the following example.
Example -
# An empty loop
str1 = 'welcome'
i = 0
while i < len(str1):
i += 1
pass
print('Value of i :', i)
The break is commonly used in the cases where we need to break the loop for a given condition.
#loop statements
break;
Example 1
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");
Example 2
str = "python"
for i in str:
if i == 'o':
break
print(i);
Example 3
n=2
while 1:
i=1;
while i<=10:
print("%d X %d = %d\n"%(n,i,n*i));
i = i+1;
choice = int(input("Do you want to continue printing the table, press 0 for no?"))
if choice == 0:
break;
n=n+1
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.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
#loop statements
continue
#the code to be skipped
Example 1
i = 0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.
Example 2
str = "welcome"
for i in str:
if(i == 'T'):
continue
print(i)
Pass Statement
The pass statement is a null operation since nothing happens when it is executed. It is used in the
cases where a statement is syntactically needed but we don't want to use any executable
statement at its place.
For example, it can be used while overriding a parent class method in the subclass but don't want
to give its specific implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the program
file.
list = [1,2,3,4,5]
flag = 0
for i in list:
print("Current element:",i,end=" ");
if i==3:
pass
print("\nWe are inside pass block\n");
flag = 1
if flag==1:
print("\nCame out of pass\n");
flag=0
Python Pass
In Python, the 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 the 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.
It is beneficial when a statement is required syntactically, but we want we don't want to execute or
execute it later. The difference between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not ignored.
Suppose we have a loop, and we do not want to execute right this moment, but we will execute in
the future. Here we can use the pass.
# pass is just a placeholder for
# we will adde functionality later.
values = {'P', 'y', 't', 'h','o','n'}
for val in values:
pass
Example - 2:
for i in [1,2,3,4,5]:
if(i==4):
pass
print("This is pass block",i)
print(i)
We can create empty class or function using the pass statement.
# Empty Function
def function_name(args):
pass
#Empty Class
class Python:
pass
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 a 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.
The Function helps to programmer to break the program into the smaller part. It organizes the
code very effectively and avoids the repetition of the code. As the program grows, function makes
the program more organized.
Python provide us various inbuilt functions like range() or print(). Although, the user can create
its functions, which can be called user-defined functions.
o User-define functions - The user-defined functions are those define by the user to perform
the specific task.
o Built-in functions - The built-in functions are those functions that are pre-defined in
Python.
o Using functions, we can avoid rewriting the same logic/code again and again in a program.
o We can call Python functions multiple times in a program and anywhere in a program.
o We can track a large Python program easily when it is divided into multiple functions.
o Reusability is the main achievement of Python functions.
o However, Function calling is always overhead in a Python program.
Creating a Function
Python provides the def keyword to define the function. The syntax of the define function is given
below.
Syntax:
def my_function(parameters):
function_block
return expression
o The def keyword, along with the function name is used to define the function.
o The identifier rule must follow the function name.
o A function accepts the parameter (argument), and they can be optional.
o The function block is started with the colon (:), and block statements must be at the same
indentation.
o The return statement is used to return the value. A function can have only one return
Function Calling
In Python, after the function is created, we can call it from another function. A function must be
defined before the function call; otherwise, the Python interpreter gives an error. To call the
function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints the message "Hello World".
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
Syntax
1. return [expression_list]
It can contain the expression which gets evaluated and value is returned to the caller
function. If the return statement has no expression or does not exist itself in the function
then it returns the None object.
Example 1
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
In the above code, we have defined the function named sum, and it has a statement c =
a+b, which computes the given values, and the result is returned by the return statement to the
caller function.
Arguments in function
The arguments are types of information which can be passed into the function. The arguments
are specified in the parentheses. We can pass any number of arguments, but they must be
separate them with a comma.
Consider the following example, which contains a function that accepts a string as the argument.
Example 1
#defining the function
def func (name):
print("Hi ",name)
#calling the function
func("Devansh")
Example 2
#Python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))