Unit1 PythonNotes
Unit1 PythonNotes
What is Python?
Python is a general purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.
Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
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.
Python Features
Python provides many useful features which make it popular and valuable from the
other programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed
below a few essential features.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line
at a time. The advantage of being interpreted language, it makes debugging easy
and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a
program only once.
C++ vs Java
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come
into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte
code, and any platform can use that byte code.
8) Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning,
web developer, and also for the scripting. There are various machine learning
libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask,
pyramids are the popular framework for Python web development.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs
code line by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We
can use Python source code in another programming language as well. It can embed
other language into our code.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development. Python makes its presence in every
emerging field. It is the fastest-growing programming language and can develop any
application.
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile 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
Setting up PATH
Windows Installation
Here are the steps to install Python on Windows machine.
Open a Web browser and go to https://www.python.org/downloads/
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
# First comment
print "Hello, Python!" # second comment
Following triple-quoted string is also ignored by Python interpreter and can be used
as a multiline comments:
'''
This is a multiline
comment.
'''
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin
with a letter or an underscore.
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three
different variables)
Creating Variables
Python has no command for declaring a variable.
Example
x = 5
y = "SAC"
print(x)
print(y)
Example
x = 5
y = "John"
print(type(x))
print(type(y))
Python Keywords
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation.
These keywords can't be used as a variable. Following is the List of Python Keywords.
Numeric
Sequence Type
Boolean
Set
Dictionary
Numbers
Number stores numeric values. The integer, float, and complex values belong to a
Python Numbers data-type.
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It
is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and
y denote the real and imaginary parts, respectively. The complex numbers like
2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
x = "Hello World"
#display x:
print(x)
List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within
square brackets [].
Dictionary
Dictionary is an unordered set of a key-value pair of items.
The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.
# Printing dictionary
print (d)
Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0
or 'F'. Consider the following example.
Python Operators
The operator can be defined as a symbol which is responsible for a particular
operation between two operands. Operators are the pillars of a program on which
the logic is built in a specific programming language. Python provides a variety of
operators, which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two
operands. It includes + (addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**) operators.
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is l
than the second operand, the value results negative. For example, if a = 20, b = 10 => a
= 10
/ (divide) It returns the quotient after dividing the first operand by the second operand. For examp
if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b
(Multiplication) 200
% (reminder) It returns the reminder after dividing the first operand by the second operand. For examp
if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)
Comparison operator
Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false accordingly. The comparison operators are described in
the following table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes tru
>= If the first operand is greater than or equal to the second operand, then the condition becom
true.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Assignment Operators
The assignment operators are used to assign the value of the right expression to the
left operand. The assignment operators are described in the following table.
Operator Description
+= It increases the value of the left operand by the value of the right operand and assigns
modified value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to
a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to
a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will
equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the remin
back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b a
therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two
operands. Consider the following example.
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the res
and) Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will b
and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the right operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Logical Operators
The logical operators are used primarily in the expression evaluation to make a
decision. Python supports the following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If a and b are the two expressio
a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b are the two expressio
a → true, b → false => a or b → true.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value inside a
Python data structure. If the value is present in the data structure, then the resulting
value is true otherwise it returns false.
Operator Description
in It is evaluated to be true if the first operand is found in the second operand (list, tuple,
dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple,
dictionary).
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
is It is evaluated to be true if the reference present at both sides point to the same object.
is not It is evaluated to be true if the reference present at both sides do not point to the same object
Python - Conditional Statements or Decision Making
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, a block
code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides t
Statement block of the code for the false case of the condition to be checked. If the conditi
provided in the if statement is false, then the else statement will be executed.
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)
Example : Program to check whether a number is even or not.
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")
The elif statement works like an if-else-if ladder statement in C. It must be succeeded
by an if statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example
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");
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. Consider the
following diagram to understand the working of a loop statement.
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part of the code un
the given condition is satisfied. The for loop is also called as a per-tested loop. It
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
iterations in advance. The block of statements is executed in the while loop until t
condition specified in the while loop is satisfied. It is also called a pre-tested loop.
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
Syntax:
range(start,stop,step size)
Example:
for i in range(10):
print(i)
Syntax
Example
for x in adj:
for y in fruits:
print(x, y)
Example
for x in range(6):
print(x)
else:
print("Finally finished!")
while expression:
statements
Example
The following program uses a nested for loop to find the prime numbers from 2 to
100 −
Live Demo
#!/usr/bin/python
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram
Let's understand the following example.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Syntax
The syntax for a break statement in Python is as follows −
break
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
3. Pass Statement - The pass statement is used to declare the empty loop.
The pass statement is a null operation; nothing happens when it executes. It is also
used to define empty class, function, and control statement. Let's understand the
following example.
Syntax
pass