Python Part - 1
Python Part - 1
Introduction
Python is a general purpose high level programming language.
Python was developed by Guido Van Rossam in 1989 while working at National Research Institute
at Netherlands.
But officially Python was made available to public in 1991.
The official Date of Birth for Python is: Feb 20th 1991.
Python is recommended as first programming language for beginners.
In C:
1) #include<stdio.h>
2) void main()
3) {
4) print("Hello world");
5) }
In Python:
1) print("Hello World")
In C:
1) #include <stdio.h>
2)
3) void main()
4) {
5) int a,b;
6) a =10;
7) b=20;
8) printf("The Sum:%d",(a+b));
9) }
In Python:
1) a=10
2) b=20
3) print("The Sum:",(a+b))
The name Python was selected from the TV Show "The Complete Monty Python's Circus", which was
broad casted in BBC from 1969 to 1974. Guido developed Python language by taking almost all
programming features from0different languages
1. Functional Programming Features from C
2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3
@yadavnikhilrao
1
Most of syntax in Python Derived from C and ABC languages.
Where we can use Python: - We can use everywhere. The most common important application areas are:
Note: Internally Google and YouTube use Python coding NASA and Network Stock Exchange Applications
developed by Python. Top Software companies like Google, Microsoft, IBM, Yahoo using Python.
Features of Python:
1. Simple and easy to learn:
Python is a simple programming language. When we read Python program, we can feel like reading
english statements. The syntaxes are very simple and only 30+ keywords are available.
When compared with other languages, we can write programs with very less number of lines.
Hence more simplicity. We can reduce development and cost of the project.
We can use Python software without any licence and it is freeware. Its source code is open,
So that we can we can customize based on our requirement.
Python is high level programming language and hence it is programmer friendly language.
Being a programmer we are not required to concentrate low level activities like memory management
and security etc...
4. Platform Independent:
Once we write a Python program, it can run on any platform without rewriting once again.
Internally PVM is responsible to convert into machine understandable form.
5. Portability:
Python programs are portable. i.e. we can migrate from one platform to another platform very easily.
Python programs will provide same results on any paltform.
6. Interpreted:
We are not required to compile Python programs explicitly. Internally Python interpreter will take care that
compilation. If compilation fails interpreter raised syntax errors. Once compilation success then PVM
(Python Virtual Machine) is responsible to execute.
@yadavnikhilrao
2
7. Dynamically Typed:
In Python we are not required to declare type for variables. Whenever we are assigning the value, based on
value, type will be allocated automatically. Hence Python is considered as dynamically typed language. But
Java etc. are Statically Typed Languages b'z we have to provide type at the beginning only.
This dynamic typing nature will provide more flexibility to the programmer.
Python language supports both procedure oriented (like C, Pascal etc.) and object oriented (like C++,
Java) features.
Hence we can get benefits of both like security and reusability etc.
9. Interpreted:
We are not required to compile Python programs explicitly. Internally Python interpreter will take care that
compilation. If compilation fails interpreter raised syntax errors. Once compilation success then PVM
(Python Virtual Machine) is responsible to execute.
10. Extensible:
We can use other language programs in Python. The main advantages of this approach are:
11. Embedded:
Limitations of Python:
1. Performance wise not up to the mark b'z it is interpreted language.
2. Not using for mobile Applications
Python Versions:
Current versions
Python 3.6.1 Python 2.7.13
@yadavnikhilrao
3
Identifiers
A name in Python program is called identifier.0It can be class name or function name or module name
or variable name.
a = 10
By mistake if we are using any other symbol like $ then we will get syntax error.
cash = 10 √
ca$h = 20 *
123total *
total123 √
3. Identifiers are case sensitive. Of course Python language is case sensitive language.
Total = 10
TOTAL = 999
print(total) #10
print(TOTAL) #999
Rules:-
123total *
total123 √
java2share √
ca$h *
abc_abc √
def *
if *
@yadavnikhilrao
4
Note:
Eg: __add__
Reserved Words:
In Python some words are reserved to represent some meaning or functionality. Such type of words are
called reserved words.
Note:
True
False
None
Eg:
a= true *
a=True √
In [1]:
help('keywords')
Here is a list of the Python keywords. Enter any keyword to get more help
@yadavnikhilrao
5
@yadavnikhilrao
6
Data Types:
Data Type represent the type of data present inside a variable. In Python we are not required to specify the
type explicitly. Based on value provided, the type will be assigned automatically.
Hence Python is Dynamically Typed Language.
1. int
2. float
3. complex
4. bool
5. str
6. bytes
7. bytearray
8. range
9. list
10. tuple
11. set
12. frozenset
13. dict
14. None
Eg:
a=10
type(a) #int
Note: In Python2 we have long data type to represent very large integral values. But in Python3 there is
no long type explicitly and we can represent long values also by using int type only.
1. Decimal form
2. Binary form
3. Octal form
4. Hexa decimal form
@yadavnikhilrao
7
Note: Being a programmer we can specify literal values in decimal, binary,
octal and hexa decimal forms. But PVM will always provide values only in decimal form.
1) a=10
2) b=0o10
3) c=0X10
4) d=0B10
5) print(a) 10
6) print(c) 16
8) print(d) 2
Eg:
f=1.234
type(f) float
We can also represent floating point values by using exponential form (scientific notation)
Eg:
f=1.2e3
print(f) 1200.0
The main advantage of exponential form is we can represent big values in less memory.
Note: We can represent int values in decimal, binary, octal and hexa decimal forms.
But we can represent float values only by using decimal form.
In [2]:
# Example
f = 11.5
type(f)
Out[2]:
float
In [3]:
f = 1.2E5
print(f)
120000.0
@yadavnikhilrao
8
3) Complex Data Type:
A complex number is of the form a and b contain integers or floating point values
Complex numbers are the numbers that are expressed in the form of a+ib where, a,b are real numbers and 'i' is
an imaginary number called “iota”. The value of i = (√-1).
For example, 2+3i is a complex number, where 2 is a real number (Re) and 3i is an imaginary number (Im).
Eg:
3+5j
10+5.5j
0.5+0.1j
In the real part if we use int value then we can specify that either by decimal, octal, binary or hexa decimal
form.
Note: Complex data type has some inbuilt attributes to retrieve the real part and0imaginary part
We can use complex type generally in scientific Applications and electrical engineering0Applications.
In [4]:
# Example
c = 5+3j
type(c)
Out[4]:
complex
Eg:
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
@yadavnikhilrao
9
print(c)==>True
True+True==>2
True-False==>1
In [5]:
a=10
b=20
c=a<b
print(c)
True0
5) Str Type:
Str represents String data type.
s1='nikhil'
s1="nikhil"
By using single quotes or double quotes we cannot represent multi line string literals.
s1="nikhil yadav"
For this requirement we should go for triple single quotes(''') or triple double quotes(""")
s1='''nikhil
yadav'''
s1="""nikhil
yadav"""
We can also use triple quotes to use single quote or double quote in our String.
In [6]:
# example
name = 'nikhil'
type(name)
Out[6]:
str
@yadavnikhilrao
10
Slicing of Strings:
Slice means a piece[ ] operator is called slice operator, which can be used to retrieve parts of String.
------>012345
name = 'nikhil'
-6-5-4-3-2-1<------
==> length = 6
name = prakriti
- NEGATIVE INDEXING
Negative indices can also be used as shown in the figure above -1 corresponds to the
(length -1) index, -2 to (length -2).
name = "prakriti"
name[1:8:2] ---> 'rkii'
Note:
1. In Python the following data types are considered as Fundamental Data types
- int
- float
- complex
- bool
- str
2. In Python, we can represent char values also by using str type and explicitly char
type is not available.
@yadavnikhilrao
11
In [7]:
# Slicing
name = "nikhil"
name[1:8:2]
Out[7]:
'ihl'
In [8]:
# Indexing
name = 'prakriti'
name[3]
Out[8]:
'k'
Type Casting
We can convert one type value to another type. This conversion is called Typecasting or Type coersion.
1. int() - We can convert from any type to int except complex type.
2. float() - We can convert any type value to float type except complex type.
3. complex()
4. bool()
5. str()
All Fundamental Data types are immutable. i.e. once we creates an object, we cannot0perform any changes in
that object. If we are trying to change then with those changes a new object will be created.
This non-chargeable behaviour is called immutability.
In [9]:
x = [10,20,30,40]
b = bytes(x)
type(b)
print(b[0])
Out[9]:
bytes
10
@yadavnikhilrao
12
In [11]:
for i in b :
print(i)
10
20
30
40
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to0provide any other values
then we will get value error.
Conclusion 2:
Once we create bytes data type value, we cannot change its values; otherwise we will get TypeError.
x=[10,20,30,40]
b=bytes(x)
b[0]=100
In [12]:
# example
x=[10,20,30,40]
b = bytearray(x)
for i in b :
print(i)
10
20
30
40
In [13]:
b[0]=100
for i in b:
print(i)
100
20
30
40
@yadavnikhilrao
13
8) Range Data Type:
Range Data Type represents a sequence of numbers.
The elements present in range Data type are not modifiable. i.e. range Data type is immutable.
Form-1: range(10)
generate numbers from 0 to 9
Eg:
r=range(10)
for i in r : print(i) 0 to 9
Form-2: range(10,20)
generate numbers from 10 to 19
Eg:
r = range(10,20)
for i in r : print(i) 10 to 19
Form-3: range(10,20,2)
2 means increment value
Eg:
r = range(10,20,2)
for i in r : print(i) 10,12,14,16,18
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
@yadavnikhilrao
14
9) List data Type:
If we want to represent a group of values as a single entity where insertion order required to preserve and
duplicates are allowed then we should go for list data type.
In [15]:
# example
list=[10,10.5,'nikhil',True,10]
print(list)
In [16]:
list=[10,20,30,40]
list[2]
Out[16]:
30
List is growable in nature. i.e. based on our requirement we can increase or decrease the0size.
Note: An ordered, mutable, heterogeneous collection of elements is nothing but list, where duplicates
also allowed.
In [17]:
list=[10,20,30]
list.append("nikhil")
list
Out[17]:
In [18]:
@yadavnikhilrao
15
10) Tuple Data Type:
Tuple data type is exactly same as list data type except that it is immutable. i.e we cannot change values.
In [20]:
# example
t = (10,20,30,40)
type(t)
Out[20]:
tuple
1) t[0]=100
2) TypeError: 'tuple' object does not support item assignment
3) >>> t.append("nikhil")
4) AttributeError: 'tuple' object has no attribute 'append'
5) >>> t.remove(10)
6) AttributeError: 'tuple' object has no attribute 'remove'
Eg:
1) s={100,0,10,200,10,'nikhil'}
2) s # {0, 100, 'nikhil', 200, 10}
3) s[0] ==>TypeError: 'set' object does not support indexing
4)
5) set is growable in nature, based on our requirement we can increase or decrease the
size.
6)
7) >>> s.add(60)
8) >>> s
9) {0, 100, 'nikhil', 200, 10, 60}
10) >>> s.remove(100)
11) >>> s
12) {0, 'nikhil', 200, 10, 60}
@yadavnikhilrao
16
In [21]:
# example
s={100,0,100,200,10,'nikhil',10,15}
print(s)
1) s={10,20,30,40}
2) fs=frozenset(s)
3) type(fs)
4) <class 'frozenset'>
5) fs
6) frozenset({40, 10, 20, 30})
7) for i in fs:
8) print(i)
9) 40
10) 10
11) 20
12) 30
13)
14) fs.add(70)
15) AttributeError: 'frozenset' object has no attribute 'add'
16) fs.remove(10)
17) AttributeError: 'frozenset' object has no attribute 'remove'
In [22]:
# erxample
s={10,20,30,40}
fs=frozenset(s)
type(s)
Out[22]:
set
@yadavnikhilrao
17
13) Dict Data Type:
If we want to represent a group of values as key-value pairs then we should go for dict0data type.
Eg:
d={101:'nikhil',102:'ravi',103:'shiva'}
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an0entry with
duplicate key then old value will be replaced with new value.
Note: dict is mutable and the order wont be preserved.
Note:
1. In general we can use bytes and bytearray data types to represent binary information like images,
video files etc.
2. In Python2 long data type is available. But in Python3 it is not available and we can represent long
values also by using int type only.
3. In Python there is no char data type. Hence we can represent char values also by using str type.
In [23]:
# example
d={101:'nikhil',102:'ravi',103:'shiva'}
d[101]='sunny'
d
Out[23]:
In [24]:
d['a']='apple'
d['b']='banana'
print(d)
Eg:
def m1():
a=100
print(m1())
None
@yadavnikhilrao
18
Escape Characters:
In String literals we can use escape characters to associate a special meaning.
In [25]:
# example
s = 'nikhil\nyadav'
print(s)
nikhil
yadav
In [26]:
s = 'prakriti\tyadav'
print(s)
prakriti yadav
Constants:
Constants concept is not applicable in Python.
But it is convention to use only uppercase characters if we don’t want to change value.
MAX_VALUE=10
@yadavnikhilrao
19
Operators:
Operator is a symbol that performs certain operations. Python provides the following set of operators
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
** ==> Exponent operator or power operator
In [27]:
# example
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)
a+b = 12
a-b = 8
a*b = 20
a/b = 5.0
a//b = 5
a%b = 0
a**b = 100
Eg:
@yadavnikhilrao
20
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.
Note:
1) >>> "nikhil"+10
2) TypeError: must be str, not int
3) >>> "nikhil"+"10"
4) 'nikhil10'
If we use * operator for str type then compulsory one argument should be int and other
argument should be str type.
2*"nikhil"
"nikhil"*2
Note: For any number x, x/0 and x%0 always raises "ZeroDivisionError"
10/0
10.0/0
2. Relational Operators:
In [28]:
# >,>=,<,<=
a=10
b=20
a > b is False
a >= b is False
a < b is True
a <= b is True
@yadavnikhilrao
21
Equality operators:
In [29]:
# ==,!=
# We can apply these operators for any type even for incompatible types also.
10==20
Out[29]:
False
In [30]:
10!= 20
Out[30]:
True
In [31]:
False==False
Out[31]:
True
In [32]:
10=="nikhil"
Out[32]:
False
3. Logical Operators:
and, or ,not
and ==> If both arguments are True then only result is True0
or ====> If atleast one arugemnt is True then result is
True0 not ==> complement
0 means False
non-zero means True
empty string is always treated as False
@yadavnikhilrao
22
4. Bitwise Operators:
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.
&,|,^,~,<<,>>
print(4&5) ==>valid
print(10.5 & 5.6) ==>
TypeError: unsupported operand type(s) for &: 'float' and 'float'
print(True & True) ==>valid
In [33]:
print(4&5)
40
& ==> If both bits are 1 then only result is 1 otherwise result is 0 |
==> If atleast one bit is 1 then result is 1 otherwise result is 0 ^
==>If bits are different then only result is 1 otherwise result is 0 ~
==>bitwise complement operator
print(4&5) ==>4
print(4|5) ==>5
print(4^5) ==>1
5. Assignment Operators:
Eg:
x=100We can combine assignment operator with some other operator to form compound
assignment operator.
The following is the list of all possible compound assignment operators in Python.
+= | **=
-= | &=
*= | |=
/= | |=
%= | ^=
//= | >>=
@yadavnikhilrao
23
In [34]:
# example
x=10
x+=20
print(x)
x&=5
print(x)
30
4
6. Special operators:
1. Membership operators
2. Identity operators
a. 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)
in --> Returns True if the given object present 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)
print('d' in x)
print('d' not in x)
print('Python' in x)
In [37]:
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1)
print("tunny" in list1)
print("tunny" not in list1)
True
False
True
@yadavnikhilrao
24
b. Identity Operators
1. is
2. is not
In [35]:
# example
a=10 b=10
print(a is b)
x=True y=True
print(x is y)
True
True
In [36]:
# Note: We can use is operator for address comparison whereas == operator for content comp
list1=["one","two","three"]
list2=["one","two","three"]
print(id(list1))
print(id(list2))
print(list1 is list2)
print(list1 is not list2)
print(list1 == list2)
2049112833536
2049112833344
False
True
True
Ternary Operator:
Syntax:
If condition is True then firstValue will be considered else secondValue will be considered.
In [38]:
# Eg 1:
a,b=10,20
x=30 if a<b else 40
print(x)
30
@yadavnikhilrao
25
In [39]:
# Eg 2: Read two numbers from the keyboard and print minimum value
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
if a<b:
print("Minimum Value:",a)
else:
print("Minimum Value:",b)
Operator Precedence:
If multiple operators present then which operator will be evaluated first is decided by operator
precedence. Eg:-
print(3+10*2) --> 23
print((3+10)*2) --> 26
() --> Parenthesis
** --> exponential operator
~,- --> Bitwise complement operator,unary minus operator
*,/,%,// --> multiplication,division,modulo,floor division
+,- --> addition,subtraction
<<,>> --> Left and Right Shift
& --> bitwise And
& ^ --> Bitwise X-OR
& --> Bitwise OR0
>,>=,<,<=, ==, != --> Relational or Comparison operators
=,+=,-=,*= --> Assignment operators is ,
is not --> Identity Operators
in , not in --> Membership operators
not --> Logical not
and --> Logical and
or --> Logical or
In [40]:
#example
a=30
b=20
c=10
d=5
print((a+b)*c/d)
print((a+b)*(c/d))
print(a+(b*c)/d)
100.0
100.0
70.0
@yadavnikhilrao
26
Step: 1 Learn the Basics - Syntax, Step: 2 Conditionals, Loops, Functions,
Variables, Data Types Built-in-Functions
View profile
@yadavnikhilrao
27