PP-Unit 1-Notes
PP-Unit 1-Notes
History of Python
Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other
scripting languages.
At the time when he began implementing Python, Guido van
Rossum was also reading the published scripts from "Monty
Python's Flying Circus" (a BBC comedy series from the seventies,
in the unlikely case you didn't know). It occurred to him that he
needed a name that was short, unique, and slightly mysterious, so
he decided to call the language Python.
Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing its progress.
Python 1.0 was released on 20 February, 1991.
Python 2.0 was released on 16 October 2000 and had many major
new features, including a cycle detecting garbage collector and
1
Python Programming Unit:1
Python Features:
Python's features include:
Free and Open Source: Python is an open source software i.e.,
anyone can freely distribute it, read the source code, edit it, and
even use the code to write new (free) programs.
Simple: Python is a simple and a small language. Reading a
program written in puthon feels almost like reading English.
Easy-to-learn: Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the
language quickly.
Easy-to-read: Python code is more clearly defined and visible to
the eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Versatile: Python supports development of a wide range of
applications ranging from simple text processing to WWW
browsers to games.
High-level language: Python is a high-level language.
Object Oriented: Python is a powerful language for OOP concepts,
especially when compared to languages like C++ or Java.
Interpreted: Python program is processed at run-time by the
interpreter. So, there is no need to compile a program before
executing it. We can simply run the program.
A broad standard library: Python's bulk of the library is very
portable and cross- platform compatible on UNIX, Windows, and
2
Python Programming Unit:1
Macintosh.
Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of
code.
Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial
databases.
GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of UNIX.
Multi-threaded: Python supports multi-threading, i.e executing
more than one process of program simultaneously.
Scalable: Python provides a better structure and support for large
programs than shell scripting.
Robust: Python programmers cannot manipulate memory directly.
For every syntactical mistake, a simple and easy to interpret
message is displayed.
3
Python Programming Unit:1
4
Python Programming Unit:1
5
Python Programming Unit:1
Programming-in-the-large support
Finally, for building larger systems, Python includes tools
such as modules, classes, and exceptions; they allow you to
organize systems into components, do OOP, and handle events
gracefully.
It's Mixable
Python programs can be easily "glued" to components
written in other languages. In technical terms, by employing the
Python/C integration APIs, Python programs can be both extended
by (called to) components written in C or C++, and embedded in
(called by) C or C++ programs. That means you can add
functionality to the Python system as needed and use Python
programs within other environments or systems.
7
Python Programming Unit:1
as an application language.
7. Maya, a powerful integrated 3D modeling and animation system,
provides a Python scripting API.
8. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use
Python for hardware testing.
9. NASA, Los Alamos, Fermilab, JPL, and others use Python for
scientific programming tasks.
Once your program has been compiled to byte code (or the byte
code has been loaded from existing .pyc file), it is shipped off for
execution to something generally known as the python virtual machine
(PVM).
Applications of Python:
Python is a high-level general purpose programming language that is
used to develop a wide range of applications including
1. Systems Programming
2. GUIs
3. Internet Scripting
4. Component Integration
5. Database Programming
6. Rapid Prototyping
8
Python Programming Unit:1
Limitations of Python
Speed -
Python is slower than C or C++.
Mobile Development
Python is not a very good language for mobile development . It is
seen as a weak language for mobile computing. This is the reason very
few mobile applications are built in it like Carbonnelle.
Memory Consumption
Python is not a good choice for memory intensive tasks. Due to
the flexibility of the data-types, Python's memory consumption is also
high.
Database Access
As compared to the popular technologies like JDBC and ODBC,
the Python's database access layer is found to be bit underdeveloped
and primitive . However, it cannot be applied in the enterprises that
need smooth interaction of complex legacy data .
Runtime Errors
Python programmers cited several issues with the design of the
language. Because the language is dynamically typed , it requires more
testing and has errors that only show up at runtime .
Running Python:
Python is also considered as an interpreted language because Python programs
9
Python Programming Unit:1
Interactive Mode:
Interactive Mode, as the name suggests, allows us to interact with OS. Hear,
when we type Python statement, interpreter displays the result(s)
immediately. That means, when we type Python expression / statement /
command after the prompt (>>>), the Python immediately responses with the
output of it.
Let's see what will happen when we type print "WELCOME TO PACEITS" after
the prompt.
WELCOME TO KMIT
Example:
15
>>> x=10
10
Python Programming Unit:1
Script Mode:
11
Python Programming Unit:1
Output:
IDLE
Most Python installations contain a rudimentary IDE called IDLE. The
name ostensibly stands for Integrated Development and Learning
12
Python Programming Unit:1
The procedure for running IDLE varies from one operating system to
another.
Using IDLE
Once IDLE is installed and you have started it successfully, you should
see a window titled Python 3.x.x Shell, where 3.x.x corresponds to
your version of Python:
The >>> prompt
should look
familiar. You
can type REPL
commands
interactively,
just like when you
started the
interpreter
from a
console
window. Mindful of the qi of the universe, display Hello,
World! again:
13
Python Programming Unit:1
The interpreter behaves more or less the same as when you ran it
directly from the console. The IDLE interface adds the perk of
displaying different syntactic elements in distinct colors to make things
more readable.
You can also create script files and run them in IDLE. From the Shell
window menu, select File → New File. That should open an additional
editing window. Type in the code to be executed:
14
Python Programming Unit:1
Once both windows are open, you can switch back and forth, editing
the code in one window, running it and displaying its output in the
other. In that way, IDLE provides a rudimentary Python development
platform.
Running Python:
b. Running Python Interpreter:
Python comes with an interactive interpreter. When you type
15
Python Programming Unit:1
Now you can type any valid python expression at the prompt.
Python reads the typed expression, evaluates it and prints the result.
And run this program by calling python hello.py. Make sure you
change to the directory where you saved the file before doing it.
16
Python Programming Unit:1
Python Comments
Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program. Comments enhance
the readability of the code and help the programmers to understand the
code very carefully. There are three types of comments in Python –
Single line Comments
Multiline Comments
Docstring Comments
Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no
white spaces and lasts till the end of the line. If the comment exceeds
one line then put a hashtag on the next line and continue the comment.
Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See
the following code snippet demonstrating single line comment:
Example:
# Hello World Demo
Print(“Hello World”)
Multi-Line Comments
Python does not provide the option for multiline comments. However,
there are different ways through which we can write multiline
comments.
# multiline comments
print("Multiline comments")
17
Python Programming Unit:1
Output
Multiline comments
Python ignores the string literals that are not assigned to a variable so
we can use these string literals as a comment.
Example 1:
Python3
On executing the above code we can see that there will not be any
output so we use the strings with triple quotes(“””) as multiline
comments.
Python3
multiline comments"""
print("Multiline comments")
Output
Multiline comments
Python Docstring
Python docstring is the string literals with triple quotes that are
appeared right after the function. It is used to associate documentation
that has been written with Python modules, functions, classes, and
methods. It is added right below the functions, modules, or classes to
18
Python Programming Unit:1
describe what they do. In Python, the docstring is then made available
via the __doc__ attribute.
Example:
Python3
return a*b
print(multiply.__doc__)
Output:
Multiplies the value of a and b
Variables:
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in
memory.
An Identity,
A type, and
A value.
A. Identity of the object is its address in memory and does not get
change once it is created. We may know
19
Python Programming Unit:1
it by typing id (variable)
B. Type (i.e data type) is a set of values, and the allowable operations
on those values.
C. Value: Value is any number or a letter or string. To bind value
to a variable, we use assignment operator (=).
For example –
Program for assignments to variables
20
Python Programming Unit:1
x=y=z=0
print(x)
print(y)
print(z)
Variables : Delete
● In languages like C, C++, Java , PHP variable used within a function will
be lost once you leave the function.
21
Python Programming Unit:1
the memory that a variable occupies once I've finished with it?
In this case, the variable name still exists but it contains no data,
b) You can actually remove (del) the variable name itself from the
symbol table,
Python
queue = None
del queue
Example:
>>> a = 1
>>> a
>>> a = None
>>> a
>>> del a
>>> a
22
Python Programming Unit:1
KEYWORDS
The following list shows the Python keywords. These are
reserved words and you cannot use them as constant or variable or any
other identifier names. All the Python keywords contain lowercase
letters only.
INPUT Function: input()
To get input from the user you can use the input function. When
the input function is called the program stops running the program,
prompts the user to enter something at the keyboard by printing a
string called the prompt to the screen, and then waits for the user to
press the Enter key. The user types a string of characters and presses
enter. Then the input function returns that string and Python continues
running the program by executing the next statement after the input
statement.
Python provides the function input(). input has an optional
parameter, which is the prompt string.
Syntax: input([optional])
For example,
>>> name=input()
pace
>>> print(name)
23
Python Programming Unit:1
Output
Enter value of x:5
'Enter value of y:10
The value of x after swapping: 10
The value of y after swapping: 5
Indentation
Code blocks are identified by indentation rather than using
symbols like curly braces. Without extra symbols, programs are easier
to read. Also, indentation clearly identifies which block of code a
statement belongs to. Of course, code blocks can consist of single
statements, too. When one is new to Python, indentation may come as
a surprise. Humans generally prefer to avoid change, so perhaps after
many years of coding with brace delimitation, the first impression of
using pure indentation may not be completely positive. However,
recall that two of Python's features are that it is simplistic in nature and
easy to read.
24
Python Programming Unit:1
Numbers:
DATA TYPES
25
Python Programming Unit:1
3.2 Lists: List is also a sequence of values of any type. Values in the
list are called elements / items. These are mutable and
indexed/ordered. List is enclosed in square brackets ([]).
5.Mapping: This data type is unordered and mutable. Dictionaries fall under
Mappings.
5.1Dictionaries:
It can store any number of python objects. What they store is a key -
value pairs, which are accessed using key. Dictionary is enclosed in
curly brackets ({}).
Operators:
1. Arithmetic Operators
26
Python Programming Unit:1
27
Python Programming Unit:1
removed.
a = 21
b = 10
c=0
c=a+b
print("a+b=",c
)
c=a-b
print("a-
b=" ,c)
c=a*b
print("a*b=" ,c
)
c=a/b
print("a/
b=" ,c)
c=a%b
print("a%b=",
c)
a=2b=3
c = a**b
print("a pow b=", c) a = 10
b=5
c = a//b
print("a//b=" ,c)
Output
28
Python Programming Unit:1
a+b= 31
a-b= 11
a*b= 210
a/b= 2.1
a%b= 1
a pow b= 8
a//b= 2
Operat
or Description Example
true.
If the value of left operand is less than the
< value of (a < b) is true.
29
Python Programming Unit:1
becomes true.
If the value of left operand is less than or
<= equal to (a <= b) is true.
the value of right operand, then
condition
becomes true.
Ex::
a = 21
b = 10
if ( a == b ):
print( "Line 1 - a is equal to b")
else:
print( "Line 1 - a is not equal to b")
Output:
Line 1 - a is not equal to b
1.3 Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then:
30
Python Programming Unit:1
to c = c +
assign the result to left operand a
It subtracts right operand from the c -= a is
-= left equivalent
operand and assign the result to left to c = c -
Subtract operand a
%
a
*
Performs exponential (power) *
**= calculation on c = a is
operators and assign value to the left equivalent to c =
Exponent operand c
*
*
a
//= It performs floor division on operators c //= a is
31
Python Programming Unit:1
and equivalent
to c = c //
Floor assign value to the left operand a
Division
Example:
4. a = 21 b = 10 c = 0
c=a+b
print( "Line 1 - Value of c is ", c )
c += a
print ("Line 2 - Value of c is ", c )
5. c *= a
print ("Line 3 - Value of c is ", c)
c /= a
print( "Line 4 - Value of c is ", c )
c=2
c %= a
print ("Line 5 - Value of c is ", c )
c **= a
print( "Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
-----------------
Operato
r Description Example
Operator copies a bit to the result
& if it (a & b) = 12
Binary AND exists in both operands. (means 0000 1100)
It copies a bit if it exists in
| Binary OR either (a | b) = 61
operand. (means 0011 1101)
It copies the bit if it is set in one
^ Binary XOR operand (a ^ b) = 49 (means 0011 0001)
but not both.
It is unary and has the effect of
~ 'flipping' (~a ) = -61 (means 1100 0011 in 2's
O
n
e complement form due to a signed
Binary sbits. binary
Complement number.
The left operands value is moved
<< left by a << 2 = 240
Binary Left the number of bits specified by the
Shift right (means 1111 0000)
33
Python Programming Unit:1
operand.
The left operands value is moved
>> right a >> 2 = 15
R
i
g
h
t
S
h
Binary i
right fby the number of bits specified by
shift tthe right operand (means 0000 1111)
Example:
a = 60 # 60 = 0011 1100
c=0
print("a&b=",c)
c = a | b; # 61 = 0011 1101
print("a|b=",c)
c = a ^ b; # 49 = 0011 0001
print("a^b=",c)
print("~a=",c)
34
Python Programming Unit:1
print("a<<2",c)
print("a>>2",c)
Output:
#a&b= 12
#a|b= 61
#a^b= 49
#~a= -61
#a<<2 240
#a>>2 15
AND)
If any of the two operands are non-
or zero (a or b) is true.
(Logical then condition becomes true.
OR)
35
Python Programming Unit:1
NOT)
sequence y.
Operato
r Description Example
36
Python Programming Unit:1
otherwise.
is
no Evaluates to false if the variables on either x is not y, here is not
t side of results
the operator point to the same object
and true in 1 if id(x) is not equal to
otherwise. id(y).
Operator Description
** Exponentiation (raise to the power)
Ccomplement, unary plus and
~+- minus (method
names for the last two are +@ and -
@)
Multiply, divide, modulo and floor
* / % // division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
37
Python Programming Unit:1
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c #( 30 *
/d 15 ) / 5
print ("Value of (a + b) * c / d
is ", e)
e = ((a + b) * # (30 * 15
38
Python Programming Unit:1
c) / d )/5
e = (a + b) * # (30) *
(c / d); (15/5)
print( "Value of (a + b) * (c / d)
is ", e)
e = a + (b * c) # 20 +
/ d; (150/5)
print("Value of a + (b * c) / d is ", e)
When you execute the above program, it produces the following result:
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
syntax:-
if test expression:
statement(s)
39
Python Programming Unit:1
Program
a = int(input(“enter a value”))
b = int(input(“enter b value”))
if a == b:
print('yes')
if...else Statement
syntax:-
if test expression:
Body of if
else:
Body of else
if a>b:
large=a
else:
large=b
print(large)
40
Python Programming Unit:1
if...elif...else
syntax:-
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Nested if statements
We can have a if...elif...else statement inside
another if...elif...elsestatement. This is called nesting in computer
programming.
41
Python Programming Unit:1
for loop
Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.
example:-
# Program to find the sum of all numbers stored in a list
42
Python Programming Unit:1
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
Output
Example:-
43
Python Programming Unit:1
o/p
I like pop
I like rock
I like jazz
Ex:-
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
o/p
0
1
5
No items left.
44
Python Programming Unit:1
string2 = ""
i = len(string1)-1
while(i>=0):
i = i-1
Output:
While loop
The while loop in Python is used to iterate over a block of code as long
as the test expression (condition) is true.
We generally use this loop when we don't know beforehand, the
number of times to iterate.
Syntax
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression evaluates to True. After one
45
Python Programming Unit:1
Ex:-
# Program to add natural numbers upto n
# sum = 1+2+3+...+n
n = int(input("Enter n: "))
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
o/p
Enter n: 10
The sum is 55
46
Python Programming Unit:1
In such case, the else part is ignored. Hence, a while loop's else part
runs if no break occurs and the condition is false.
Here is an example to illustrate this.
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
o/p
Inside loop
Inside loop
Inside loop
Inside else
break statement
The break statement terminates the loop containing it. Control of the
program flows to the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.
Syntax of break
break
# Use of break statement inside loop
47
Python Programming Unit:1
print("The end")
o/p
s
t
r
The end
continue statement
The continue statement is used to skip the rest of the code inside a
loop for the current iteration only. Loop does not terminate but
continues on with the next iteration.
Syntax
continue
print("The end")
o/p
s
t
r
n
g
The end
48
Python Programming Unit:1
Pass
Syntax of pass
pass
PROGRAMS
temp = a
a=y
b = temp
o/p
Enter value of a: 10
Enter value of b: 20
49
Python Programming Unit:1
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
o/p
The sum is 48
o/p
50
Python Programming Unit:1
o/p
The H.C.F. of 54 and 24 is 6
Program to check if the input number is prime or not take input from
the user
o/p
Enter a number: 13
Sample Output
13 is a prime number
Sample Input
Enter a number :25
Sample Output
51
Python Programming Unit:1
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
o/p
Enter a number: 6
The factorial of 6 is 720
ARMSTRONG NUMBER
O/P
Palindrome number
53
Python Programming Unit:1
else:
print("Not Palindrome number")
o/p
Reverse of number
o/p
for i in range(1,11):
print(n,'x',i,'=',n*i)
o/p
54
Python Programming Unit:1
Functions
Syntax:-
def function_name(parameters):
"""docstring"""
statement(s)
def greet(name):
"""This function greets to the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
55
Python Programming Unit:1
if test:
def func():
…
else:
def func():
…
The def statement makes a function but does not call it. After the def
has run, you can call (run) the function in your program by adding
parentheses after the function‘s name.
Function Call
Syntax:- func ()
56
Python Programming Unit:1
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
output
output
Function Arguments
Default arguments:
57
Python Programming Unit:1
Default values indicate that the function argument will take that value if
no argument value is passed during function call. The default value is
assigned by using assignment (=) operator.
output
Name: joy
Id 50
Name: joy
Id 101
Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition
Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
58
Python Programming Unit:1
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters.
output
Name: miki
Age 50
Variable-length arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-
length arguments and are not named in the function definition, unlike
required and default arguments.
output
Output is:
10
Output is:
70
59
Python Programming Unit:1
60
50
The Anonymous Functions(Lambda)
These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use
the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value
in the form of an expression. They cannot contain commands or multiple
expressions.
An anonymous function cannot be a direct call to print because lambda
requires an expression
Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
Although it appears that lambda's are a one-line version of a function, they
are not equivalent to inline statements in C or C++, whose purpose is by
passing function stack allocation during invocation for performance
reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is
as follows −
ex:-
output
Value of total : 30
Value of total : 40
60
Python Programming Unit:1
Ex:-
output
10
61
Python Programming Unit:1
Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions.
money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
money = money + 1
print( money)
AddMoney()
print (money)
62