Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Python Training session 2

Students copy

Strings are immutable

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.

>>> squares = [1, 4, 9, 16, 25]


>>> squares
[1, 4, 9, 16, 25]
Like strings (and all other built-in sequence type), lists can be indexed and sliced:
>>>
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
All slice operations return a new list containing the requested elements. This means that the following
slice returns a new (shallow) copy of the list:
>>>
>>> squares[:]
[1, 4, 9, 16, 25]
Lists also support operations like concatenation:
>>>
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:
>>>
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
You can also add new items at the end of the list, by using the append() method (we will see more about
methods later):
>>>
>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

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'

Data Type Conversion

There are several in build function in python to perform conversion from one Data type variable to
another.

Function Description

int(x [,base]) Converts x to an integer. base specifies the base if x is a string.

long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.

float(x) Converts x to a floating-point number.

complex(real [,imag]) Creates a complex number.

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

Akhil
Python Training session 2
Students copy

tuple(s) Converts s to a tuple.

list(s) Converts s to a list.

set(s) Converts s to a set.

dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.

frozenset(s) Converts s to a frozen set.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.

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.

Python supports following types of operators:

 Arithmetic
 Comparison
 Assignment
 Bitwise
 Logical (or Relational)
 Membership
 Identity

Arithmetic Operator: -

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example

+ Addition - Adds values on either side of the operator a + b will give 30

- Subtraction - Subtracts right hand operand from left a - b will give -10
hand operand

* Multiplication - Multiplies values on either side of the a * b will give 200


operator

/ Division - Divides left hand operand by right hand b / a will give 2


operand

% Modulus - Divides left hand operand by right hand b % a will give 0


operand and returns remainder

** 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

result is the quotient in which the digits after the


decimal point are removed.

Comparison

Operator Description Example

== 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.

What is the difference between = (single- equal) and == (double- equal)?


The = (single- equal) assigns the value on the right to a variable on the left. The == (double- equal) used
for comparison.

Assignment

Operator Description Example

= 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

-= Subtract AND assignment operator, It subtracts right operand c -= a is equivalent to c = c – a


from the left operand and assign the result to left operand

*= Multiply AND assignment operator, It multiplies right operand c *= a is equivalent to c = c * a


with the left operand and assign the result to left operand

/= Divide AND assignment operator, It divides left operand with c /= a is equivalent to c = c / a


the right operand and assign the result to left operand

%= Modulus AND assignment operator, It takes modulus using two c %= a is equivalent to c = c % a


operands and assign the result to left operand

**= Exponent AND assignment operator, Performs exponential c **= a is equivalent to c = c ** a


(power) calculation on operators and assign value to the 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

Bitwise operator works on bits and perform bit by bit operation.


Assume if a = 60; and b = 13; Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
Operator Description Example

& 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.

Logical (or Relational)

Operator Description Example

and Called Logical AND operator. If both the operands are (a and b) is true.
true then condition becomes true.

or Called Logical OR Operator. If any of the two (a or b) is true.


operands are non zero 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.

Operator Description Example

in Evaluates to true if it finds a variable in the specified x in y, here in results in a 1 if x is a member of


sequence and false otherwise. sequence y.

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

Identity operators compare the memory locations of two objects.

Operator Description Example

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).

Python operator precedence

The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, 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'

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Python Decision making

 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!"

if people < dogs:


print "The world is drooled on!"
if people > dogs:
print "The world is dry!"

dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."

if people <= dogs:


print "People are less than or equal to dogs."

if people == dogs:
print "People are a social animal."

Results

Too many cats! The world is doomed!


The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

What does += mean?


The code x += 1 is the same as doing x = x + 1 but involves less typing. You can call this the “increment
by” operator. The same goes for - =

The elif statements


The elif statement allows you to check multiple expressions for truth value and execute a block of code
as soon as one of the conditions evaluates to true.

Akhil
Python Training session 2
Students copy

people = 30
cars = 40
buses = 15

if cars > people:


print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."

if buses > cars:


print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."

if people > buses:


print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
>>>More

The Nested if...elif...else Construct


There may be a situation when you want to check for another condition after a condition resolves to
true. In such a situation, you can use the nested ifconstruct.
In a nested if construct, you can have anif...elif...else construct inside another if...elif...else construct.

The syntax of the nested if...elif...else construct may be:


if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:

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"

print "Good Job!"


This will produce following result:
Expression value is less than 200
Which is 100
Good Job!

Single statement suites


If the suite of an if clause consists only of a single line, it may go on the same line as the header
statement:
Here is an example of a one-line if clause:
If (expressions == 1): print "Value of expression is 1"

Python loops [while, for, nested loops]

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

print "Good Job!"

This will produce following result:


The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good Job!

The Infinite Loops:


#!/usr/bin/python

var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num

print "Good Job!"

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]

>>> # Measure some strings:


... words = ['cat', 'window', 'defenestrate']

Akhil
Python Training session 2
Students copy

>>> for w in words:


... print w, len(w)
...
cat 3
window 6
defenestrate 12

>>> 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']

Python Range Function

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

Break and continue statements


The break statement in Python terminates the current loop and resumes execution at the next
statement
#!/usr/bin/python

Akhil
Python Training session 2
Students copy

for letter in 'Python': # First Example


if letter == 'h':
break
print 'Current Letter :', letter

print "Good Job!"

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

for letter in 'Python': # First Example


if letter == 'h':
continue
print 'Current Letter :', letter

print "Good Job!"

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

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

Akhil
Python Training session 2
Students copy

print "Good Job!"


Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good Job!

Akhil

You might also like