Introduction
Python is a general-purpose high-level programming language.
Python was developed by Guido Van Rossum 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.
Eg1: To print Hello world:
Java:
1) public class HelloWorld
2) {
3) p s v main (String[] args)
4) {
5) SOP("Hello world");
6) }
7) }
C:
1) #include<stdio.h>
2) void main()
3) {
4) printf("Hello world");
5) }
Python:
print("Hello World")
The name Python was selected from the TV Show
"The Complete Monty Python's Circus", which was broadcasted in
BBC from 1969 to 1974.
Guido developed Python language by taking almost all programming
features from different languages.
1. Functional Programming Features from C
(Functions, Loops, Control Structure)
2. Object Oriented Programming Features from C++
(Classes, objects, inheritance)
3. Scripting Language Features from Perl and Shell Script
(Scripting Syantax, Quick automation, Quick Compilation)
4. Modular Programming Features from Modula-3
(Modulas and packages)
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 are:
1. For developing Desktop Applications
2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. For developing games
6. For Data Analysis Applications
7. For Machine Learning
8. For developing Artificial Intelligence Applications
9. For IOT
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 readability and simplicity.
We can reduce development and cost of the project.
2. Freeware and Open Source:
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.
Eg: python is customized version of Python to work with Java
Applications.
3. High Level Programming language:
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. ie we can migrate from one platform to
another platform very easily. Python programs will provide same results
on any paltform.
6. 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 [Link]
Python is considered
as dynamically typed language.
But Java, C 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.
7. Both Procedure Oriented and Object Oriented:
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
8. 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.
9. Extensible:
We can use other language programs in Python.
The main advantages of this approach are:
1. We can use already existing legacy non-Python code
2. We can improve performance of the application
10. Embedded:
We can use Python programs in any other language programs.
i.e. we can embedd Python programs anywhere.
11. Extensive Library:
Python has a rich inbuilt library.
Being a programmer, we can use this library directly and we are not
responsible to implement the functionality.
Limitations of Python:
1. Performance wise not up to the mark b'z it is interpreted language.
2. Not using for mobile Applications
Flavors of Python:
[Link]:
It is the standard flavour of Python. It can be used to work with C language
Applications
2. Jayton or Python:
It is for Java Applications. It can run on JVM
3. Iron Python:
It is for C#.Net platform
[Link]:
The main advantage of PyPy is performance will be improved because JIT
compiler is
available inside PVM.
[Link]
For Ruby Platforms
6. Anaconda Python
It is specially designed for handling large volume of data processing.
Python Versions:
Python 1.0V introduced in Jan 1994
Python 2.0V introduced in October 2000
Python 3.0V introduced in December 2008
Reserved Words
In Python some words are reserved to represent some meaning or functionality.
Such type of words are called Reserved words.
There are 33 reserved words available in Python.
True, False, None
and, or, not, is
if, Elif, else
while, for, break, continue, return, in, yield
try, except, finally, raise, assert
import, from, as, class, def, pass, global, nonlocal, lambda, del, type
Note:
1. All Reserved words in Python contain only alphabet symbols.
2. Except the following 3 reserved words, all contain only lower-case alphabet
symbols.
True
False
None
E.g.: a= true
a=True √
Import keyword
keyword. Kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'Elif', 'else’, ‘except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or’, ‘pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
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.
Python contains the following inbuilt data types
1. int
2. float
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Note: Python contains several inbuilt functions
[Link]()
to check the type of variable
2. id()
to get address of object
10
10
20
a
a
b
a = 10
a = 20
a = 10
b = 10
3. print()
to print the value
In Python everything is object
int data type:
We can use int data type to represent whole numbers (integral values)
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.
how many ways we can represent int value?
We can represent int values in the following ways
1. Decimal form
2. Binary form
3. Octal form
4. Hexa decimal form
1. Decimal form(base-10):
It is the default number system in Python
The allowed digits are: 0 to 9
Eg: a =10
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg: a = 0B1111
a =0B123
a=b111
3. Octal Form(Base-8):
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O.
Eg: a=0o123
a=0o786
4. Hexa Decimal Form(Base-16):
The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed)
Literal value should be prefixed with 0x or 0X
Eg:
a =0XFACE
a =0XBeer
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.
a=10
b=0o10
c=0X10
d=0B10
print(a)10
print(b)8
print(c)16
print(d)2
Base Conversions
Python provide the following in-built functions for base conversions
[Link]():
We can use bin() to convert from any base to binary
Eg:
1) >>> bin(15)
2) '0b1111'
3) >>> bin(0o11)
4) '0b1001'
5) >>> bin(0X10)
6) '0b10000'
2. oct():
We can use oct() to convert from any base to octal
Eg:
1) >>> oct(10)
2) '0o12'
3) >>> oct(0B1111)
4) '0o17'
5) >>> oct(0X123)
6) '0o443'
3. hex():
We can use hex() to convert from any base to hexa decimal
Eg:
1) >>> hex(100)
2) '0x64'
3) >>> hex(0B111111)
4) '0x3f'
5) >>> hex(0o12345)
6) '0x14e5'
float data type:
We can use float data type to represent floating point values (decimal values)
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
instead of 'e' we can use 'E'
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.
Eg:
f=0B11.01
File "<stdin>", line 1
f=0B11.01
^
SyntaxError: invalid syntax
6)
7) >>> f=0o123.456
8) SyntaxError: invalid syntax
9)
10) >>> f=0X123.456
11) SyntaxError: invalid syntax
Complex Data Type:
A complex number is of the form
a+bj
a is real part
b is imaginary part
a and b contain intergers or floating point values
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.
But imaginary part should be specified only by using decimal form.
1) >>> a=0B11+5j
2) >>> a
3) (3+5j)
4) >>> a=3+0B11j
5) SyntaxError: invalid syntax
Even we can perform operations on complex type values.
1) >>> a=10+1.5j
2) >>> b=20+2.5j
3) >>> c=a+b
4) >>> print(c)
5) (30+4j)
6) >>> type(c)
7) <class 'complex'>
a + bj
Real Part Imaginary Part
j2 = -1
j=
Note: Complex data type has some inbuilt attributes to retrieve the real part and
imaginary part
c=10.5+3.6j
[Link]==>10.5
[Link]==>3.6
We can use complex type generally in scientific Applications and electrical
engineering
Applications.
[Link] data type:
We can use this data type to represent boolean values.
The only allowed values for this data type are:
True and False
Internally Python represents True as 1 and False as 0
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True
String Data Type
The most commonly used object in any project and in any programming
language is String only.
Hence we should aware complete information about String data type.
What is String?
Any sequence of characters within either single quotes or double quotes is
considered as a String.
Syntax: variable_name="data"
s='durga'
s="durga"
Note: In most of other languges like C, C++,Java, a single character within
single quotes is treated as char data type value. But in Python we are not having
char data [Link] it is treated as
String only.
Eg:
>>> ch='a'
>>> type(ch)
<class 'str'>
How to define multi-line String literals:
We can define multi-line String literals by using triple single or double quotes.
Eg:
>>> s='''softmusk
info
pvt ltd'''
We can also use triple quotes to use single quotes or double quotes as symbol
inside String literal.
Eg:
s='This is ' single quote symbol' ==>invalid
s=''This is \' single quote symbol ==>valid
s="This is ' single quote symbol"====>valid
s='This is “ double quotes symbol' ==>valid
s='The "Python Notes" by 'durga' is very helpful' ==>invalid
s="The "Python Notes" by 'durga' is very helpful"==>invalid
s='The \"Python Notes\" by \'durga\' is very helpful' ==>valid
s='''The "Python Notes" by 'durga' is very helpful''' ==>valid
How to access characters of a String:
We can access characters of a string by using the following ways.
1. By using index
2. By using slice operator
1. By using index:
Python supports both +ve and -ve index.
+ve index means left to right(Forward direction)
-ve index means right to left(Backward direction)
Eg:
s='softmusk'
# -8 -7 -6 -5 -4 -3 -2 -1
#s o f t m u s k
#0 1 2 3 4 5 6 7
Eg:
>>> s='softmusk'
>>> s[0]
's'
>>> s[4]
'm'
>>> s[-1]
'k'
>>> s[10]
IndexError: string index out of range
Note: If we are trying to access characters of a string with out of range index
then we will get error saying : IndexError
Accessing characters by using slice operator:
Syntax: s[bEginindex:endindex:step]
bEginindex:From where we have to consider slice(substring)
endindex: We have to terminate the slice(substring) at endindex-1
step: incremented value
Note: If we are not specifying bEgin index then it will consider from bEginning
of the [Link] we are not specifying end index then it will consider up to end of
the string
The default value for step is 1
Eg:
1) >>> s="Learning Python is very very easy!!!"
2) >>> s[Link]
3) 'earnin'
4) >>> s[1:7]
5) 'earnin'
6) >>> s[Link]
7) 'eri'
8) >>> s[:7]
9) 'Learnin'
10) >>> s[7:]
11) 'g Python is very very easy!!!'
12) >>> s[::]
13) 'Learning Python is very very easy!!!'
14) >>> s[:]
15) 'Learning Python is very very easy!!!'
16) >>> s[::-1]
17) '!!!ysae yrev yrev si nohtyP gninraeL'
Behaviour of slice operator:
s[bEgin:end:step]
step value can be either +ve or –ve
if +ve then it should be forward direction(left to right) and we have to consider
bEgin to end-1
if -ve then it should be backward direction(right to left) and we have to consider
bEgin to end+1
String Concatenation and Multiplication
Ex:
s1="soft"
s2="musk"
print(s1+s2)
print(s1+" "+s2)
print("raj"+" "+"kumar")
print(s1*3)
print((s1+" ")*3)
print(("raj"+" ")*3)
• String Split and Max Split
Ex:
s="python is very easy and it is oop and it is interpreter"
print(s)
s1=[Link](" ",3)
print(s1)
• String capitalize and title
Ex:
s="pyThon is vEry eaSy"
print(s)
s1=[Link]()
print(s1)
print([Link]())
• String upper and lower
Ex:
s="softmusk"
print(s)
print([Link]())
s="SOFTMUSK"
print(s)
print([Link]())
• String count
Ex:
s="python is very easy and it is oop and it is interpreter"
substring="is"
print([Link](substring))
print([Link]("and"))
print([Link]("is"))
print([Link]("x"))
print([Link](" "))
print([Link]('a'))
• String replace
Ex:
s="my name is soft"
print(s)
s1=[Link]("soft","mohan")
print(s1)
• String join
Ex:
print(",".join("RAJ"))
print(" ".join(["sai","mohan","raj","durga"]))
• String reverse
Ex:
print(" ".join(reversed("SAI")))
s="SAI"
print(s[::-1])
• String sort
Ex:
s="python is very easy"
print(s)
s1=[Link](" ")
print(s1)
print(type(s1))
[Link]()
print(s1)
[Link](reverse=True)
print(s1)
• String swap case
Ex:
s="DuRgAsOfT"
print(s)
print([Link]())
• String strip , lstrip, rstrip
Ex:
s=" durga "
print(s)
print([Link](" "))
s="adurga"
print(s)
print([Link]('a'))
print([Link]('a'))
print([Link]('a'))
• String length
Ex:
print(len("durga soft"))
• String find , index ,rindex
Ex:
s="python is very easy and it is oop and it is
interpreter"
print([Link]("is"))
print([Link]("x"))
print([Link]("is"))
#print([Link]("x"))
print([Link]("is"))
• String max, min
Ex:
s="softmusk"
print(max(s))
print(min(s))
s="SOFTMUSK"
print(max(s))
print(min(s))
• String partition
Ex:
s="python is very easy and it is oop"
s1=[Link]("is")
print(s1)
print(type(s1))
• String starts with , ends with
Ex:
s="soft musk"
print([Link]('s'))
print([Link]('S'))
print([Link]('s'))
print([Link]('T'))
print([Link]('K')
• String isdigit ,isalpha, isalnum
Ex:
s="12345"
print([Link]())
s="12345a"
print([Link]())
s="abcd"
print([Link]())
s='abcd12'
print([Link]())
s="abcd"
print([Link]())
s="1234"
print([Link]())
s="123abc"
print([Link]())
s="$%#%"
print([Link]())