Unit Ii
Unit Ii
Unit Ii
Python Mode
The last line is a prompt that indicates that the interpreter is ready for you to enter code.
If you type a line of code and hit Enter, the interpreter displays the result:
>>> 5 + 4
9
This prompt can be used as a calculator. To exit this mode type exit() or quit() and press
enter.
We can use any text editing software to write a Python script file.
We just need to save it with the .py extension. But using an IDE can make our life a lot
easier. IDE is a piece of software that provides useful features like code hinting, syntax
highlighting and checking, file explorers etc. to the programmer for application development.
Using an IDE can get rid of redundant tasks and significantly decrease the time required for
application development.
IDEL is a graphical user interface (GUI) that can be installed along with the Python
programming language and is available from the official website.
We can also use other commercial or free IDE according to our preference.PyScripter IDEis
one of the Open source IDE.
Type the following code in any text editor or an IDE and save it as helloWorld.py
print("Hello world!")
Now at the command window, go to the loaction of this file. You can use the cd command to
change directory.
To run the script, type, python helloWorld.py in the command window. We should be able to
see the output as follows:
Hello world!
If you are using PyScripter, there is a green arrow button on top. Press that button or
press Ctrl+F9 on your keyboard to run the program.
In this program we have used the built-in function print(), to print out a string to the
screen. String is the value inside the quotation marks, i.e. Hello world!.
In these results, the word ―class‖ is used in the sense of a category; a type is
a category ofvalues.Not surprisingly, integers belong to the type int, strings belong to str and
floating-pointnumbers belong to float.What about values like '5' and '83.0'? They look like
numbers, but they are in quotationmarks like strings.
>>>type('5')
<class 'str'>
>>>type('83.0')
<class 'str'>
They‘re strings.When you type a large integer, you might be tempted to use commas
between groups ofdigits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> 1,000,000
(1, 0, 0)
That‘s not what we expected at all! Python interprets 1,000,000 as a comma-
separatedsequence of integers. We‘ll learn more about this kind of sequence later.
2.2.1 Standard Data Types
Python has various standard data types that are used to define the operationspossible
on them and the storage method for each of them.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
2.2.1.1 Python Numbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example –
var1 =1
var2 =10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del var1[,var2[,var3[...,varN]]]]
You can delete a single object or multiple objects by using the del statement. For
example −
delvar
delvar_a,var_b
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
Examples
Here are some examples of numbers –
Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.
2.2.1.2 Python Strings
Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example –
Python Programming
P
g
tho
thon Programming
Python ProgrammingPython Programming
Python Programming Course
2.2.1.3 Python Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is that all the items belonging to a
list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −
>>>bool(1)
True
>>>bool(0)
False
Python's Booleans were added with the primary goal of making code clearer.
For example, if you're reading a function and encounter the statement return 1, you might
wonder whether the 1 represents a Boolean truth value, an index, or a coefficient that
multiplies some other quantity. If the statement is return True, however, the meaning of the
return value is quite clear.
Python's Booleans were not added for the sake of strict type-checking. A very
strict language such as Pascal would also prevent you performing arithmetic with Booleans,
and would require that the expression in an if statement always evaluate to a Boolean result.
Python is not this strict and never will be. This means you can still use any expression in
an if statement, even ones that evaluate to a list or tuple or some random object. The Boolean
type is a subclass of the int class so that arithmetic using a Boolean still works.
>>> True + 1
2
>>> False + 1
1
>>> False * 85
0
>>> True * 85
85
>>>True+True
2
>>>False+False
0
We will discuss about data types like Tuple, Dictionary in Unit IV.
Sometimes, you may need to perform conversions between the built-in types.
To convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type
to another. These functions return a new object representing the converted value.
Function Description
2.3 VARIABLES
Programmers generally choose names for their variables that are meaningful
The Rules
The interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.
Python 3 has these keywords:
except in raise
>>>1book = 'python'
SyntaxError: invalid syntax
>>>more@ = 1000000
SyntaxError: invalid syntax
>>>class = 'Fundamentals of programming'
SyntaxError: invalid syntax
1book is illegal because it begins with a number. more@ is illegal because it
contains an illegal character, @. class is illegal because it is a keyword.
Good Variable Name
Choose meaningful name instead of short name. roll_no is better than rn.
Maintain the length of a variable name. Roll_no_of_a_student is too long?
Be consistent; roll_no or orRollNo
Begin a variable name with an underscore(_) character for a special case.
2.4 EXPRESSIONS AND STATEMENTS
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:
>>> 50
50
>>> 10<5
False
>>> 50+20
70
When you type an expression at the prompt, the interpreter evaluates it, which
means that it finds the value of the expression.
A statement is a unit of code that has an effect, like creating a variable or
displaying a value.
>>> n = 25
>>>print(n)
The first line is an assignment statement that gives a value to n. The second
line is a print statement that displays the value of n. When you type a statement, the
interpreter executes it, which means that it does whatever the statement says. In general,
statements don‘t have values.
Operators are special symbols in Python that carry out computation. The value
that the operator operates on is called the operand.
For example:
>>>10+5
15
Here, + is the operator that performs addition. 10 and 5 are the operands and 15 is the output
of the operation. Python has a number of operators which are classified below.
Arithmetic operators
Comparison (Relational) operators
Logical (Boolean) operators
Bitwise operators
Assignment operators
Special operators
Example
x=7
y=3
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x % y =',x%y)
print('x ** y =',x**y)
When you run the program, the output will be:
x + y = 10
x-y=4
x * y = 21
x / y = 2.3333333333333335
x // y = 2
x%y=1
x ** y = 343
2.5.2 Comparison or Relational Operators
Example
x=5
y=7
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
When you run the program, the output will be:
x >y is False
x <y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
2.5.3 Logical Operators
Example
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
When you run the program, the output will be:
x and y is False
x or y is True
not x is False
2.5.4 Bitwise Operators
Bitwise operators act on operands as if they were string of binary digits. It
operates bit by bit, hence the name.
In Table 2.6: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Example
x=10
y=4
print('x& y=',x& y)
print('x | y=',x | y)
print('~x=',~x)
print('x ^ y=',x ^ y)
print('x>> 2=',x>> 2)
print('x<< 2=',x<< 2)
When you run the program, the output will be:
x& y= 0
x | y= 14
~x= -11
x ^ y= 14
x>> 2= 2
x<< 2= 40
2.5.5 Assignment Operators
There are various compound operators in Python like a += 10 that adds to the
variable and later assigns the same. It is equivalent to a = a + 10.
Table 2.7: Assignment operators in Python
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.
Example
x1 = 7
y1 = 7
x2 = 'Welcome'
y2 = 'Welcome'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
When you run the program, the output will be:
False
True
False
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.
Example
x = 'Python Programming'
print('Program' not in x)
print('Program' in x)
print('program' in x)
When you run the program, the output will be:
False
True
False
Here, ' Program ' is in x but ' program' is not present in x, since Python is case
sensitive.
2.6 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. When an expression
contains more than one operator, the order of evaluation dependson the Precedence of
operations.
>>> 20 – 5*3
5
But we can change this order using parentheses () as it has higher precedence.
>>> (20 - 5) *3
45
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.
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 Comparisions, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR
We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.
For example, multiplication and floor division have the same precedence.
Hence, if both of them are present in an expression, left one is evaluates first.
>>> 10 * 7 // 3
23
>>> 10 * (7//3)
20
>>> (10 * 7)//3
23
We can see that 10 * 7 // 3is equivalent to (10 * 7)//3.
>>> 5 ** 2 ** 3
390625
>>> (5** 2) **3
15625
>>> 5 **(2 **3)
390625
We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).
2.7.1 Non Associative Operators
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
< y and y < z, and is evaluates from left-to-right.
2.9 COMMENTS
As programs get bigger and more complicated, they get more difficult to read.
Formal languages are dense, and it is often difficult to look at a piece of code and figure out
what it is doing, or why. For this reason, it is a good idea to add notes to your programs to
explain in natural language what the program is doing. These notes are called comments, and
they start with the # symbol:
# computeArea of a triangle using Base and Height
area= (base*height)/2
In this case, the comment appears on a line by itself. You can also put
comments at the endof a line:
area= (base*height)/2 # Area of a triangle using Base and Height
Everything from the # to the end of the line is ignored—it has no effect on the
execution ofthe program.Comments are most useful when they document non-obvious
features of the code. It isreasonable to assume that the reader can figure out what the code
does; it is more useful toexplain why.
This comment is redundant with the code and useless:
base= 5 # assign 5 to base
This comment contains useful information that is not in the code:
base = 5 # base is in centimetre.
Good variable names can reduce the need for comments, but long names can
make complexexpressions hard to read, so there is a tradeoff.
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:
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.9.1 Docstring in Python
def area(r):
"""Compute the area of Circle"""
return 3.14159*r**2
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(area. doc )
Compute the area of Circle
2.10. MODULES AND FUNCTIONS
2.10.1 Functions
In the context of programming, a function is a named sequence of statements
that performs a computation. When you define a function, you specify the name and the
sequence of statements. Later, you can ―call‖ the function by name. 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.
Functions
Note that:
>>>range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>range(5,10)
[5, 6, 7, 8, 9]
>>>range(10,1,-2)
[10, 8, 6, 4, 2]
>>> x=10
>>> y=7
>>>print('The sum of', x, 'plus', y, 'is', x+y)
The sum of 10 plus 7 is 17
You can also use it with no parameters:
print()
>>> x=10
>>> y=7
>>>print'The sum of', x, 'plus', y, 'is', x+y
The sum of 10 plus 7 is 17
Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are −
raw_input
input
Example of a function
def welcome(person_name):
"""This function welcome
the person passed in as
parameter"""
print(" Welcome " , person_name , " to Python Function Section")
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
defabsolute_value(num):
"""This function returns the absolute
value of the entered number"""
ifnum>= 0:
returnnum
else:
return -num
print(absolute_value(5))
print(absolute_value(-7))
def welcome(person_name):
print(" Welcome " , person_name , " to Python Function Section")
This function assigns the argument to a parameter named person_name. When
the function is called, it prints the value of the parameter (whatever it is). This function works
with any value that can be printed.
>>>welcome("Vinu")
Welcome Vinu to Python Function Section
>>>welcome(100)
Welcome 100 to Python Function Section
>>>welcome(50.23)
Welcome 50.23 to Python Function Section
The argument is evaluated before the function is called, so in the below
examples the expressions 'vinu'*3 is evaluated.
>>>welcome('vinu'*3)
Welcome vinuvinuvinu to Python Function Section
>>>student_name='Ranjith'
>>>welcome(student_name)
Welcome Ranjith to Python Function Section
2.10.4 Modules
A module allows you to logically organize your Python code. Grouping
related code into a module makes the code easier to understand and use. A module is a file
that contains a collection of related functions. Python has lot of built-in modules; math
module is one of them. math module provides most of the familiar mathematical functions.
Before we can use the functions in a module, we have to import it with an
import statement:
>>> import math
This statement creates a module object named math. If you display the
module object, youget some information about it:
>>>math
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and the name of
the function, separated by a dot (also known as a period). This format is called dot notation.
>>>math.log10(200)
2.3010299956639813
>>>math.sqrt(10)
3.1622776601683795
Math module have functions like log(), sqrt(), etc… In order to know what are
the functions available in particular module, we can use dir() function after importing
particular module. Similarly if we want to know detail description about a particular module
or function or variable means we can use help() function.
Eg.
>>> import math
>>>dir(math)
[' doc ', ' name ', ' package ', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh',
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor',
'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>>help(pow)
Help on built-in function pow in module builtin :
pow(...)
pow(x, y[, z]) -> number
Programs that will be imported as modules often use the following idiom:
if name == ' main ':
add(10,20)
name is a built-in variable that is set when the program starts. If the
program is running as a script, name has the value ' main '; in that case, the test code
runs. Otherwise, if the module is being imported, the test code is skipped. Modify
addModule.py file as given below.
def add(a, b):
result = a + b
print(result)
if name == ' main ':
add(10,20)
Now while importing addModule test case is not running
>>> import addModule
name has module name as its value when it is imported. Warning: If you
import a module that has already been imported, Python does nothing. It does not re-read the
file, even if it has changed. If you want to reload a module, you can use the built-in function
reload, but it can be tricky, so the safest thing to do is restart the interpreter and then import
the module again.
We can do the same swapping operation even without the use of third variable,
There are number of ways to do this, they are.
In this method inthe above programinstead of line number 3,4,5 use a single
tuple assignment statement
var1 , var2 = var2 , var1
The left side is a tuple of variables; the right side is a tuple of expressions.
Each value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.
If the variables are both numbers, Swapping can be performed using simple
mathematical addition subtraction relationship or multiplication division relationship.
In this method inthe above program instead of line number 3,4,5 use the following
code
x=x+y
y=x-y
x=x-y
Multiplication and Division
In this method inthe above program instead of line number 3,4,5 use the following
code
x=x*y
y=x/y
x=x/y
2.11.1.2.3 Using Bitwise operators
If the variables are integers then we can perform swapping with the help of bitwise
XOR operator. In order to do this in the above program instead of line number 3,4,5 use the
following code
x=x^y
y=x^y
x=x^y
1 2 3 4 5 6 7
Figure 2.4.aExample List
Consider the above list Figure 2.4.a; circulation of the above list by n position
can be easily achieved by slicing the array into two and concatenating them. Slicing is done
as nth element to end element + beginning element to n-1 th element. Suppose n=2 means,
given list is rotated 2 positions towards left side as given in Figure 2.4.b
3 4 5 6 7 1 2
Figure 2.4.b Left Circulated List
6 7 1 2 3 4 5
Figure 2.4.c Right Circulated List
>>>circulate([1,2,3,4,5,6,7], 2)
[3, 4, 5, 6, 7, 1, 2]
>>>circulate([1,2,3,4,5,6,7], -2)
[6, 7, 1, 2, 3, 4, 5]