0% found this document useful (0 votes)
125 views33 pages

Unit 2 N

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views33 pages

Unit 2 N

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

19

UNIT II DATA, EXPRESSIONS, STATEMENTS


Python interpreter and interactive mode; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; modules and functions, function definition and use, flow of execution,
parameters and arguments; Illustrative programs: exchange the values of two
variables, circulate the values of n variables, distance between two point

2.1 About Python


Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language. It was created by Guido van Rossum during 1985-
1990. Like Perl, Python source code is also available under the GNU General
Public License (GPL). Python is a high-level, interpreted, interactive and
object-oriented scripting language. Python is designed to be highly readable. It
uses English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.

 Python is Interpreted: Python is processed at runtime by the interpreter.


You do not need to compile your program before executing it. This is
similar to PERL and PHP.
 Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.

2.1.1 History of Python


Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer
Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C+


+, Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).

Python is now maintained by a core development team at the institute, although


Guido van Rossum still holds a vital role in directing its progress.
20

2.1.2 Python Features


Python's features include:

 Easy-to-learn: Python has few keywords, simple structure, and a clearly


defined syntax. This allows the student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the
eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable
and cross-platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode:Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
 Extendable: You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries and windows systems,
such as Windows MFC, Macintosh, and the X Window system of Unix.
 Scalable: Python provides a better structure and support for large
programs than shell scripting.

2.1.3 Python Program Execution


Let us execute programs in different modes of programming.

Interactive Mode Programming

Invoking the interpreter without passing a script file as a parameter brings up


the following prompt −

$ 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:

>>> print "Hello, Python!"


21

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:

print "Hello, Python!"

We assume that you have Python interpreter set in PATH variable. Now, try to
run this program as follows −

$ python test.py

This produces the following result:

Hello, Python!

Let us try another way to execute a Python script. Here is the modified test.py
file −

#!/usr/bin/python

print "Hello, Python!"

We assume that you have Python interpreter available in /usr/bin directory.


Now, try to run this program as follows −

$ chmod +x test.py # This is to make file executable


$./test.py

This produces the following result −

Hello, Python!
22

2.2 PYTHON VARIABLES ,VALUES AND DATA TYPES

2.2.1 python Variables

A variable is a location in memory used to store some data (value).

They are given unique names to differentiate between different memory


locations. The rules for writing a variable name is same as the rules for writing
identifiers in Python.

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.

2.2.1.1 Variable assignment

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"

Here, we have three assignment statements. 5 is an integer assigned to the


variable a.

Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of


characters) assigned to the variables b and c respectively.

2.2.1.2 Multiple assignments

In Python, multiple assignments can be made in a single statement as follows:

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"

This assigns the "same" string to all the three variables.


23

2.2.2 Values and Data types in Python

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!'.

Every value in Python has a datatype. Since everything is an object in Python


programming, data types are actually classes and variables are instance (object)
of these classes.

There are various data types in Python. Some of the important types are listed
below.

2.2.2.1 Python Numbers

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

Integers can be of any length, it is only limited by the memory available.

A floating point number is accurate up to 15 decimal places. Integer and


floating points are separated by decimal points. 1 is integer, 1.0 is floating point
number.

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

List is an ordered sequence of items. It is one of the most used datatype in


Python and is very flexible. All the items in a list do not need to be of the same
type.

Declaring a list is pretty straight forward. Items separated by commas are


enclosed within brackets [ ].

>>> a = [1, 2.2, 'python']

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:])

Lists are mutable, meaning, value of elements of a list can be altered.

>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]
2.2.2.3 Python Tuple

Tuple is an ordered sequence of items same as list.The only difference is that


tuples are immutable. Tuples once created cannot be modified.

Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically.

It is defined within parentheses () where items are separated by commas.

>>> t = (5,'program', 1+3j)


25

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

2.2.2.4 Python Strings

String is sequence of Unicode characters. We can use single quotes or double


quotes to represent strings. Multi-line strings can be denoted using triple quotes,
''' or """.

>>> s = "This is a string"


>>> s = '''a multiline

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'

2.2.2.5 Python Set

Set is an unordered collection of unique items. Set is defined by values


separated by comma inside braces { }. Items in a set are not ordered.
a = {5,2,3,1,4}

# printing set variable


print("a = ", a)

# data type of variable a


print(type(a))
26

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

2.2.2.6 Python Dictionary

Dictionary is an unordered collection of key-value pairs.

It is generally used when we have a huge amount of data. Dictionaries are


optimized for retrieving data. We must know the key to retrieve the value.

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

print("d[1] = ", d[1]);

print("d['key'] = ", d['key']);

# Generates error
print("d[2] = ", d[2]);
27

2.2.3 Conversion between data types

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

Conversion to and from string must contain compatible values.

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

We can even convert one sequence to another.

>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair

>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
28

2.3 PYTHON STATEMENT, INDENTATION AND


COMMENTS
2.3.1 Python Statement

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.

2.3.1.1 Multi-line statement

In Python, end of a statement is marked by a newline character. But we can


make a statement extend over multiple lines with the line continuation character
(\). For example:

a=1+2+3+\
4+5+6+\
7+8+9

This is explicit line continuation. In Python, line continuation is implied inside


parentheses ( ), brackets [ ] and braces { }. For instance, we can implement the
above multi-line statement as

a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same


is the case with [ ] and { }. For example:

colors = ['red',
'blue',
'green']

We could also put multiple statements in a single line using semicolons, as


follows

a = 1; b = 2; c = 3

2.3.2 Python Indentation

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.

Incorrect indentation will result into IndentationError.

2.3.3 Python Comments

Comments are very important while writing a program. It describes what's


going on inside a program so that a person looking at the source code does not
have a hard time figuring it out. You might forget the key details of the program
you just wrote in a month's time. So taking time to explain these concepts in
form of comments is always fruitful.

In Python, we use the hash (#) symbol to start writing a comment.

It extends up to the newline character. Comments are for programmers for


better understanding of a program. Python Interpreter ignores comment. 

#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

#This is a long comment


#and it extends
#to multiple lines

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

Docstring is short for documentation string.

It is a string that occurs as the first statement in a module, function, class, or


method definition. We must write what a function/class does in the docstring.

Triple quotes are used while writing docstrings. For example:

def double(num):

"""Function to double the value"""

return 2*num

Docstring is available to us as the attribute __doc__ of the function. Issue the


following code in shell once you run the above program.

>>> print(double.__doc__)
Function to double the value

2.4 PYTHON KEYWORDS AND IDENTIFIER

2.4.1 Python Keywords

Keywords are the reserved words in Python.

We cannot use a keyword as variable name, function name or any other


identifier. They are used to define the syntax and structure of the Python
language.
31

In Python, keywords are case sensitive.

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.

Keywords in Python programming language


False Class finally Is return
None Continue for Lambda try
True Def from Nonlocal while
And Del global Not with
As Elif if Or yield
Assert Else import Pass  
Break Except in Raise  

2.4.2 Python Identifiers

Identifier is the name given to entities like class, functions, variables etc. in
Python. It helps differentiating one entity from another.

Rules for writing identifiers

1. Identifiers can be a combination of letters in lowercase (a to z) or


uppercase (A to Z) or digits (0 to 9) or an underscore (_). Names
like myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1
is perfectly fine.
3. Keywords cannot be used as identifiers.

>>> global = 1
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax

4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.

>>> a@ = 0
File "<interactive input>", line 1
a@ = 0
32

^
SyntaxError: invalid syntax

5. Identifier can be of any length.

2.5 PYTHON INPUT, OUTPUT AND IMPORT

Python provides numerous built-in functions that are readily available to us at


the Python prompt.

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.

2.5.1 Python Output Using print() function

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.

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

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&

2.5.2 Output formatting

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

print('I love {1} and {0}'.format('bread','butter'))


# Output: I love butter and bread
We can even use keyword arguments to format the string.
>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning

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

2.5.3 Python Input

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

input([prompt])where prompt is the string we wish to display on the screen. It is


optional.
>>> num = input('Enter a number: ')
34

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

2.5.4 Python Import

When our program grows bigger, it is a good idea to break it into different
modules.

A module is a file containing Python definitions and statements. Python


modules have a filename and end with the extension .py.

Definitions inside a module can be imported to another module or the


interactive interpreter in Python. We use the import keyword to do this.

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:

>>> from math import pi


35

>>> pi
3.141592653589793

While importing a module, Python looks at several places defined in sys.path. It


is a list of directory locations.

>>> import sys


>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

2.6 PYTHON OPERATORS

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.

Python has a number of operators which are classified below.

Type of operators in Python

Arithmetic operators

Comparison (Relational) operators

Logical (Boolean) operators

Bitwise operators

Assignment operators
36

Special operators

2.6.1 Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication etc.

Arithmetic operators in Python

Operator Meaning Example

+ Add two operands or unary plus x+y+2

- Subtract right operand from the left or unary minus x-y-2

* Multiply two operands x*y

Divide left operand by the right one (always results


/ x/y
into float)

Modulus - remainder of the division of left x % y (remainder


%
operand by the right of x/y)

Floor division - division that results into whole


// x // y
number adjusted to the left in the number line

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

2.6.2 Comparison operators

Comparison operators are used to compare values. It either returns True or False
according to the condition.

Comparision operators in Python


Operator Meaning Example
> Greater that - True if left operand is greater than the right x > y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater
>= x >= y
than or equal to the right
Less than or equal to - True if left operand is less than or
<= x <= y
equal to the right

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)

# Output: x == y is False
print('x == y is',x==y)

# Output: x != y is True
print('x != y is',x!=y)

# Output: x >= y is False


38

print('x >= y is',x>=y)

# Output: x <= y is True


print('x <= y is',x<=y)

2.6.3 Logical operators

Logical operators are the and, or, not operators.

Logical operators in Python

Operator Meaning Example

And True if both the operands are true x and y

Or True if either of the operands is true x or y

Not True if operand is false (complements the operand) not x

Example:
x = True
y = False

# Output: x and y is False


print('x and y is',x and y)

# Output: x or y is True
print('x or y is',x or y)

# Output: not x is False


print('not x is',not x)

2.6.4 Bitwise operators

Bitwise operators act on operands as if they were string of binary digits. It


operates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
39

Bitwise operators in Python

Operator Meaning Example

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)

2.6.5 Assignment operators

Assignment operators are used in Python to assign values to variables.

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.

Assignment operators in Python

Operator Example Equivatent to

= 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

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5

2.6.6 Special operators

Python language offers some special type of operators like the identity operator
or the membership operator. They are described below with examples.

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

Identity operators in Python

Operator Meaning Example

True if the operands are identical (refer to the same


Is x is True
object)

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.

2.6.6.2 Membership operators

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.

Operator Meaning Example

In True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x

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

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case


sensitive). Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y r

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:

 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.
 Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4,
and 3*1**3 is 3, not 27.
 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

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.

2.9 TUPLE ASSIGNMENT

Once in a while, it is useful to swap the values of two variables. With


conventional assignment statements, we have to use a temporary variable. For
example, to swap a and b:

>>>temp=a
>>>a=b
>>> b = temp

If we have to do this often, this approach becomes cumbersome. Python


provides a form of tuple assignment that solves this problem neatly:

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

2.10 PYTHON FUNCTIONS

A function is a block of organized, reusable code that is used to perform a


single, related action. Functions provide better modularity for your application
and a high degree of code reusing.

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.

2.10.1 Defining a Function


44

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

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them
in the same order that they were defined.

Example

The following function takes a string as input parameter and prints it on


standard screen.

def printme( str ):


"This prints a passed string into this function"
print str
return

2.10.2 Calling a Function

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

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result −

I'm first call to user defined function!


Again second call to the same function

2.10.3 Pass by reference vs value

All parameters (arguments) in the Python language are passed by reference. It


means if you change what a parameter refers to within a function, the change
also reflects back in the calling function. For example −

#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in
the same object. So, this would produce the following result −
46

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

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

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

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:

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

2.10.4 Function Arguments

You can call a function by using the following types of formal arguments:

 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

2.10.4.1 Required arguments

Required arguments are the arguments passed to a function in correct positional


order. Here, the number of arguments in the function call should match exactly
with the function definition.

To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −
47

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result:

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

2.10.4.2 Keyword arguments

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

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result −

My string
48

The following example gives more clear picture. Note that the order of
parameters does not matter.

#!/usr/bin/python

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50

2.10.4.3Default arguments

A default argument is an argument that assumes a default value if a value is not


provided in the function call for that argument. The following example gives an
idea on default arguments, it prints default age if it is not passed −

#!/usr/bin/python

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50
Name: miki
49

Age 35

2.10.4.4 Variable-length arguments

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.

Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

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

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −

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:

Before swap a = 30 and b = 20

After swaping a = 20 and b = 30

2. Distance Between Two Points


51

Distance Between Two Points Can Be Calculated Using The Below Formula.

Distance Formula: The Distance Formula Is Derived From The Pythagorean


Theorem. To Find The Distance Between Two Points(X1,Y1) and (X2,Y2)

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

You might also like