0% found this document useful (0 votes)
16 views16 pages

Imparative Programming in Python

Imperatives Programing in python

Uploaded by

Rowen Fernando
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views16 pages

Imparative Programming in Python

Imperatives Programing in python

Uploaded by

Rowen Fernando
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

5 Imperative Programming with Python

5.1 Introduction
Python is a widely used high-level programming language for
general-purpose programming, created by Guido van Rossum and
first released in 1991.

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

5.1.1 Features of Python


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

Unit 01: Programming 29


5.2 Using Variables in Python
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can
store integers, decimals, or characters in these variables.

5.2.1 Assigning Values to Variables


Python variables do not have to be explicitly declared to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.

The operand to the left of the = operator is the name of the variable, and the operand to the right
of the = operator is the value stored in the variable. For example:

Example 1

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)

5.2.2 Standard Data Types


The data stored in memory can be of many types. For example, a person’s age is stored as a numeric
value and his or her address is stored as alphanumeric characters.

Python has some standard types that are used to define the operations possible on them and the
storage method for each of them.

Python has five standard data types:

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

30 Unit 01: Programming


5.3 Python Operators

5.3.1 What is an operator?


Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands
and + is called operator. Python language supports following type of operators.

· Arithmetic Operators
· Comparison Operators
· Logical (or Relational) Operators
· Assignment Operators
· Conditional (or ternary) Operators
Let’s have a look on all operators one by one.

5.3.2 Python Arithmetic Operators:

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

Operator Description Example

Addition - Adds values on either side of


+ a + b will give 30
the operator

Subtraction - Subtracts right hand


- a - b will give -10
operand from left hand operand

Multiplication - Multiplies values on


* a * b will give 200
either side of the operator

Division - Divides left hand operand by


/ b / a will give 2
right hand operand

Modulus - Divides left hand operand by


% right hand operand and returns b % a will give 0
remainder

Exponent - Performs exponential (power)


** a**b will give 10 to the power 20
calculation on operators

Floor Division - The division of operands


where the result is the quotient in which 9//2 is equal to 4 and 9.0//2.0 is equal to
//
the digits after the decimal point are 4.0
removed.

Unit 01: Programming 31


5.3.3 Python Comparison Operators:

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

Operator Description Example

== Checks if the value of two operands are


equal or not, if yes then condition (a == b) is not true.
becomes true.

!= Checks if the value of two operands are


equal or not, if values are not equal then (a != b) is true.
condition becomes true.

<> Checks if the value of two operands are


(a <> b) is true. This is similar to !=
equal or not, if values are not equal then
operator.
condition becomes true.

Checks if the value of left operand is


> greater than the value of right operand, if (a > b) is not true.
yes then condition becomes true.

Checks if the value of left operand is less


< than the value of right operand, if yes (a < b) is true.
then condition becomes true.

Checks if the value of left operand is


greater than or equal to the value of right
>= (a >= b) is not true.
operand, if yes then condition becomes
true.

Checks if the value of left operand is less


than or equal to the value of right
<= (a <= b) is true.
operand, if yes then condition becomes
true.

32 Unit 01: Programming


5.3.4 Python Assignment Operators:

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

Operator Description Example

Simple assignment operator, Assigns


= values from right side operands to left c = a + b will assign value of a + b into c
side operand

Add AND assignment operator, It adds


+= right operand to the left operand and c += a is equivalent to c = c + a
assign the result to left operand

Subtract AND assignment operator, It


subtracts right operand from the left
-= c -= a is equivalent to c = c – a
operand and assign the result to left
operand

Multiply AND assignment operator, It


multiplies right operand with the left
*= c *= a is equivalent to c = c * a
operand and assign the result to left
operand

Divide AND assignment operator, It


divides left operand with the right
/= c /= a is equivalent to c = c / a
operand and assign the result to left
operand

Modulus AND assignment operator, It


%= takes modulus using two operands and c %= a is equivalent to c = c % a
assign the result to left operand

Exponent AND assignment operator,


Performs exponential (power) calculation
**= c **= a is equivalent to c = c ** a
on operators and assign value to the left
operand

Floor Division and assigns a value,


//= Performs floor division on operators and c //= a is equivalent to c = c // a
assign value to the left operand

Unit 01: Programming 33


5.3.5 Python Operators Precedence
The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

Complement, unary plus and minus (method names for the last two
~+-
are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'

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

<= < > >= Comparison operators

<> == != Equality operators

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

Is. is not Identity operators

In. not in Membership operators

not or and Logical operators

5.4 Control Constructs – Advanced Syntaxes


In chapter 3 we have already discussed in detail the syntaxes of the following control constructs.
Therefore in this section we will only list them here to recap on what we have done.

· if Statement
· if…elif Statement
· while loop
· for loop

34 Unit 01: Programming


5.4.1 Break and Continue Keywords
In Python, break and continue statements can alter the flow of a normal loop.

Loops iterate over a block of code until test expression is false, but sometimes we wish to terminate
the current iteration or even the whole loop without checking test expression.

The break and continue statements are used in these cases.

Python break statement

The break statement terminates the loop


containing it. Control of the program flows
to the statement immediately after the
body of the loop.

If break statement is inside a nested loop


(loop inside another loop), break will
terminate the innermost loop. The break
statement can be used in both while loop as
well as for loop.

Python continue statement

The continue statement is used to skip the


rest of the code inside a loop for the current
iteration only. Loop does not terminate but
continues on with the next iteration.

Unit 01: Programming 35


What will be the output of the following program?

# Use of break statement inside a for loop


Output
for val in "string":
if val == "i":
break
print(val)
print("The end")

What will be the output of the following program?

# Use of continue statement inside a while loop


Output
x = 1
while x <= 10:
if x % 3 == 0:
continue
print(x)
print("The end")

5.4.2 else Statement in loops


In almost every programming language ‘else’ can be used only with conditional statements such as
if and case. However, it is interesting to note that Python allows us to use else statements with loops
too (i.e., with while loops and for loops).

x = 1
Output
while x<=5:
print(x)
x = x + 1
else:
print(“The end value of x = “,x)
print(“** The End **”)

What is the output of the program? Note that the else block is executed immediately after the
condition becomes false before executing statements outside while block.

36 Unit 01: Programming


Consider the following example. This time it is a for loop and inside that we are using a if condition
with a break keyword. What will be the output of this program.

for x in range(1, 5):


if == 3: Output
if x == 3:
break
break
print(x)
else:
print(“The end value of x = “,x)
print(“** The End **”)

Now change the above program by replacing the break keyword with continue keyword and run the
program again. Can you explain the reason for not executing the ‘else block’ with ‘break’ but
executing it with ‘continue’.

5.5 Displaying Output with - 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.

Output
# Here line numbers should not be typed
1: Hello, Welcome
1: print('Hello, Welcome’)
2: The value of a is 5
2: a = 5
3: print('The value of a is', a)

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)

· objects – is the value(s) to be printed.


· sep – is the separator used between the values. It defaults into a space character.
· end – is printed after all values are printed. It defaults into a new line.
· file – is the object where the values are printed and its default value is sys.stdout (screen).

Unit 01: Programming 37


Here is an example to illustrate this.

Output
# Here line numbers should not be typed
1: 1 2 3 4
1: print(1,2,3,4)
2: 1*2*3*4
2: print(1,2,3,4,sep='*')
3: print(1,2,3,4,sep='#',end='&') 3: 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.

Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by
using numbers (tuple index).

# Here line numbers should not be typed


1: x = 5; y = 10
2: print('The value of x is {} and y is {}'.format(x,y))
3: print('I love {0} and {1}'.format('bread','butter'))
3: print('I love {1} and {0}'.format('bread','butter'))

Output

1: The value of x is 5 and y is 10

2: I love bread and butter

3: I love butter and bread

We can even format strings like the old printf() style used in C programming language.
We use the % operator to accomplish this.

Output
# Here line numbers should not be typed
12: The value of x is 12.35
1: x = 12.3456789
3: The value of x is 12.3457
2: print('The value of x is %3.2f' %x)
3: print('The value of x is %3.4f' %x)

38 Unit 01: Programming


5.6 Reading Keyboard Input with - input() function
Python provides this function to read a line of text from standard input, which by default comes from
the keyboard.

The syntax for input() is

input([prompt])

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

5.7 Special Data Types

5.7.1 Python Strings


Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes.

Creating strings is as simple as assigning a value to a variable. For example:

var1 = 'Hello World!'


var2 = "Python Programming"

Accessing Values in Strings:

Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.

To access substrings, use the square brackets for slicing along with the index or indices to obtain
your substring:

Unit 01: Programming 39


Example:

var1 = "Hello World!"


var2 = "Python Programming"

print("var1[0]: ", var1[0])


print("var2[1:5]: ", var2[1:5])

This will produce the following output.

5.7.2 Python - Lists


The list is a most versatile data type available in Python, which can be written as a list of comma-
separated values (items) between square brackets. Good thing about a list that items in a list need
not all have the same type:

Creating a list is as simple as putting different comma-separated values between square brackets.
For example:

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Accessing Values in Lists:

To access values in lists, use the square brackets for slicing along with the index or indices to obtain
value available at that index:

Example:

#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];

print("list1[0]: ", list1[0])


print("list2[1:5]: ", list2[1:5])

40 Unit 01: Programming


This will produce following result:

list1[0]: physics

list2[1:5]: [2, 3, 4, 5]

5.7.3 Python – Tuples


A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only
difference is that tuples can't be changed ie: Tuples are immutable and tuples use parentheses and
lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values and optionally you can put
these comma-separated values between parentheses also. For example:

tup1 = ('physics', 'chemistry', 1997, 2000)


tup2 = (1, 2, 3, 4, 5 )
tup3 = ("a", "b", "c", "d")

The empty tuple is written as two parentheses containing nothing:

tup1 = ()

To write a tuple containing a single value you have to include a comma, even though there is only

tup1 = (50,)

one value:

Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.

Accessing Values in Tuples:

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain
value available at that index:

Example:

#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );

print("tup1[0]: ", tup1[0])


print("tup2[1:5]: ", tup2[1:5])

Unit 01: Programming 41


This will produce following result:

tup1[0]: physics

tup2[1:5]: [2, 3, 4, 5]

5.7.4 Python - Dictionary


A dictionary is mutable and is another container type that can store any number of Python objects,
including other container types.

Dictionaries consist of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a
dictionary is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can create dictionary in the following way as well:

dict1 = { 'abc': 456 };


dict2 = { 'abc': 123, 98.6: 37 };

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole
thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly
braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any
type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary:

To access dictionary elements, you use the familiar square brackets along with the key to obtain its
value:

Example:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print("dict['Name']: ", dict['Name'])


print("dict['Age']: ", dict['Age'])

42 Unit 01: Programming


This will produce following result:

dict['Name']: Zara

dict['Age']: 7

If we attempt to access a data item with a key which is not part of the dictionary, we get an error as
follows:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print("dict['Alice']: ", dict['Alice'])

This will produce following result:

dict['Zara']:

Traceback (most recent call last):

File "test.py", line 4, in <module>

print "dict['Alice']: ", dict['Alice'];

KeyError: 'Alice'

5.8 Python – Functions


Defining a Function

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.

Unit 01: Programming 43


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

5.9 Importing Other Modules


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)

import sys
sys.path

44 Unit 01: Programming

You might also like