Unit-1 Part-1
Unit-1 Part-1
Introduction
• Python is a general purpose high level programming language.
• But officially Python was made available to public in 1991. The official Date of
Birth for Python is : Feb 20th 1991.
1) High-level
Python is a high-level programming language that makes it easy to learn. Python doesn’t
require youto understand the details of the computer in order to develop programs
efficiently.
2) General-purpose
Python is a general-purpose language. It means that you can use Python in various domains
including:
• Web applications
• Big data applications
• Testing
• Automation
• Data science, machine learning, and AI
• Desktop software
• Mobile apps
The targeted language like SQL which can be used for querying data from relational databases.
3) Interpreted
Python is an interpreted language. To develop a Python program, you write Python code
into a file called source code.
To execute the source code, you need to convert it to the machine language that the
computer can understand. And the Python interpreter turns the source code, line by line,
once at a time, into the machine code when the Python program executes.
Compiled languages like Java and C# use a compiler that compiles the whole source code
before theprogram executes.
We can use everywhere. The most common important application areas are
Features of Python:
1. Simple and easy to learn:
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 platform.
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 automatically. Hence
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.
8. Interpreted:
If compilation fails interpreter raised syntax errors. Once compilation success then
PVM (Python Virtual Machine) is responsible to execute.
9. Extensible:
1. We can use other language programs in Python. The We can use already existing
legacy non-Python code
2. We can improve performance of the application
10. Embedded:
Python has a rich inbuilt library. Being a programmer we can use this library directly
and we are not responsible to implement the functionality.
Python History
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection
systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-3
o There is a fact behind choosing the name Python. Guido van Rossum was reading
the script of a popular BBC comedy series "Monty Python's Flying Circus". It was
late on-air 1970s.
o Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So
he decided to select naming Python after the "Monty Python's Flying Circus" for
their newly created programming language.
With Python installed, we can now write and run our first Python program.
All Python files end with the “.py” extension. You can create, edit, and save Python files
with any text editor.
To create your first Python file, navigate to the folder that you would like to create your file
in and create a file called test.py. Next, open this file up in a text editor and type in the
following code:
print("Hello, World!")
Save your file, and in the terminal, navigate to the file’s location. Then, run the file by
calling python test.py. This line instructs your Python interpreter to execute the command
you just wrote. You should see the correct output:
Hello, World!
The IDE stands for Integrated Development Environment. There are various IDEs
but Pycharm is Python's most popular and useful text editor among them. It is recommended
for developing large and more complex applications.
Create a new project and then create a new Python file using the .py extension.
Then select run option from menu and click on Run module option it will display the output.
Tokens in Python
a) Identifiers
b) Keywords
c) Data types
d) Operators
Identifiers:
By mistake if we are using any other symbol like $ then we will get syntax
error.
• cash = 10 √
• ca$h =20
2. Identifier should not starts with digit
• 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
Identifier:
Note:
• 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,
with
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
['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:
1.type()
to check the type of variable
2. id()
to get address of object
3. print()
to print the value
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
1. Decimal form(base-10):
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg:
a=0B1111
3. Octal Form(Base-8):
Eg:
a=0o123
a=0o786
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=0XBee
We can use float data type to represent floating point values (decimal values)
Eg: f=1.234
type(f) float
The main advantage of exponential form is we can represent big values in less
memory.
Complex Data Type:
j2 = -1
a+
j=
bj
Real Part Imaginary√−1
Part
False as 0 b=True
type(b) =>bool
str type:
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
Eg: test.py:
1) a=10
2) b=2
3) print('a+b=',a+b)
4) print('a-b=',a-b)
5) print('a*b=',a*b)
6) print('a/b=',a/b)
7) print('a//b=',a//b)
8) print('a%b=',a%b)
9) print('a**b=',a**b)
Output:
1) a+b= 12
2) a-b= 8
3) a*b= 20
4) a/b= 5.0
5) a//b= 5
6) a%b= 0
7) a**b= 100
Relational Operators:
>,
>=
,<,
<=
Eg
1:
1) a=10
2) b=20
3) print("a > b is ",a>b)
4) print("a >= b is ",a>=b)
5) print("a < b is ",a<b)
6) print("a <= b is ",a<=b)
Output:
1) a > b is False
2) a >= b is False
3) a < b is True
4) a <= b is True
equality operators:
== , !=
We can apply these operators for any type even for incompatible types also
1) >>> 10==20
2) False
3) >>> 10!= 20
4) True
5) >>> 10==True
6) False
7) >>> False==False
8) True
9) >>> "durga"=="durga"
10) True
11) >>> 10=="durga"
12) False
Logical Operators:
and, or ,not
We can apply for all types.
& ==> 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 1==>0 &
0==>1
<< ==>Bitwise Left shift
>> ==>Bitwise Right Shift
print(4&5) ==>4
print(4|5) ==>5
print(4^5) ==>1
Operator Description
& If both bits are 1 then only result is 1 otherwise result is 0
| If at least 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 i.e. 1 means 0 and 0 means 1
>> Bitwise Left shift Operator
<< Bitwise Right shift Operator
Assignment Operators:
We can use assignment operator to assign value to the variable.
Eg:
x=10
Special operators:
1. Identity Operators
2. Membership operators
1. Identity Operators
We can use identity operators for address
comparison. 2 identity operators are
available
1. is
2. is not
1) a=10
2) b=10
3) print(a is b) True
4) x=True
5) y=True
6) print( x is y) True
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)
Collection
Eg:
Indentation is the leading whitespace (spaces or/and tabs) before any statement in Python.
The reason why indentation is important in python is that the indentation serves another
purpose other than code readability. Python treats the statements with the same indentation
level (statements with an equal number of whitespaces before them) as a single code block.
So whereas in languages like C, C++, etc. a block of code is represented by curly braces { },
in python a block is a group of statements that have the same Indentation level i.e same
number of leading whitespaces.
Example:
i=1
while(i<=6)
print(“value is “+str(i))
i=i+1
output:
value is 1
value is 2
value is 3
value is 4
value is 5
value is 6
I. Conditional Statements
1.if
if condition :
statement
or
if condition:
statement-1
statement -2
statement-n
Ex:
A=10
B=20
if(A>B):
print(“A is Big”)
o\p:
if-else:
if condition :
Action-1
else :
Action-2
Ex:
A=10
B=20
if(A>B):
print(“A is Big”)
else:
print(“B is Big”)
o\p:
B is Big
if-elif-else:
Syntax:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action
Eg:
1) brand=input("Enter Your Favourite Brand:")
2) if brand=="RC" :
3) print("It is childrens brand")
4) elif brand=="KF":
5) print("It is not that much kick")
6) elif brand=="FO":
7) print("Buy one get Free One")
8) else :
9) print("Other Brands are not recommended")
1. for loop
2. while loop
1) for loop:
If we want to execute some action for every element present in some
sequence(it may be string or collection)then we should go for for loop.
Syntax:
for x in
sequen
ce :
body
the sequence.
S=”hello”
for i in S:
print(i)
o/p:
hello
while loop:
If we want to execute a group of statements iteratively until some condition
false,then we should go for while loop.
Syntax:
while condition :
body
1)x=1
2)while x <=10:
3) print(x)
4) x=x+1
Nested Loops:
Sometimes we can take a loop inside another loop,which are also known
1) for i in range(4):
2) for j in range(4):
3) print("i=",i," j=",j)
4)
5) Output
6) D:\Python_classes>py test.py
7) i= 0 j= 0
8) i= 0 j= 1
9) i= 0 j= 2
10) i= 0 j= 3
11) i= 1 j= 0
12) i= 1 j= 1
13) i= 1 j= 2
14) i= 1 j= 3
15) i= 2 j= 0
16) i= 2 j= 1
17) i= 2 j= 2
18) i= 2 j= 3
19) i= 3 j= 0
20) i= 3 j= 1
21) i= 3 j= 2
22) i= 3 j= 3
break:
We can use break statement inside loops to break loop execution
based on some condition. It is used to exit from the iteration.
for i in range(10):
if i==7:
print("processing is enough..plz break")
break
print(i)
O/p:
0 1 2 3 4 5 6 processing is enough..plz break
continue:
We can use continue statement to skip current iteration and continue next
iteration.
1) for i in range(10):
2) if i%2==0:
3) continue
4) print(i)
5)
6) D:\Python_classes>py test.py
7) 1
8) 3
9) 5
10) 7
11) 9
pass statement:
pass is a keyword in Python.
pass
|- It is an empty statement
|- It is null statement
|- It won't do
anything
Eg:
if True: pass
==>valid