Python Session 3
Python Session 3
Students copy
List []
Tuple ()
Dictionary {}
Python knows a number of compound data types, used to group together other values. The most
versatile is the list, which can be written as a list of comma-separated values (items) between square
brackets. Lists might contain items of different types, but usually the items all have the same type.
Akhil
Python Training session 2
Students copy
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
The built-in function len() also applies to lists:
>>>
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
It is possible to nest lists (create lists containing other lists), for example:
>>>
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
There are several in build function in python to perform conversion from one Data type variable to
another.
Function Description
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
Akhil
Python Training session 2
Students copy
Operators
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and +
is called as operator.
Arithmetic
Comparison
Assignment
Bitwise
Logical (or Relational)
Membership
Identity
Arithmetic Operator: -
- Subtraction - Subtracts right hand operand from left a - b will give -10
hand operand
** Exponent - Performs exponential (power) calculation a**b will give 10 to the power 20
on operators
// Floor Division - The division of operands where the 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
Akhil
Python Training session 2
Students copy
Comparison
== Checks if the value of two operands are equal or not, if yes then condition (a == b) is not true.
becomes true.
!= Checks if the value of two operands are equal or not, if values are not equal (a != b) is true.
then condition becomes true.
<> Checks if the value of two operands are equal or not, if values are not equal (a <> b) is true. This is similar
then condition becomes true. to != operator.
> Checks if the value of left operand is greater than the value of right (a > b) is not true.
operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right operand, if (a < b) is true.
yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of (a >= b) is not true.
right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right (a <= b) is true.
operand, if yes then condition becomes true.
The comparison operators <> and != are alternate spellings of the same operator. != is the preferred
spelling; <> is obsolescent.
Assignment
= Simple assignment operator, Assigns values from right side c = a + b will assign value of a + b into c
operands to left side operand
+= Add AND assignment operator, It adds right operand to the left c += a is equivalent to c = c + a
operand and assign the result to left operand
//= Floor Dividion and assigns a value, Performs floor division on c //= a is equivalent to c = c // a
operators and assign value to the left operand
Akhil
Python Training session 2
Students copy
Bitwise
& Binary AND Operator copies a bit to the result if it (a & b) will give 12 which is 0000 1100
exists in both operands.
| Binary OR Operator copies a bit if it exists in eather (a | b) will give 61 which is 0011 1101
operand.
^ Binary XOR Operator copies the bit if it is set in one (a ^ b) will give 49 which is 0011 0001
operand but not both.
~ Binary Ones Complement Operator is unary and has (~a ) will give -60 which is 1100 0011
the effect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands value is a << 2 will give 240 which is 1111 0000
moved left by the number of bits specified by the
right operand.
>> Binary Right Shift Operator. The left operands value is a >> 2 will give 15 which is 0000 1111
moved right by the number of bits specified by the
right operand.
and Called Logical AND operator. If both the operands are (a and b) is true.
true then condition becomes true.
not Called Logical NOT Operator. Use to reverses the not(a and b) is false.
logical state of its operand. If a condition is true then
Logical NOT operator will make false.
Membership
In addition to the operators discussed previously, Python has membership operators, which test for
membership in a sequence, such as strings, lists, or tuples.
Akhil
Python Training session 2
Students copy
not in Evaluates to true if it does not finds a variable in the x not in y, here not in results in a 1 if x is a member
specified sequence and false otherwise. of sequence y.
Identity
is Evaluates to true if the variables on either side of the x is y, here is results in 1 if id(x) equals id(y).
operator point to the same object and false otherwise.
is not Evaluates to false if the variables on either side of the x is not y, here is not results in 1 if id(x) is not equal
operator point to the same object and true otherwise. to id(y).
The following table lists all operators from highest precedence to lowest.
Operator Description
~+- Complement, unary plus and minus (method names for the last two are +@ and -@)
If
Elif
Else
nested if
Akhil
Python Training session 2
Students copy
Control the execution of those statements in some way (or specific criteria). In general, compound
statements span multiple lines, although in simple incarnations a whole compound statement may be
contained in one line.
IF
The if statement is used for conditional execution:
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
Example:
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people == dogs:
print "People are a social animal."
Results
Akhil
Python Training session 2
Students copy
people = 30
cars = 40
buses = 15
Akhil
Python Training session 2
Students copy
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example:
#!/usr/bin/python
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
A loop is a construct that causes a section of a program to be repeated a certain number of times. The
repetition continues while the condition set for the loop remains true. When the condition becomes
false, the loop ends and the program control are passed to the statement following the loop.
While
For
Nested loops
Akhil
Python Training session 2
Students copy
The while loop continues until the expression becomes false. The expression has to be a logical
expression and must return either a true or a false value.
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" expression ":" suite
["else" ":" suite”]
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
For Loop
The for loop in Python has the ability to iterate over the items of any sequence, such as a list or a string.
The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or
other iterable object:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
Akhil
Python Training session 2
Students copy
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It
generates lists containing arithmetic progressions:
>>>
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given end point is never part of the generated list; range(10) generates a list of 10 values, the legal
indices for items of a sequence of length 10. It is possible to let the range start at another number, or to
specify a different increment (even negative; sometimes this is called the ‘step’):
>>>
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
To iterate over the indices of a sequence, you can combine range() and len() as follows:
>>>
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2a
3 little
4 lamb
Akhil
Python Training session 2
Students copy
Current Letter: P
Current Letter: y
Current Letter: t
Good Job!
Continue causes the loop to skip the reminder of its body immediately retest its condition prior to re
iterating.
The continue statement in Python returns the control to the beginning of the while loop.
The continue statement rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
#!/usr/bin/python
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n
Good Job!
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in
places where your code will eventually go, but has not been written yet (e.g., in stubs for example):
#!/usr/bin/python
Akhil
Python Training session 2
Students copy
Akhil