Python Unit - 1
Python Unit - 1
Python History
Python laid its foundation in the late 1980s.
The implementation of Python was started in the December 1989 by Guido Van
Rossum.
In February 1991, van Rossum published the code.
Python Introduction:
"Python is a programming language that lets our work more quickly and integrates our
systems more effectively."
Python is a general purpose, dynamic, high level and interpreted programming language. It
supports Object Oriented programming approach to develop applications.
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, makes it an ideal language for
scripting and rapid application development.
Python supports multiple programming pattern, including object oriented, imperative and
functional or procedural programming styles.
Python makes the development and debugging fast because there is no compilation step
included in python development and edit-test-debug cycle is very fast.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Data Analysis
Machine Learning
AI
IoT
2. Easy to Read:
Python code looks like simple English words. There is no use of semicolons or brackets, and the
indentations define the code block. We can tell what the code is supposed to do simply by looking at it.
4. High-level Language:
Python is a high-level programming language because programmers don’t need to remember the
system architecture, nor do they have to manage the memory. This makes it super programmer-friendly
and is one of the key features of Python.
5. Expressive:
'Expressive' means that it's easy to write code that's easy to understand, both for the compiler and for a
human reader. Python needs to use only a few lines of code to perform complex tasks.
For example, to display Hello World, we simply need to type one line -
print("Hello World")
For example, to display a message five times we can use for loop as:
for i in range(5):
print("Python is Easy...!")
Other languages like Java or C would take up multiple lines to execute this.
6. Dynamically Typed:
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Many programming languages need to declare the type of the variable before they are using. Python is
a dynamically typed language. Which means, in Python there is no need to declare the type of a
variable. Whenever we assign a value to the variable, based on the value the type will be allocated
automatically. This makes Python a dynamically typed language.
For example, if you have to assign an integer value 20 to a variable “x”, we don’t need to write int x =
20. We just have to write x = 15.
7. Interpreted:
When a programming language is interpreted, it means that the source code is executed line by line,
and not all at once. Programming languages such as C++ or Java are not interpreted, and hence need to
be compiled first to run them. There is no need to compile Python because it is processed at runtime by
the interpreter.
8. Platform Independent:
Python is a Platform-Independent programming language. It means Python can run equally easily on a
variety of platforms like Windows, Linux or Unix, and many more Operating Systems. So, there is no
need to write a separate code for each Operating System, as the same code can run on multiple
platforms. Python uses PVM (Python Virtual Machine) to convert python code to machine
understandable code.
9. Portability:
The python applications or portable. The applications which are developed by python on one platform
are going to execute any platform without making any changes. To achieve the portability feature for
every Operating System a separate python software is developed for every version.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
12. Extensible:
A programming language is said to be extensible if it can be extended to other languages. Python code
can also be written in other languages like C++, making it a highly extensible language.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Step 6: Output:
Then the output will be displayed on another window.
Identifiers:
Every name in Python is called as an Identifier. That name may be class name, method name,
function or variable name.
Ex:2
1name #not allowed
2id #not allowed
id1 #allowed
n1a #allowed
Ex:3 Keywords
if #not allowed
If #allowed
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Literals:
It is a constant value assigned to a variable. It may be Integers, Floats, Strings, etc.,
Ex:
emp_id = 101 #integer literal
empName = "Scott" #string literal
empSalary = 2000.00 #float literal
Variables:
A variable is the name given to a memory location. It is the basic unit of storage in a
program.
The value stored in a variable can be changed during program execution.
Variables are used to store the values, by using these values we are achieving the
project requirements.
Example:
For Employee we required:
employeeId, employeeName, employeeSalary,
In order to use a variable in a Python program we to need to perform one step, i.e, Variable
Initialization.
Syntax:
<identifier> = <value/literal>
Ex:
emp_id = 101
emp_name = "Scott"
emp_salary = 2000.00
Comments in Python:
In Python, we use the hash '#' symbol to start writing a comment.
It extends up to the newline character. "Python Interpreter ignores comment".
Comments are very important while writing a program. It describes what's going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
Example:
#This is a comment, Here print() function prints the value
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
print("Welcome to Python")
Multi-line comments:
If we have comments that extend multiple lines, one way of doing it is to use hash '#' in the
beginning of each line.
Example:
#This is a long comment
#
#and it extends up to multiple lines
Reserved Words:
Keywords are the reserved words in Python. They are used to define the syntax and
structure of the Python language.
We cannot use a keyword as variable name, function name or any other identifier.
In Python, keywords are case sensitive.
>>>print(1,2,3,4)
1 2 3 4
>>>print(1,2,3,4,sep='*')
1*2*3*4
>>>print(1,2,3,4,sep='#',end='&')
1#2#3#4&
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
x=input("Enter Value)
type(x)
Example:
a = input("Enter a Number :")
b = input("Enter a Number :")
Python Indentation:
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first un-
indented line. The amount of indentation is up to us, but it must be consistent throughout that
block.
Generally, four whitespaces are used for indentation and is preferred over tabs.
Example:
for i in range(1, 11):
print(i)
if i == 5:
break
Example:
>>>print(1000)
1000
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:1
if True:
print('Hello')
a = 5
1. Decimal(base-10) By default
0-9 (allowed digits but not start with 0)
2. Binary (base-2)
1. 0 and 1(allowed digits)
2. starts with 0 followed by 'b' or 'B'
Ex: a=0b1010,
b=0B1010
c=0B10102 #(Invalid)
3. Octal (base-8)
1. 0-7 (allowed digits)
2. starts with 0 followed by 'o' or 'O'
Ex: a=0o1014,
b=0O1014,
c=0o1237
d=0o1238 #(invalid)
Ex: a=0x1039Af
b=0X1039Af
c=0X09ag #(invalid)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Note:
a=10
b=0o10
c=0b10
d=0x10
Output: only in decimal
Ex:
f=123.456 #valid
f=0123.456 #valid
f=0X123.456 #invalid
f=0o123.456 #invalid
f=0b123.456 #invalid
Ex:
f=1.2e3 # (1.2*10^3)
>>> a=1.2e100
>>> a
1.2e+100
Notation:
a+bj #allowed
a+jb #not allowed
j^2=-1 or j =sqrt(-1)
To extract these parts from a complex number 'x', use x.real and x.imag.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Ex: x=10+20j
Ex: x=2.3+4.5j
Example:1
>>> a=10+20j
>>> a
(10+20j)
>>> a.real
10.0
>>> a.imag
20.0
Example:2
>>> a=10.3+20.5j
>>> a
(10.3+20.5j)
>>> a.real
10.3
>>> a.imag
20.5
Examples:
Single quotes:
s = 'Welcome to Python'
s = 'Welcome to "Python" Classes'
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Double quotes:
s = "Welcome to Python"
s = "Welcome to 'Python' Classes"
Triple quoted:
s = """Welcome to Python"""
or
s = '''Welcome to Python'''
Ex:
s='Hi Hello'
Ex:1
a='Hi Hello'
print(a)
Ex:2
a="Hi Hello"
print(a)
a= '''
Hi Hello
How are
you '''
print(a)
a="""Hi Hello
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
How are
you"""
print(a)
Example:
list = [10, 10.5, 'Madhu', True, 10]
print(list) #[10, 10.5, 'Madhu', True, 10]
Example:
list=[10,20,30,40]
>>> list[0]
10
>>> list[-1]
40
>>> list[1:3]
[20, 30]
>>> list[0]=100
>>> for i in list : print(i)
Example:
>>>t = (10,20,30,40)
>>>type(t)
<class 'tuple'>
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
The elements present in range Data type are not modifiable. i.e., range Data type is
immutable.
We can access elements present in the range Data Type by using index.
r = range(10, 20)
r[0] # 10
r[15] # IndexError: range object index out of range
Example:
s = {100, 0, 10, 200, 10, 'Madhu'}
print(s) # {0, 100, 'Madhu', 200, 10}
Example:
d={101:'durga',102:'Madhu',103:'shiva'}
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry
with duplicate key then old value will be replaced with new value.
Example:
>>> d={101:'durga',102:'madhu',103:'shiva'}
>>> d[101]='sunny'
>>> d
101: 'sunny', 102: 'madhu', 103: 'shiva'}
Operators in Python
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator
// ==>Floor Division operator
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example 1: test.py:
a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
Output:
python test.py or py test.py
a+b= 12
a-b= 8
a*b= 20
a/b= 5.0
a//b= 5
a%b= 0
a**b= 100
Example 2: test.py
a=10.5
b=2
print('a+b=', a+b)
print('a-b=', a-b)
print('a*b=', a*b)
print('a/b=', a/b)
print('a//b=', a//b)
print('a%b=', a%b)
print('a**b=', a**b)
Output:
python test.py or py test.py
a+b= 12.5
a-b= 8.5
a*b= 21.0
a/b= 5.25
a//b= 5.0
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
a%b= 0.5
a**b= 110.25
Example 3: test.py
10 / 2 # 5.0
10 // 2 # 5
10.0 / 2 # 5.0
10.0 // 2 # 5.0
Note: / operator always performs floating point arithmetic. Hence it will always
return float value.
But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If at least one argument is
float type then result is float type.
Relational Operators:
>, >=, <, <=
Example:
a = 10
b = 20
print("a > b is ", a > b)
print("a >= b is ", a >= b)
print("a < b is ", a < b)
print("a <= b is ", a <= b)
Example:
print(True > True)
print(True >= True)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
print(10 > True)
print(False > True)
print(10>'durga')
TypeError: '>' not supported between instances of 'int' and 'str'
Example:
print(10 < 20)
print(10 < 20 < 30)
print(10 < 20 < 30 < 40)
print(10 < 20 < 30 < 40 > 50)
Equality Operators:
== , !=
We can apply these operators for any type even for incompatible types also
>>> 10 == 20
False
>>> 10 != 20
True
>>> 10 == True
False
>>> False == False
True
>>> "madhu" == "madhu"
True
>>> 10 == "madhu"
False
>>>10 == 20 == 30 == 40
False
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
>>>10 == 10 == 10 == 10
True
Logical Operators:
The logical operators are and, or, not. We can apply these operators for all
types.
Bitwise Operators:
We can apply these operators bitwise.
These operators are applicable only for int and Boolean types.
By mistake if we are trying to apply for any other type then we will get
Error.
The operators are &, |, ^, ~, <<, >>
Example:
print(4 & 5) #Valid
print(10.5 & 5.6)
#TypeError: unsupported operand type(s) for &: 'float' and 'float'
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:
print(4 & 5)
print(4 | 5)
print(4 ^ 5)
Example:
print(~5) #-6
Note:
The most significant bit acts as sign bit. 0 value represents positive value whereas
1 represents negative value.
Shift Operators:
<< Left shift operator:
After shifting the empty cells, we have to fill with zero.
Example:
print(10<<2) #40
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:
print(10>>2) #2
Example:
print(True & False) # False
print(True | False) # True
print(True ^ False) # True
print(~True) # -2
print(True << 2) # 4
print(True >> 2) # 0
Assignment Operators:
We can use assignment operator to assign value to the variable.
Example:
x = 0
Example:
x += 10 is equals to x = x + 10
The following is the list of all possible compound assignment operators in Python
+=, -=, *=, /=, %=, //=, **=
&=, |=, ^=, >>=, <<=
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:
x = 10
x += 20
print(x)
Example:
x = 10
x &= 5
print(x)
Ternary Operator:
Syntax:
x = firstValue if condition else secondValue
Example:
a, b = 10, 20
x = 30 if a < b else 40
print(x) #30
Example: Read two numbers from the keyboard and print minimum value
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
min = a if a < b else b
print("Minimum Value:", min)
Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
c = int(input("Enter Third Number:"))
min = a if a < b and a < c else b if b < c else c
print("Minimum Value:", min)
Example:
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
print("Both numbers are equal" if a == b else "First Number is Less than
Second Number" if a < b else "First Number Greater than Second Number")
Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
1. Identity Operators
We can use identity operators for address comparison.
2 identity operators are available. They are is, is not
r1 is r2 returns True if both r1 and r2 are pointing to the same object
r1 is not r2 returns True if both r1 and r2 are not pointing to the same
object
Example:
a = 10
b = 10
print(a is b) # True
x = True
y = True
print(x is y) # True
Example:
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
a="madhu"
b="madhu"
print(id(a))
print(id(b))
print(a is b)
Example:
list1 = ["one", "two", "three"]
list2 = ["one", "two", "three"]
print(id(list1))
print(id(list2))
print(list1 is list2) # False
print(list1 is not list2) # True
print(list1 == list2) # True
Note:
We can use ‘is’ operator for address comparison whereas ‘==’ operator for
content comparison.
2. Membership operators:
We can use Membership operators to check whether the given object
present in the given collection. (It may be String, List, Set, Tuple or Dict).
2 membership operators are available. They are in, not in
in Returns True if the given object presents in the specified Collection
not in Returns True if the given object not present in the specified
Collection
Example:
x = "hello learning Python is very easy!!!"
print('h' in x) # True
print('d' in x) # False
print('d' not in x) # True
print('Python' in x) # True
Example:
list1 = ["sunny", "bunny", "chinny", "pinny"]
print("sunny" in list1) # True
print("tunny" in list1) # False
print("tunny" not in list1) # True
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
www.leelasoft.com Cell: 78 42 66 47 66