2 Cse Python
2 Cse Python
Python Numbers
Number data types store numeric values. Number objects are created when
you assign a value to them. For example −
var1 =1
var2 =10
long (long integers, they can also be represented in octal and hexadecimal)
STRING OPERATION:
The+ operator works with strings, but it is not addition in the mathematical
[Link] it performs concatenation , which means joining the strings by
linking
them end-to-end. For example:
>>>first = 10
>>>second = 15
>>>printfirst+second
25
>>>first ='100'
>>>second ='150'
>>>print first + second
100150
BOOLEAN EXPRESSIONS:
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as Y.
OPERATORS
Operators are the constructs which can manipulate the value of operands.
TYPES OF OPERATORS
Python language supports the following types of operators.
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
- Subtraction Subtracts right hand operand from left hand operand. a–b=-
10
% Modulus Divides left hand operand by right hand operand and b%a=
returns remainder 0
> If the value of left operand is greater than the value of (a > b)
right operand, then condition becomes true. is not
true.
< If the value of left operand is less than the value of right (a < b)
operand, then condition becomes true. is true.
>= If the value of left operand is greater than or equal to the (a >= b)
value of right operand, then condition becomes true. is not
true.
<= If the value of left operand is less than or equal to the (a <= b)
value of right operand, then condition becomes true. is true.
+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent
to c = c +
a
/= Divide AND It divides left operand with the right operand and c /= a is
assign the result to left operand equivalent
to c = c /
ac /= a is
equivalent
to c = c /
a
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
& Binary AND Operator copies a bit to the result if it exists in (a & b)
both operands (means
0000 1100)
~ Binary Ones It is unary and has the effect of 'flipping' bits. (~a ) = -61
Complement (means
1100 0011
in 2's
complement
form due to
a signed
binary
number.
<< Binary Left The left operands value is moved left by the a << = 240
Shift number of bits specified by the right operand. (means
1111 0000)
>> Binary Right The left operands value is moved right by the a >> = 15
Shift number of bits specified by the right operand. (means
0000 1111)
17
x + 17
>>> 1 + 1
Exercise 2 Type the following statements in the Python interpreter to see what
they do:
x=5
x+1
Now put the same statements into a script and run it. What is the output? Modify
the script by transforming each expression into a print statement and then run it
again.
Order of operations:
When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence. For mathematical operators, Python follows
mathematical convention. The acronym PEMDAS is a useful way to remember the
rules:
Parentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are evaluated
first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an
expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the
result.
Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5,
not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right (except
exponentiation). So in the expression degrees / 2 * pi, the division happens first
and the result is multiplied by pi. To divide by 2 π, you can use parentheses or
write degrees / 2 / pi.
SYNTAX:
The syntax of if statement
If test_expression:
Statement1
………………
Statement n
Statement x
FLOW CHART:
Python programming language assumes any non-zero and non-
null values as TRUE, and if it is either zero or null, then it is assumed as
FALSE value.
Example:
if x > 0 :
IF-ELSE:
An else statement can be combined with an if statement.
An else statement contains the block of code that executes if the
conditional expression in the if statement resolves to 0 or a FALSE value.
Syntax:
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
Flow Diagram
Example:
if x%2 == 0 :
else :
print'x is odd'
Similar to the else, the elif statement is optional. However, unlike else, for
which there can be at most one statement, there can be an arbitrary
number of elif statements following an if.
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example:
if x < y:
elif x > y:
else:
Nested conditionals:
One conditional can also be nested within another. We could have written the trichotomy
example like this:
if x == y:
else:
if x < y:
LOOPS IN PYTHON:
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:
whiletest_expression:
Body of while
Flow chart:
Example:
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
Body of for
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.
Flow chart:
Example:
forval in numbers:
sum = sum+val
If break statement is inside a nested loop (loop inside another loop), break will terminate
the innermost loop.
Syntax of break
Break
Example:
forval in "string":
ifval == "i":
break
print(val)
print("The end")
Syntax of Continue
Continue
Example:
forval in "string":
ifval == "i":
continue
print(val)
print("The end")
Pass statement:
Occasionally, it is useful to have a body with no statements (usually as a
place keeper for code you haven’t written yet). In that case, you can use
the pass
statement, which does nothing.
if x < 0 :
pass
If you enter an if statement in the Python interpreter, the prompt will change
from three chevrons to three dots to indicate you are in the middle of a
block of statements as shown below:
>>> x = 3
>>>if x < 10:
... print'Small'
...
Small
>>>
Lists
A list is a sequence
Like a string, a list is a sequence of values. In a string, the values are characters;
in a list, they can be any type. The values in list are called elements or sometimes
items.
There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):
Traversing a list
The most common way to traverse the elements of a list is with a forloop. The
syntax is the same as for strings:
for cheese in cheeses:
print cheese
This works well if you only need to read the elements of the list. But if you want
to write or update the elements, you need the indices. A common way to do that
is to combine the functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
Although a list can contain another list, the nested list still counts as a single
element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3]
['b', 'c']
>>>t[:4]
['a', 'b', 'c', 'd']
>>>t[3:]
['d', 'e', 'f']
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']
List methods
Python provides methods that operate on lists. For example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>>[Link]('d')
>>> print t
['a', 'b', 'c', 'd']
extendtakes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>>[Link](t2)
Deleting elements
There are several ways to delete elements from a list. If you know the index of the
element you want, you can use pop:
8.8. Lists and functions 95
>>> t = ['a', 'b', 'c']
>>> x = [Link](1)
>>> print t
['a', 'c']
>>>print x
b
popmodifies the list and returns the element that was removed. If you don’t
provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the deloperator:
>>> t = ['a', 'b', 'c']
>>>del t[1]
>>> print t
['a', 'c']
If you know the element you want to remove (but not the index), you can use
remove:
>>> t = ['a', 'b', 'c']
>>>[Link]('b')
>>> print t
['a', 'c']
To remove more than one element, you can use delwith a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>del t[1:5]
>>> print t
['a', 'f']
numlist = list()
while ( True ) :
inp = raw_input('Enter a number: ')
ifinp == 'done' : break
value = float(inp)
[Link](value)
average = sum(numlist) / len(numlist)
print 'Average:', average
The list function breaks a string into individual letters. If you want to break a
string into words, you can use the split method:
>>> s = 'pining for the fjords'
>>> t = [Link]()
>>> print t
['pining', 'for', 'the', 'fjords']
>>> print t[2]
the
You can call split with an optional argument called a delimiter specifies which
characters to use as word boundaries.
>>> s = 'spam-spam-spam'
>>>delimiter = '-'
>>>[Link](delimiter)
['spam', 'spam', 'spam']
joinis the inverse of split. It takes a list of strings and concatenates the elements.
joinis a string method, so you have to invoke it on the delimiter and pass
the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>>delimiter = ' '
>>>[Link](t)
'pining for the fjords'
To concatenate strings without spaces, you can use the empty string, '', as a
delimiter.
a='banana'
b='banana'
In one case, a andb refer to two different objects that have the same value. In the
second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the isoperator.
>>> a = 'banana'
>>> b = 'banana'
>>>a is b
True
In this example, Python only created one string object, and both a andb refer to it.
But when you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>>a is b
False
In this case we would say that the two lists are equivalent, because they have the
same elements, but not identical, because they are not the same object. If two
objects are identical, they are also equivalent, but if they are equivalent, they are
not necessarily identical.
Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
>>> b = a
>>>b is a
True
>>>b[0] = 17
>>> print a
[17, 2, 3]
Tuples
A tupleis a sequence of values much like a list. The values stored in a tuple can
be any type, and they are indexed by integers. The important difference is that
tuples are immutable.
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
Without the comma Python treats ('a') as an expression with a string in parentheses
that evaluates to a string:
>>> t2 = ('a')
>>>type(t2)
<type 'str'>
Another way to construct a tuple is the built-in function tuple. With no argument,
it creates an empty tuple:
>>> t = tuple()
>>> print t
()
If the argument is a sequence (string, list or tuple), the result of the call to tuple
is a tuple with the elements of the sequence:
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')
Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
And the slice operator selects a range of elements.
>>> print t[1:3]
('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>>t[0] = 'A'
Comparing tuples
The comparison operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the
next element, and so on, until it finds elements that differ
Tuple assignment
>>> m = [ 'have', 'fun' ]
>>>x, y = m
>>>x
'have'
>>>y
'fun'
For example, to split an email address into a user name and a domain, you could
write:
>>>addr = 'monty@[Link]'
>>>uname, domain = [Link]('@')
fork,v in [Link]()
printk,v
+ and * on tuples
We can use sum(), max(), min(), len(),sorted() functions with tuple. Run the following and understand
how these functions works with tuple.
X=(12,22,33,2)
print (sum(X))
print (max(X))
print (min(X))
print (max(X))
print (min(X))
print (sorted(X))
print (sorted(X, reverse=True))
Comparing tuples
Usually, The function cmp() compares the values of two arguments x and y:
cmp(x,y)
Zero if x is equal to y.
The built-in cmp() function will typically return only the values -1, 0, or 1.
X,Y=(12,33),(22,44)
print(cmp(x,y))
print (cmp(y,x))
X,Y=(12,33,5),(22,44,2)
print(cmp(x,y))
print (cmp(y,x))
X,Y=(12,33),(12,33)
print(cmp(x,y))
print (cmp(y,x))
We can use all(), any(), enumerate functions with tuples. For example, all() function returns true if all
the elements are true (or tuple is empty); otherwise returns False(if the the tuple is emply also it returns
False). Similarly, any() method returns True if atleast one of its elements is True; otherwise falls.
enumerate prints all elements of the tuple along with their index.
x=(992,33,33,None)
print (any(x))
print (all(x))
for y in enumerate(x):
print (y)
x=(992,33,33,45,55,66)
for y in enumerate(x):
print (y)
for y in enumerate(x,3):
print (y)
print (type(X))
print (X)
print (type(X))
print (X)
print (type(X))
print (X)
print (type(X))
print (X)
print (type(X))
print (X)
The following program illustrates the use of sorted(), reversed(), zip() methods with tuples.
print (album)
print (album)
s=()
ss={}
sss={1}
ssss={'a':12}
sssss=set()
print type(s)
print type(ss)
print type(sss)
print type(ssss)
print type(sssss)
Set operations
1. len(): We can compute the length of a set (number of values at the top-level). For
example, the with the sets defined above,
for i in b:
print(i)
alist=[1, 2, 3, 5,2,9,3]
aset = set(alist)
printlen(aset), len(alist)
printalist
printaset
# Asaset has no duplicated values, its length will be smaller than or equal to alist
blist = list(aset)
printlen(blist),len(aset)
printaset
printblist
Set Objects
s.symmetric_difference(t) s^t new set with elements in either s or t but not both
Frozen Sets Frozen sets are immutable objects that only support methods and operators that
produce a result without a?ecting the frozen set or sets to which they are applied.
# A frozen set
frozen_set =frozenset(["e", "f", "g"])
print("Frozen Set")
print(frozen_set)
1. add(x) Method: Adds the item x to set if it is not already present in the set.
union(s) Method: Returns a union of two [Link] the ‘|’ operator between 2 sets is the same as
writing [Link](set2)
OR
population = people|vampires
[Link](s) Method: Returns an intersection of two [Link] ‘&’ operator comes can also be
used in this case.
victims = [Link](vampires)
-> Set victims will contain the common element of people and vampire
4. difference(s) Method: Returns a set containing all the elements of invoking set but not of the
second set. We can use ‘-‘ operator here.
safe = [Link](vampires)
OR
-> Set safe will have all the elements that are in people but not vampire
5. clear() Method: Empties the whole set.
[Link]()
s1 == s2 # s1 is equivalent to s2
s1 != s2 # s1 is not equivalent to s2
Dictionaries
A dictionary is like a list, but more general. In a list, the positions (a.k.a. indices)
have to be integers; in a dictionary the indices can be (almost) any type
a dictionary as a mapping between a set of indices (which are called keys) and a set of values.
Each key maps to a value.
The association of a key and a value is called a key-value pair or sometimes an item.
The function dictcreates a new dictionary with no items. Because dictis the
name of a built-in function, you should avoid using it as a variable name.
>>> eng2sp = dict()
>>> print eng2sp
The squiggly-brackets, {}, represent an empty dictionary. To add items to the
dictionary, you can use square brackets:
>>>eng2sp['one'] = 'uno'
If we
print the dictionary again, we see a key-value pair with a colon between the key
and value:
>>> print eng2sp
create a new dictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
To see whether something appears as a value in a dictionary, you can use the
methodvalues, which returns the values as a list, and then use the in operator:
>>>vals = [Link]()
>>> 'uno' in vals
True
The in operator uses different algorithms for lists and dictionaries. For lists, it
uses a linear search algorithm. As the list gets longer, the search time gets longer
in direct proportion to the length of the list. For dictionaries, Python uses an
algorithm called a hash table
>>>[Link]('a', 0)
1
>>>[Link]('b', 0)
0
Dictionary Methods
Dictionaries have a number of useful built-in methods. The following table provides a summary
and more details can be found in the Python Documentation.
terse={}
terse['abscond']='Dis-appear without knowledge'
terse['mutable']='able to change'
terse['abstain']='stop from voting'
terse['abbey']='A place where people will pray for god'
terse['awkward']='Not in proper order'
for k in terse:
print ("Key",k)
kys=list([Link]())
print(kys)
for k in [Link]():
print("Key",k)
Aliasing in Dictionaries
Whenever two variables refer to the same dictionary object, changes to one affect the other. This
problem is known as aliasing problem which we did encounter in lists also. In order to avoid this, we can
use copy() method of dictionary class to create a copy of it.
concise=[Link]()
print(concise is terse)
concise['abstain']='stop from voting'
print(terse)
print(concise)terse={'abscond':'Dis-appear without knowledge', 'mutable':'able to change','abstain':'stop
from voting'}
compact=terse
print(compact is terse)
print(terse)
print(compact)
compact['abstain']='xxxxx'
print(terse)
print(compact)
concise=[Link]()
print(concise is terse)
concise['abstain']='stop from voting'
print(terse)
print(concise)
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value
expressions:
>>>
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
When the keys are simple strings, it is sometimes easier to specify pairs using keyword
arguments:
>>>
>>>dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
When looping through dictionaries, the key and corresponding value can be retrieved at the same
time using the items() method.
>>>
>>>knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>>for k, v in [Link]():
... print(k, v)
...
gallahad the pure
robin the brave
When looping through a sequence, the position index and corresponding value can be retrieved
at the same time using the enumerate() function.
>>>
>>>for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
questions=['name','quest','favoritecolor']
>>>answers=['lancelot','the holy grail','blue']
>>>forq,ainzip(questions,answers):
... print('What is your {0}? It is {1}.'.format(q,a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favoritecolor? It is blue.
To loop over a sequence in reverse, first specify the sequence in a forward direction and then call
the reversed() function.
>>>
>>>for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
chr(i)
Return a string of one character whose ASCII code is the integer i. For example, chr(97)
returns the string 'a'. This is the inverse of ord()
Dictionary Comprehensions
unique_numbers = []
for n in numbers:
if n not in unique_numbers:
unique_numbers.append(n)
print(unique_numbers)
Some times, we want to initialize all values of a dictionary with 0 or none. For this, we can use list
comprehension or [Link]() method as shown below.
fromkeys() is a class method that returns a new dictionary. value defaults to None.
z=[Link](range(10))
o/p
{(0, 0): 0, (0, 1): 1, (0, 2): 2, (0, 3): 3, (1, 0): 1, (1, 1): 2, (1, 2): 3,
(1, 3): 4, (2, 0): 2, (2, 1): 3, (2, 2): 4, (2, 3): 5, (3, 0): 3, (3, 1): 4,
(3, 2): 5, (3, 3): 6}
writedict for it
uses nested dictionary comprehension generates a dictionary of an identity matrix of size 4x4.
o/p {(0, 0): 1, (0, 1): 0, (0, 2): 0, (0, 3): 0, (1, 0): 0, (1, 1): 1, (1,
2): 0, (1, 3): 0, (2, 0): 0, (2, 1): 0, (2, 2): 1, (2, 3): 0, (3, 0): 0, (3,
1): 0, (3, 2): 0, (3, 3): 1}
Assume that you have a list a set of words and you want to display how many times each word has
appeared. We use dictionary comprehension to achieve this