UNIT II PSPP
UNIT II PSPP
om
3.5 Comments
4. Illustrative programs:
4.1 Exchange the values of two variables
4.2 Circulate the values of n variables
.c
4.3 Distance between two points.
ot
1. Python interpreter
sp
● Python is a cross-platform programming language, meaning, it runs on
multiple platforms like Windows, Mac OS X, Linux, Unix
● It is free and open source.
og
1. Interactive mode
2. Script Mode
ic
Interactive mode
cs
● Typing python in the command line will invoke the interpreter in interactive
mode.
>>> - is a prompt that indicates that the interpreter is ready for you to enter
th
code.
>>> 5 + 4
ru
9
● This prompt can be used as a calculator. To exit this mode type exit() or quit()
and press enter.
Script Mode
● This mode is used to execute Python program written in a file.
● Such a file is called a script.
● Python scripts have the extension .py
● For example: helloWorld.py
● To execute this file in script mode we simply write python helloWorld.py at the
command prompt.
bug: An error in a program.
debugging: The process of finding and removing any of the three kinds of
programming errors.
syntax: The structure of a program.
syntax error: An error in a program that makes it impossible to parse (and therefore
impossible to interpret).
exception: An error that is detected while the program is running.
semantics: The meaning of a program.
om
● The numbers with a decimal point belong to a type called float.
● The values written in quotes will be considered as string, even it’s an integer.
● If type of value is not known it can be interpreted as
.c
Eg: >>> type('Hello, World!')
<type 'str'>
ot
>>> type(17)
<type 'int'>
>>> type('17')
sp
<type 'str'>
>>> type('3.2')
<type 'str'>
og
❖ Numbers
❖ String
ic
❖ List
❖ Tuple
cs
❖ Dictionary
Python Numbers
th
● For example –
var1 =1
var2 =10
● You can also delete the reference to a number object by using the del statement.
● The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
Python Strings
● Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
● Python allows for either pairs of single or double quotes.
● Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the end.
● The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
● For example –
str = 'Python Programming' print str # Prints complete string
print str[0] # Prints first character of the string
print str[-1] # Prints last character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + " Course" # Prints concatenated string
om
This will produce the following result –
.c
Python Programming
P
ot
g
tho
thon Programmin
sp
Python ProgrammingPython Programming
Python Programming Course
og
Python Lists
● Lists are the most versatile of Python's compound data types.
● A list contains items separated by commas and enclosed within square brackets ([]).
bl
indexes starting at 0 in the beginning of the list and working their way to end -1.
● The plus (+) sign is the list concatenation operator, and the asterisk (*) is the
cs
repetition operator.
● For example −
list = [ 'Hai', 123 , 1.75, 'vinu', 100.25 ]
th
print list[0]
print list[-1]
print list[1:3]
print list[2:]
print smalllist * 2
print list + smalllist
Python Boolean
● A Boolean type was added to Python 2.3.
● Two new constants were added to the __builtin__ module,
● True and False.
● True and False are simply set to integer values of 1 and 0 and aren't a different type.
>>>bool(1)
True
om
>>>bool(0)
False
>>> False + 1
.c
1
>>> False * 85
ot
0
>>> True * 85
85 sp
>>>True+True
2
>>>False+False
og
0
3 VARIABLES
bl
● This means that when you create a variable you reserve some space in memory.
● Based on the data type of a variable, the interpreter allocates memory and decides
ic
Assignment Statements
● An assignment statement creates a new variable and gives it a value:
>>>message = 'Introducing Python Variable'
th
>>>num = 15
>>>radius = 5.4
ru
Variable Names
● Programmers generally choose names for their variables that are meaningful
● The Rules
❖ Variables names must start with a letter or an underscore,such as:
_mark
mark_
❖ The remainder of your variable name may consist of letters, numbers and
underscores.
subject1
my2ndsubject
un_der_scores
❖ Names are case sensitive.
case_sensitive, CASE_SENSITIVE, and Case_Sensitive are each a different
variable.
❖ Can be any (reasonable) length
❖ There are some reserved (KeyWords)words which you cannot use as a
variable name
● If you give a variable an illegal name, you get a syntax error:
om
>>>1book = 'python'
SyntaxError: invalid syntax
>>>more@ = 1000000
.c
SyntaxError: invalid syntax
>>>class = 'Fundamentals of programming'
ot
SyntaxError: invalid syntax
● 1book is illegal because it begins with a number.
● more@ is illegal because it contains an illegal character,
sp
● class is illegal because it is a keyword.
>>> 10<5
False
ru
>>> 50+20
70
● When you type an expression at the prompt, the interpreter evaluates it, which
means that it finds the value of the expression.
3.2 STATEMENT
● A statement is a unit of code that has an effect, like creating a variable or displaying
a value.
>>> n = 25
>>>print(n)
● The first line is an assignment statement that gives a value to n.
● The second line is a print statement that displays the value of n.
● When you type a statement, the interpreter executes it, which means that it does
whatever the statement says.
● In general, statements don’t have values.
om
as expressions.
.c
3.3 TUPLE ASSIGNMENT
● It is often useful to swap the values of two variables.
ot
● With conventional assignments, you have to use a temporary variable.
● For example, to swap a and b:
>>>temp = a
sp
>>> a = b
>>> b = temp
>>>a, b = b, a
og
● This is called tuple assignment
● The left side is a tuple of variables; the right side is a tuple of expressions.
● Each value is assigned to its respective variable.
bl
● All the expressions on the right side are evaluated before any of the assignments.
● The number of variables on the left and the number of values on the right have to be
e.
the same.
>>>a, b = 1, 2, 3
ic
● For example, to split an email address into a user name and a domain, you could
write:
>>>addr = '[email protected]'
th
3.4 OPERATORS
● Operators are special symbols in Python that carry out computation.
● The value that the operator operates on is called the operand.
For example:
>>>10+5
15
● Here, + is the operator that performs addition.
● 10 and 5 are the operands and 15 is the output of the operation.
● Python has a number of operators which are classified below.
1) Arithmetic operators
2) Comparison (Relational) operators
3) Logical (Boolean) operators
4) Bitwise operators
5) Assignment operators
6) Special operators
i) Arithmetic Operators
● Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
om
Example
x=7
y=3
.c
print('x + y =',x+y)
print('x - y =',x-y)
ot
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
sp
print('x % y =',x%y)
print('x ** y =',x**y)
og
When you run the program, the output will be:
x + y = 10
x-y=4
bl
x * y = 21
x / y = 2.3333333333333335
e.
x // y = 2
x%y=1
ic
x ** y = 343
cs
th
ru
om
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
.c
print('x <= y is',x<=y)
ot
When you run the program, the output will be:
x >y is False
sp
x <y is True
x == y is False
og
x != y is True
x >= y is False
x <= y is True
bl
iii)Logical Operators
e.
Example
x = True
y = False
ru
x and y is False
x or y is True
not x is False
iv) Bitwise Operators
● Bitwise operators act on operands as if they were string of binary digits. It operates
bit by bit, hence the name.
om
Example
.c
x=10
y=4
ot
print('x& y=',x& y)
print('x | y=',x | y)
sp
print('~x=',~x)
print('x ^ y=',x ^ y)
print('x>> 2=',x>> 2)
og
print('x<< 2=',x<< 2)
x& y= 0
x | y= 14
e.
~x= -11
x ^ y= 14
ic
x>> 2= 2
x<< 2= 40
cs
v) Assignment Operators
● Assignment operators are used in Python to assign values to variables.
th
● a=10 assigns the value 10 on the right side to the variable a on the left.
● There are various compound operators in Python like a += 10 that adds to the
ru
a) Identity Operators
● is and is not are the identity operators in Python. They are used to
check if two values (or variables) are located on the same part of the
memory.
● Two variables that are equal does not imply that they are identical.
om
Example
.c
x1 = 7
y1 = 7
ot
x2 = 'Welcome'
sp y2 = 'Welcome'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
og
print(x2 is y2)
print(x3 is y3)
When you run the program, the output will be:
bl
False
True
e.
False
ic
b) Membership Operators
● in and in not are the membership operator.
cs
Example
x = 'Python Programming'
print('Program' not in x)
print('Program' in x)
print('program' in x)
When you run the program, the output will be:
False
True
False
● Here, ' Program ' is in x but ' program' is not present in x, since Python
is case sensitive
om
For example, multiplication has higher precedence than subtraction.
>>> 20 – 5*3
5
.c
But we can change this order using parentheses () as it has higher precedence.
ot
>>> (20 - 5) *3
45
sp
● The operator precedence in Python are listed in the following table. It is in
descending order, upper group has higher
og
bl
e.
ic
cs
th
● We can see in the above table that more than one operator exists in the same group.
● These operators have the same precedence.
● When two operators have the same precedence, associativity helps to determine
which the order of operations.
● Associativity is the order in which an expression is evaluated that has multiple
operator of the same precedence.
● Almost all the operators have left-to-right associativity.
For example, multiplication and floor division have the same precedence.
Hence, if both of them are present in an expression, left one is evaluates first.
>>> 10 * 7 // 3
23
>>> 10 * (7//3)
20
>>> (10 * 7)//3
23
om
15625
>>> 5 **(2 **3)
390625
.c
We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).
ot
3.5 COMMENTS
● As programs get bigger and more complicated, they get more difficult to read.
● Formal languages are dense, and it is often difficult to look at a piece of code and
sp
figure out what it is doing, or why.
● For this reason, it is a good idea to add notes to your programs to explain in natural
language what the program is doing.
og
● These notes are called comments, and they start with the # symbol:
area= (base*height)/2
● In this case, the comment appears on a line by itself. You can also put comments at
e.
● Another way of doing this is to use triple quotes, either ''' or """.
"""This is also a
perfect example of
multi-line comments"""
4. ILLUSTRATIVE PROBLEMS
4.1 EXCHANGE THE VALUES OF TWO VARIABLES
● In python exchanging the values can be done in three ways
i) Using third variable
ii) Using tuple assignment method
iii) Using arithmetic operator
iv) Using bitwise operator
om
4 var1 = var2
5 var2 = temp
6 print("After swapping:")
.c
7 print("First Variable =",var1,)
8 print("Second Variable=",var2,)
ot
When you run the program, the output will be:
sp
Enter value of variable1: 5
Enter value of variable2: 10
After swapping:
og
First Variable = 10
Second Variable= 5
bl
var1,var2=var2,var1
ic
x=x+y
y=x-y
ru
x=x-y
x=x^y
y=x^y
x=x^y
om
can be easily performed by List slicing operator.
.c
● Consider the above list Figure 2.4.a; circulation of the above list by n position can be
easily achieved by slicing the array into two and concatenating them.
ot
● Slicing is done as nth element to end element + beginning element to n-1th element.
Suppose n=2 means, given list is rotated 2 positions towards left side
sp
● Suppose n= - 2 means, given list is rotated 2 position towards right side
og
bl
>>> circulate([1,2,3,4,5,6,7], 2)
[3, 4, 5, 6, 7, 1, 2]
cs
Import math
p1=[4,0]
p2=[6,6]
distance=math.sqrt((p1[0]-p2[0]**2)+p1[1]-p2[1]**2))
print(distance)
Output
Distance between two points
6.3245532