Unit 2 N
Unit 2 N
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter:
If you are running new version of Python, then you would need to use print
statement with parenthesis as in print ("Hello, Python!") However in Python
version 2.4.3, this produces the following result:
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script
and continues until the script is finished. When the script is finished, the
interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension
.py. Type the following source code in a test.py file:
We assume that you have Python interpreter set in PATH variable. Now, try to
run this program as follows −
$ python test.py
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py
file −
#!/usr/bin/python
Hello, Python!
22
We don't need to declare a variable before using it. In Python, we simply assign
a value to a variable and it will exist. We don't even have to declare the type of
the variable. This is handled internally according to the type of value we assign
to the variable.
We use the assignment operator (=) to assign values to a variable. Any type of
value can be assigned to any valid variable.
a=5
b = 3.2
c = "Hello"
a, b, c = 5, 3.2, "Hello"
If we want to assign the same value to multiple variables at once, we can do this
as
x = y = z = "same"
A value is one of the basic things a program works with, like a letter or a
number. The values we have seen so far are 1, 2, and 'Hello, World!'.
There are various data types in Python. Some of the important types are listed
below.
Integers, floating point numbers and complex numbers falls under Python
numbers category. They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value
belongs to and the isinstance() function to check if an object belongs to a
particular class.
Program:
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Complex numbers are written in the form, x + yj, where x is the real part and y
is the imaginary part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
24
>>> c = 1+2j
>>> c
(1+2j)
2.2.2.2 Python List
We can use the slicing operator [ ] to extract an item or a range of items from a
list. Index starts form 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]
2.2.2.3 Python Tuple
Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically.
We can use the slicing operator [] to extract items but we cannot change its
value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# Generates error
# Tuples are immutable
t[0] = 10
Like list and tuple, slicing operator [ ] can be used with string. Strings are
immutable.
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
We can perform set operations like union, intersection on two sets. Set have
unique values. They eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence the slicing
operator [] does not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
In Python, dictionaries are defined within braces {} with each item being a pair
in the form key:value. Key and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))
# Generates error
print("d[2] = ", d[2]);
27
We can convert between different data types by using different type conversion
functions like int(), float(), str() etc.
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
28
Instructions that a Python interpreter can execute are called statements. For
example, a = 1 is an assignment statement. if statement, for statement, while
statement etc. are other kinds of statements which will be discussed later.
a=1+2+3+\
4+5+6+\
7+8+9
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
colors = ['red',
'blue',
'green']
a = 1; b = 2; c = 3
Most of the programming languages like C, C++, Java use braces { } to define a
block of code. Python uses indentation.
29
A code block (body of a function, loop etc.) starts with indentation and ends
with the first unindented line. The amount of indentation is up to you, but it
must be consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs.
The enforcement of indentation in Python makes the code look neat and clean.
This results into Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always
indent. It makes the code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer.
#This is a comment
#print out Hello
print('Hello')
2.3.3.1 Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line. For example:
30
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be
used as multi-line comment as well. Unless they are not docstrings, they do not
generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
2.3.4 Docstring in Python
def double(num):
return 2*num
>>> print(double.__doc__)
Function to double the value
There are 33 keywords in Python 3.3. This number can vary slightly in course
of time.
All the keywords except True, False and None are in lowercase and they must
be written as it is. The list of all the keywords are given below.
Identifier is the name given to entities like class, functions, variables etc. in
Python. It helps differentiating one entity from another.
>>> global = 1
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
>>> a@ = 0
File "<interactive input>", line 1
a@ = 0
32
^
SyntaxError: invalid syntax
Some of the functions like input() and print() are widely used for standard input
and output operations respectively. Let us see the output section first.
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example
use is given below.
print('This sentence is output to the screen')
# Output: This sentence is output to the screen
a=5
print('The value of a is', a)
# Output: The value of a is 5
In the second print() statement, we can notice that a space was added between
the string and the value of variable a.This is by default, but we can change it.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is
sys.stdout (screen). Here are an example to illustrate this.
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
33
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
Sometimes we would like to format our output to make it look attractive. This
can be done by using the str.format() method. This method is visible to any
string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in
which it is printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter
We can even format strings like the old sprintf() style used in C programming
language. We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Up till now, our programs were static. The value of variables were defined or
hard coded into the source code.
To allow flexibility we might want to take the input from the user. In Python,
we have the input() function to allow this. The syntax for input() is
Enter a number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number. To convert
this into a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
This same operation can be performed using the eval() function. But it takes it
further. It can evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5
When our program grows bigger, it is a good idea to break it into different
modules.
For example, we can import the math module by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can
also import some specific attributes and functions only, using the from
keyword. For example:
>>> pi
3.141592653589793
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is
the output of the operation.
Arithmetic operators
Bitwise operators
Assignment operators
36
Special operators
x**y (x to the
** Exponent - left operand raised to the power of right
power y)
Example:
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
37
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
When you run the program, the output will be:
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators are used to compare values. It either returns True or False
according to the condition.
Example:
x = 10
y = 12
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
Example:
x = True
y = False
# Output: x or y is True
print('x or y is',x or y)
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
39
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the
variable and later assigns the same. It is equivalent to a = a + 5.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
40
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Python language offers some special type of operators like the identity operator
or the membership operator. They are described below with examples.
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.
True if the operands are not identical (do not refer to the x is not
is not
same object) True
Example:
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
41
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Here, we see that x1 and y1 are integers of same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. Since list are mutable
(can be changed), interpreter locates them separately in memory although they
are equal.
in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).
In a dictionary we can only test for presence of key, not the value.
Example:
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
42
2.7 PRECEDENCE OF OPERATORS
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:
2.8 EXPRESSIONS
An expression is a combination of values, variables, and operators. A
value all by itself is considered an expression, and so is a variable, so the
following are all legal expressions (assuming that the variable x has been
assigned a value):
17
x
x + 17
If you type an expression in interactive mode, the interpreter evaluates it
and displays the result:
>>> 1 + 1
2
But in a script, an expression all by itself doesn’t do anything! This is a
common source of confusion for beginners.
Exercise Type the following statements in the Python interpreter to see
what they do:
5
43
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.
>>>temp=a
>>>a=b
>>> b = temp
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of values. Each value
is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments. This feature makes tuple assignment
quite versatile.
Naturally, the number of variables on the left and the number of values on the
right have to be the same:
>>>a,b,c,d=1,2,3
ValueError: unpack tuple of wrong size
As you already know, Python gives you many built-in functions like print(), etc.
but you can also create your own functions. These functions are called user-
defined functions.
You can define functions to provide the required functionality. Here are simple
rules to define a function in Python.
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is
indented.
The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments is
the same as return None.
Syntax
By default, parameters have a positional behavior and you need to inform them
in the same order that they were defined.
Example
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
45
Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt. Following is the
example to call printme() function −
#!/usr/bin/python
#!/usr/bin/python
Here, we are maintaining reference of the passed object and appending values in
the same object. So, this would produce the following result −
46
There is one more example where argument is being passed by reference and
the reference is being overwritten inside the called function.
#!/usr/bin/python
The parameter mylist is local to the function changeme. Changing mylist within
the function does not affect mylist. The function accomplishes nothing and
finally this would produce the following result:
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −
47
#!/usr/bin/python
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.
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. You can also make keyword calls to the printme() function in the
following ways −
#!/usr/bin/python
My string
48
The following example gives more clear picture. Note that the order of
parameters does not matter.
#!/usr/bin/python
Name: miki
Age 50
2.10.4.3Default arguments
#!/usr/bin/python
Name: miki
Age 50
Name: miki
49
Age 35
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.
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. Following is a simple example
−
#!/usr/bin/python
Output is:
10
Output is:
70
60
50
50
ILLUSTRATIVE PROGRAMS
1. Exchange The Values Of Two Variables
Swapping two variables refers to mutually exchanging the values of the variables. Generally,
this is done with the data in memory.
The simplest method to swap two variables is to use a third temporary variable :
define swap(a, b)
temp := a
a := b
b := temp
Sample Solution:-
Python Code:
a = 30
b = 20
print("\nBefore swap a = %d and b = %d" %(a, b))
a, b = b, a
print("\nAfter swaping a = %d and b = %d" %(a, b))
print()
Sample Output:
Distance Between Two Points Can Be Calculated Using The Below Formula.
d= √(x 1− y 1) −( x 2− y 2)
2 2
Program:
import math
p1=[4,0]
p2=[6,6]
distance=math.sqrt(((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2))
print("distance between 2 points:",distance)
output:
distance between 2 points:6.324555320336759