Você está na página 1de 42

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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

Python interpreter :

Python is a high-level, interpreted, interactive and object-oriented scripting language.


• Python was designed to be highly readable which uses English keywords frequently
whereas other languages use punctuation and it has fewer syntactical constructions than
other languages
• Python is Interpreted - It means that it is processed at runtime by the interpreter and
you do not need to compile your program before executing it.

What is interpreter and compiler


• A program that executes instructions line by line and converts to intermediate form called
interpreter
• A compiler translates high-level instructions directly into machine language

• Python is Interactive - It means that you can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
• Python is Object-Oriented - It means that Python supports Object Oriented style or
technique of programming that encapsulates code within objects.
• Python is Beginner's Language - Python is a great language for the beginner
programmers and supports the development of a wide range of applications from simple
text processing to www browsers to games.
• Easy-to-maintain - Python's success is that its source code is fairly easy-to-maintain.

1 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

• A Broad Standard Library - One of Python's greatest strengths is the bulk of the library
is very portable and cross-platform compatible on UNIX, Windows and Macintosh.
• 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.

Python
Python is an interpreted, cross-platform, object-oriented language that can be used to write
large scale Internet search engines, small administration scripts, GUI applications, CGI
scripts and more.
Python is a freely distributed technology whose open-source nature has encouraged a
wide base of developers to submit modules that extend the language. Using Python’s core
modules and those freely available on the Web, programmers can develop applications that
accomplish a great variety of tasks. Python’s interpreted nature facilitates rapid application
development (RAD) of powerful programs. GUI applications, in particular, can be tested
quickly and developed using Python’s interface to Tcl/Tk (among other GUI toolkits).
Running Python
There are three different ways to start Python:

(1) Interactive Interpreter:


You can start Python from Unix, DOS, or any other system that provides you a
command line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
Here is the list of all the available command line options:

Option Description
-d : provide debug output
-O : generate optimized byte code (resulting in .pyo files)
-S : do not run import site to look for Python paths on startup
-v : verbose output (detailed trace on import statements)

2 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

-X : disable class-based built-in exceptions (just use strings); obsolete starting with
versionb1.6
-c : cmd run Python script sent in as cmd string
file : run Python script from given file

(2) Script from the Command-line:


A Python script can be executed at command line by invoking the interpreter on
your application, as in the following:
$python script.py # Unix/Linux
or
python% script.py # Unix/Linux
or
C:>python script.py # Windows/DOS
Note: Be sure the file permission mode allows execution.

(3) Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you
have a GUI application on your system that supports Python.
 Unix: IDLE is the very first Unix IDE for Python.
 Windows: Python Win is the first Windows interface for Python and is an IDE with
a GUI.
 Macintosh: The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.

If you are not able to set up the environment properly, then you can take help from your
system admin. Make sure the Python environment is properly set up and working perfectly
fine.

Note: All the examples given in subsequent chapters are executed with Python 2.4.3
version available on CentOS flavor of Linux.

We already have set up Python Programming environment online, so that you can execute
all the available examples online at the same time when you are learning theory. Feel free
to modify any example and execute it online.

The Python language has many similarities to Perl, C, and Java. However, there are some
definite differences between the languages.

First Python Program


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

3 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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

4 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

This produces the following result

Hello, Python!

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

5 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

# Output: 1 2 3 4

print(1,2,3,4,sep='*')

# Output: 1*2*3*4

print(1,2,3,4,sep='#',end='&')

# Output: 1#2#3#4&

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)

6 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

The value of x is 12.35


>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

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


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

7 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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

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


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

8 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed
by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are
two different identifiers in Python.

Here are naming conventions for Python identifiers Class names start with an uppercase
letter. All other identifiers start with a lowercase letter. Starting an identifier with a single
leading underscore indicates that the identifier is private. Starting an identifier with two
leading underscores indicates a strongly private identifier. If the identifier also ends with
two trailing underscores, the identifier is a language defined special name.

Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot
use them as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
Keywords in Python programming language

and del global return with

as elif if try yield

assert else import while print

break except is not

class finally lambda or

continue for exec pass

def from in raise

9 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Values and data types


A value is one of the fundamental things — like a letter or a number — that a program
manipulates. The values we have seen so far are 2 (the result when we added 1 + 1),
and "Hello, World!".
These values belong to different data types: 2 is an integer, and "Hello, World!" is a string,
so-called because it contains a string of letters. You (and the interpreter) can identify strings
because they are enclosed in quotation marks.
Data types in Python

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.

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 is instance() function to check if an object belongs to a particular class.

Eg:
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?", is instance(1+2j,complex))

Answer :
(5, 'is of type', <type 'int'>)
(2.0, 'is of type', <type 'float'>)
((1+2j), 'is complex number?', True)

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.

10 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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
>>> c = 1+2j
>>> c
(1+2j)

Notice that the float variable b got truncated.

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

11 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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

>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]

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)

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

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

12 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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'

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

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

13 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

File "<string>", line 301, in runcode


File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing

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

14 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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

15 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

{3: 26, 4: 44}

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.

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.

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.

16 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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.

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

Python Indentation

Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation.

17 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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. Here is an
example.

for i in range(1,11):
print(i)
if i == 5:
break

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 Indentation Error.

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.

18 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

#This is a comment
#print out Hello
print('Hello')

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:

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

Evaluating expressions
An expression is a combination of values, variables, and operators. If you type an expression
on the command line, the interpreter evaluates it and displays the result:

>>> 1 + 1
2

The evaluation of an expression produces a value, which is why expressions can appear on the
right hand side of assignment statements. A value all by itself is a simple expression, and so is
a variable.

>>> 17
17
>>> x
2

19 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Confusingly, evaluating an expression is not quite the same thing as printing a value.

>>> message = "What's up, Doc?"


>>> message
"What's up, Doc?"
>>> print message
What's up, Doc?

When the Python shell displays the value of an expression, it uses the same format you would
use to enter a value. In the case of strings, that means that it includes the quotation marks.
But the print statement prints the value of the expression, which in this case is the contents
of the string.

Tuple Assignment :
• A tuple is a sequence of values.
• The values can be any type, and they are indexed by integers
• Example Swap to variables
>>> temp = a
>>> a = b
>>> b = temp

Tuple assignment
>>> a, b = b, a
The left side is a tuple of variables;
the right side is a tuple of expressions

• Each value is assigned to its respective variable


• >>> a, b = 1, 2, 3

• ValueError: too many values to unpack


• The number of variables on the left and the number of values on the right have to be the
same

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

20 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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

Special operators

Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication etc.

Arithmetic operators in Python

Operator Meaning Example

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

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

* Multiply two operands x*y

Divide left operand by the right one (always results into


/ x/y
float)

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


%
right of x/y)

21 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Floor division - division that results into whole number


// x // y
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 #1: Arithmetic operators in Python


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)

# 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

22 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Comparison operators are used to compare values. It either


returns True or False according to the condition.

Comparison 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 than or


>= x >= y
equal to the right

Less than or equal to - True if left operand is less than or equal to


<= x <= y
the right

Example #2: Comparison operators in Python


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


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

# Output: x <= y is True


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

23 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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 #3: Logical Operators in Python


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)

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)

24 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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)

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

25 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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

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

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

Special operators

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

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

is True if the operands are identical (refer to the same object) x is True

True if the operands are not identical (do not refer to the same x is not
is not
object) True

Example #4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
26 I. Rajasubramanian, AP / CSE, DRGUPCE
GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

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.

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 #5: Membership operators in Python


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)

27 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

# Output: False
print('a' in y)

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 returns False.

Precedence of Python Operators

The combination of values, variables, operators and function calls is termed as an


expression. Python interpreter can evaluate a valid expression.

For example:

>>> 5 - 7
-2

Here 5 - 7 is an expression. There can be more than one operator in an expression.

To evaluate these type of expressions there is a rule of precedence in Python. It guides the
order in which operation are carried out.

For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence


# than subtraction
# Output: 2
10 - 4 * 2

But we can change this order using parentheses () as it has higher precedence.

# Parentheses () has higher precendence


# Output: 12
(10 - 4) * 2

The operator precedence in Python are listed in the following table. It is in descending
order, upper group has higher precedence than the lower ones.

28 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Operator precedence rule in Python

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR

Parameters and arguments


Inside the function, the arguments are assigned to variables called parameters.
must admit that the notions of parameters and arguments was very abstract.
I read it several times and I was not sure after each reading who was who. This was the
perfect occasion to talk to a Computer Science (CS) professional.

If you do not know any CS professional, go to MeetUps. There are Python study groups that
can be a valuable resource at this point.

 PyLadies (is a great start)

29 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

 Girl Develop It (They offer an Intro to Python course. Their approach is hands-on
experience)
 Python MeetUp Groups
Let us consider the following:

x=3

My mathematical background made me read this as:

x equals to 3
So, when I saw this expression, I freaked out … literally!

x=x+1

How can x be equal to x plus 1?!

***

After chatting with one CS professional, I understood that:

A variable is a “place holder”. Let us see how this changes our point of view:

x=3

This statement means that variable x holds or gets the value of 3.

Knowing this, the expression: x = x + 1 is read as: variable x gets the value of x plus one (1).

Let us consider the example in Chapter Three (3):

In the Python shell, let us define a function named: ‘print_twice’

>>> def print_twice(bruce):


… print bruce
… print bruce

>>>

‘bruce’ is our parameter.

30 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

So, let us call the function ‘print_twice’ that we just created in the Python shell with
the argument “Laaa, lalalalala “:
>>> print_twice (“Laaa, lalalalala “)
Laaa, lalalalala
Laaa, lalalalala
>>>

I stumbled on the fact that the concepts of parameter and variable seemed identical to
me. I understood why:
When we define our function, the most important is to establish what the function will do.
You do not want to start thinking about what you can put in the function. At the creation
stage, you just want your function to work in a particular way. In that case, you will use the
concept of parameter.
Later, when you want to call the function and you know what you want to put in to make it
work, you may use a variable or an argument.
Let us see how the function works with a variablenamed x :
Remember: Variable x gets the value of the following string “Hickory Dickory Dock”

>>> x = “Hickory Dickory Dock”


>>> print_twice (x)
Hickory Dickory Dock
Hickory Dickory Dock
>>>

So, we can make our function work with arguments and previously defined variables.

Recap: In a function (built-in or user-defined) the argument is evaluated before the


function is called.

When we use built-in modules in our function definition, here is something to consider:

 def module name . function name (parameters)


This first function definition provides the name of the module, the name of the function we
want to use from the module and it states the parameter name.

Remember: A parameter is an information that I want to to consider but I still do not know
the exact value.

 def module name . function name (argument 1, argument 2, … argument n)


This second function definition provides the name of the module, the name of the function
we want to use from the module and it states the value of the arguments. An argument is a
precise piece of information.

31 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Variables and parameters are local


When you create a variable inside a function, it is local, which means that it only exists
inside the function

Using the user-defined function we created earlier ‘print_twice’, let us try this in the Python
shell, in order to seize this concept.

1) Let us create a user-defined function called ‘cat_twice’


NOTE: My comments start with a # sign and are italicized.
>>> def cat_twice(part1, part2):
… cat = part1 + part2 #variable ‘cat’ gets the value of the concatenation of
parameter no1 (called ‘part1’) and parameter no2 (called ‘part2’)
… print_twice (cat) #we will call the function that we created earlier
‘print_twice’ with the variable ‘cat’

>>>
Moreover, let us the function we just created ‘cat_twice’ with a set of two (2) variables:

>>> line1 = “Hickory Dickory Dock” #The variable ‘line1’ gets the value of “Hickory
Dickory Dock”
>>> line2 = “The mouse ran up the clock.” #The variable ‘line2’ gets the value of “The
mouse ran up the clock”
>>> cat_twice (line1, line2) #We will call the function that we created
‘cat_twice’ with the variables ‘line1’ and ‘line2’
Hickory Dickory DockThe mouse ran up the clock.
Hickory Dickory DockThe mouse ran up the clock.
>>> #The result is the concatenation of variables ‘line1’
and ‘line2’ and printed twice
Let us double-check what happens with the variable ‘cat’ that we initially defined in the
function ‘cat_twice’

>>> print cat


Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘cat’ is not defined
>>>
When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an
exception:

NameError: name ‘cat’ is not defined

Furthermore, it is important to notice that the parameter ‘bruce’ is useless outside the
function we defined called ‘print_twice’.

32 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Flow of Execution

When you are working with functions it is really important to know the order in which
statements are executed. This is called the flow of execution and we’ve already talked
about it a number of times in this chapter.
Execution always begins at the first statement of the program. Statements are executed one
at a time, in order, from top to bottom. Function definitions do not alter the flow of
execution of the program, but remember that statements inside the function are not
executed until the function is called. Function calls are like a detour in the flow of
execution. Instead of going to the next statement, the flow jumps to the first line of the
called function, executes all the statements there, and then comes back to pick up where it
left off.
That sounds simple enough, until you remember that one function can call another. While
in the middle of one function, the program might have to execute the statements in another
function. But while executing that new function, the program might have to execute yet
another function!
Fortunately, Python is adept at keeping track of where it is, so each time a function
completes, the program picks up where it left off in the function that called it. When it gets
to the end of the program, it terminates.
What’s the moral of this sordid tale? When you read a program, don’t read from top to
bottom. Instead, follow the flow of execution. This means that you will read
the def statements as you are scanning from top to bottom, but you should skip the body of
the function until you reach a point where that function is called.

def pow(b, p):

y = b ** p

return y

def square(x):

a = pow(x, 2)

return a

n=5

result = square(n)

33 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

print(result)

>>>
25

MODULES

Modules refer to a file containing Python statements and definitions.

A file containing Python code, for e.g.: example.py, is called a module and its module name
would be example.

We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.

We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.

Let us create a module. Type the following and save it as example.py.

# Python Module example

def add(a, b):


"""This program adds two
numbers and return the result"""

result = a + b
return result

Here, we have defined a function add() inside a module named example. The function takes
in two numbers and returns their sum.

34 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Function
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements
must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

35 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

Function Call

Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.

>>> greet('Paul')

Hello, Paul. Good morning!

How Function works in Python?

>>> def findArea(radius):


... area = 3.14159 * radius ** 2
... return area

>>> findArea(3)
28.27431

Function definition

A function is a block of reusable code that is used to perform a specific action. The
advantages of using functions are:

 Reducing duplication of code

36 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

 Decomposing complex problems into simpler pieces


 Improving clarity of the code
 Reuse of code
 Information hiding

Functions in Python are first-class citizens. It means that functions have equal status with
other objects in Python. Functions can be assigned to variables, stored in collections, or
passed as arguments. This brings additional flexibility to the language.

37 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

38 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

39 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

40 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

41 I. Rajasubramanian, AP / CSE, DRGUPCE


GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNITII

42 I. Rajasubramanian, AP / CSE, DRGUPCE

Você também pode gostar