Imparative Programming in Python
Imparative Programming in 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.
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.
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
Python has some standard types that are used to define the operations possible on them and the
storage method for each of them.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
· 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.
Operator Description
Complement, unary plus and minus (method names for the last two
~+-
are +@ and -@)
· if Statement
· if…elif Statement
· while loop
· for 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.
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.
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’.
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.
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).
Output
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)
input([prompt])
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
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:
Creating a list is as simple as putting different comma-separated values between square brackets.
For example:
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
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 ];
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
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 = ()
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.
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[0]: physics
tup2[1:5]: [2, 3, 4, 5]
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:
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.
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
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['Zara']:
KeyError: 'Alice'
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.
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