Py Unit - 2
Py Unit - 2
1 Introduction to Python
The Python programming language was conceived in the late 1980s, and its
implementation was started in December 1989 by Guido van Rossum at CWI in
the Netherlands as a successor to the ABC programming language. When he began
implementing Python, Guido van Rossum was also reading the published scripts
from “Monty Python’s Flying Circus‖, a BBC comedy series from the 1970s. Van
Rossum thought he needed a name that was short, unique, and slightly mysterious,
so he decided to call the language Python.
Python is a cross-platform programming language, meaning, it runs on multiple
platforms like Windows, Mac OS X, Linux, Unix and has even been ported to the
Java and .NET virtual machines. It is free and open source.
The different versions of python along with the release dates are as follows:
Python 1.0 - January 1994
2. 2 Python Setup
To download and Install the Python interpreter (and bundled IDLE program)
go to http://www.python.org/download/. Options available on Python website are as
follows:
Python 3.6
££ Download Windows x86 MSI Installer
££ Download Windows x86-64 MSI Installer
2.2.1 Installation of Python
Linux Environment
Platform to be installed: Centos 7 (RPM based linux).
££ Requirements
££ Memory: 4GB (Recommended)
££ Storage: 100GB
££ Processor: Intel Core i3
££ Kernel: 3.10
Windows Environment
Requirements:
££ 24 Mb of disk space.
2.2.2 Python Keywords
Keywords are reserved words that cannot be used as ordinary identifiers. All
the keywords except True, False and None are in lowercase and they must be written
as it is.
The list of all the keywords are given below
and del from not while as elif global or
Python is a case-sensitive language. This means, Variable and variable are not
the same
2.2.4 Python Comments
Comments are very important while writing a program. Comment statements
are used to provide a summary of the code in plain English to help future developers
better understand the code.
Single Line comments
1. #This is a comment statement
2. print(‘Hello’)
Multi-line comments
1. #This is a long comment
2. #and it extends
3. 3 #to multiple lines
Another way of using multi-line comments is to use triple quotes, either “ “ “or”
“ “.
1. “ “ “ This is also a
2. perfect example of
3. multi-line comments” “ “
Data, Expressions Statements 2.5
The first three lines contain information about the interpreter and the operating
system it‘s running on, so it might be different for you. But you should check that the
version number, which is 2.7.13 in this example, begins with 2, which indicates that
you are running Python 2. If it begins with 3, you are running Python 3.
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
This prompt can be used as a calculator. To exit this mode type exit() or quit()
and press enter.
2.3.3 Script Mode
This mode is used to execute Python program written in a file. Such a file is
called a script. Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with .py.
For example: helloWorld.py
To execute this file in script mode we simply write python helloWorld.py at the
command prompt.
2.3.4 Integrated Development Environment (IDE)
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.
Data, Expressions Statements 2.7
We can also use other commercial or free IDE according to our preference.
PyScripter IDE is one of the Open source IDE.
2.3.5 Hello World Example
Now that we have Python up and running, we can continue on to write our first
Python program.
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!.
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
Python supports four different numerical types -
Data, Expressions Statements 2.9
delvardelvar_a,var_b
printstr+”Course”
#Prints complete string
#Prints first character of the string
#Prints last character of the string
#Printscharacters startingfrom3rd to 5th
#Prints string startingfrom 3rd character
#Prints stringtwo times
#Printsconcatenatedstring
list=[ ‘Hai’,123,1.75,’vinu’,100.25
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.
2. 12 Problem Solving and Python Programming
>>>True+12
>>>False+11
>>>False*85
0
>>>True*8585
>>>True+True2
>>>False+False
0
We will discuss about data types like Tuple, Dictionary in Unit IV.
2.4.2 Data Type Conversion
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
This example makes three assignments. The first assigns a string to a new
variable named message; the second gives the integer 15 to num; the third assigns
floating point value 5.4 to variable radius.
2.5.2 Variable Names
Programmers generally choose names for their variables that are meaningful
The Rules
1. Variables names must start with a letter or an underscore, such as:
££ _mark
££ mark_
2. The remainder of your variable name may consist of letters, numbers and
underscores.
££ subject1
££ my2ndsubject
££ un_der_scores
4. Names are case sensitive.
££ case_sensitive, CASE_SENSITIVE, and Case_Sensitive are each a
different variable.
££ Can be any (reasonable) length
2. 14 Problem Solving and Python Programming
There are some reserved (KeyWords) words which you cannot use as a variable
name because Python uses them for other things.
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
>>>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.
2.6.1 Difference between a Statement and an Expression
A statement is a complete line of code that performs some action, while an
expression is any section of the code that evaluates to a value. Expressions can
be combined horizontally into larger expressions using operators, while
statements can only be combined vertically by writing one after another,
or with block constructs. Every expression can be used as a statement, but most
statements cannot be used as expressions.
2. 7 Operators
In this section, you’ll learn everything about different types of operators in
Python, their syntax and how to use them with examples.
Operators are special symbols in Python that carry out computation. The value
that the operator operates on is called the operand.
2. 16 Problem Solving and Python Programming
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
> 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
Example
x=5
y=7
print(‘x > yis’,x>y)
print(‘x < yis’,x<y)
print(‘x==yis’,x==y)
print(‘x != y is’,x!=y)
print(‘x>=yis’,x>=y)
print(‘x<=yis’,x
x and y is False
x or y is True
not x is False
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Here, we see that x1 and y1 are integers of same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).But x3 and y3 are list.
They are equal but not identical. Since list are mutable (can be changed), interpreter
locates them separately in memory although they are equal.
2.7.6.2 Membership Operators
in and not in are the membership operators in Python. They are used to
test whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).
Operator Meaning Example
Example
But we can change this order using parentheses () as it has higher precedence.
>>> (20-5)*3
45
Operators Meaning
() Parentheses
**` Exponent
+, - Addition, Subtraction
Data, Expressions Statements 2.23
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=,
Comparisions, Identity, Membership operators
is, is not, in, not in
not Logical NOT
or Logical OR
Table 2.10: Operator precedence rule in Python
2. 10 Tuple Assignment
It is often useful to swap the values of two variables. With conventional
assignments, you have to use a temporary variable. For example, to swap a and b:
>>>temp=a
>>> a=b
>>>b=temp
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. The number of variables on
the left and the number of values on the right have to be the same:
>>>a,b =1,2, 3
ValueError:too manyvalues to unpack
More generally, the right side can be any kind of sequence (string, list or
tuple). For example, to split an email address into a user name and a domain,
you could write:
Data, Expressions Statements 2.25
>>>addr=’[email protected]’
>>>uname,domain=addr.split(‘@’)
The return value from split is a list with two elements; the first element is
assigned to
>>>uname’monty’
>>>domain’
python.org’
2. 11 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
Heightarea=(base*height)/2
In this case,the comment appears on a line by itself. You can also put comments
at the end of a line:
area=(base*height)/2#AreaofatriangleusingBase andHeight
Everythingfromthe#totheendofthelineisignored—ithasnoeffectonthe
execution of the program. Comments are most useful when they document non-
obviousfeaturesoft the code. It is reasonable to assume that the reader can figure
out what the code does; it is more useful to explain why.
This comment is redundant with the code and useless:
base= 5 # assign 5 to base
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:
2. 26 Problem Solving and Python Programming
Thisisalongcomment#and it extends
#tomultiplelines
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”””
The name of the function is type. The expression in parentheses is called the
argument of the function. The result, for this function, is the type of the argument.
It is common to say that a function - take - an argument and- returns - a result. The
result is also called the return value.
Python provides functions that convert values from one type to another. The
intfunctiontakes any value and converts it to an integer, if it can, or complains
otherwise:
>>>int(‘25’) 25
>>>int(‘Python’)
ValueError: invalid literal for int(): Python
int can convert floating-point values to integers, but it doesn‘t round off; it
chops off the fraction part:
>>>int(9.999999)9
>>>int(-2.3)
-2
>>>float(25)25.0
>>>float(‘3.14159’)3.14159
2.12.1.1.1.range() – function
The range() constructor returns an immutable sequence object of integers
between the given start integer to the stop integer.
Python’s range() Parameters
The range() function has two sets of parameters, as follows:
range(stop)
stop: Number of integers (whole numbers) to generate, starting from zero.
eg. range(3)= [0, 1, 2].
range([start], stop[, step])
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.
Note that:
All parameters must be integers.
All parameters can be positive or negative.
>>>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]
Example .
>>> x=10
>>> y=7
>>>print(‘The sum of’, x, ‘plus’, y, ‘is’, x+y)
The sum of 10 plus 7 is 17
This prompts you to enter any string and it would display same string on the
screen.
2. 30 Problem Solving and Python Programming
Example of a function
def welcome(person_name): “””
This function welcomethe person passed in as parameter”””
print(“ Welcome “ , person_name , “ to Python Function Section”)
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 absolutevalue of the entered number”””
ifnum>= 0:
returnnum
else:
return -num
print(absolute_value(5))
print(absolute_value(-7))
Flow of Execution
To ensure that a function is defined before its first use, you have to know the
order statements run in, which is called the flow of execution. Execution always
begins at the first statement of the program. Statements are run 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 don‘t run until the
function is called. A function call is like a detour in the flow of execution. Instead
of going to the next statement, the flow jumps to the body of the function, runs the
statements there, and then comes back to pick up where it left off. Figure 2.3 show
the flow of execution
2.12.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:
>>>importmath
This statement creates a module object named math. If you display the
module object, you get some information about it:
>>>math
<module ‘math’ (built-in)>
2. 34 Problem Solving and Python Programming
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.
Example
>>>importmath
>>>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)
Helponbuilt-infunction powinmodulebuiltin:
pow(...)
pow(x, y[,z])->number
If you run this program, it will add 10 and 20 and print 30. We can import it
like this:
>>>importaddModule
30
270
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.
defadd(a,b):
result=a+bprint(result)
ifname_==
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
2. 36 Problem Solving and Python Programming
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.
2. 13Illustrative Programs
2.13.1 Exchange the Value of two Variables
In python exchange of values of two variables (swapping) can be done in
different ways
££ Using Third Variable
££ Without Using Third Variable
££ Using Tuple Assignment method
££ Using Arithmetic operators
££ Using Bitwise operators
In the above program line number 3,4,5, are used to swap the values of two
variables. In this program, we use the temp variable to temporarily hold the value
of var1. We then put the value of var2 in var1 and later temp in var2. In this way,
the values get exchanged. In this method we are using one more variable other than
var1,var2. So we calling it as swapping with the use of third variable.
3.13.1.2 Without Using Third Variable
We can do the same swapping operation even without the use of third variable,
There are number of ways to do this, they are.
2.13.1.2.1 Using Tuple Assignment method
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.
Data, Expressions Statements 2.37
2. 1 With Answers
Two Marks Questions
1. Define python
Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
2. Give the features of python.
££ Easy to Use:
££ Expressive Language
££ Interpreted Language
££ Cross-platform language
££ Free and Open Source
££ Object-Oriented language
££ Extensible
3. What is python interpreter?
The engine that translates and runs Python is called the Python Interpreter:
There are two ways to use it: immediate mode and script mode. The >>> is
called the Python prompt. The interpreter uses the prompt to indicate that it
is ready for instructions.
4. What is the difference between intermediate mode and script mode?
££ In immediate mode, you type Python expressions into the Python
Interpreter window, and the interpreter immediately shows the result.
££ Alternatively, you can write a program in a file and use the interpreter to
execute the contents of the file. Such a file is called a script. Scripts have
the advantage that they can be saved to disk, printed, and so on.
5. What is meant by value in python?
A value is one of the fundamental things—like a letter or a number—that a
program manipulates.
6. List the standard data types in python.
Python has five standard data
Types:
££ Numbers ££ List, ££ Dictionary
££ Strings ££ Tuples
2. 40 Problem Solving and Python Programming
10. What is tuple ? What is the difference between list and tuple?
A tuple is another sequence data type that is similar to the list. A tuple consists
of a number of values separated by commas.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of
as read-only lists.
Eg: tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )
11. Give the features of python dictionaries
Python’s dictionaries are kind of hash table type. They work like associative
arrays and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand,
can be any arbitrary Python object.Dictionaries are enclosed by curly braces ({
}) and values can be assigned and accessed using square braces ([]).
For example – dict = {}
dict[‘one’] = “This is one”
12. What is a variable?
One of the most powerful features of a programming language is the ability
to manipulate variables. A variable is a name that refers to a value. The
assignment statement gives a value to a variable.
Eg :
>>> n = 17
>>> pi = 3.14159
13. What are the rules for naming a variable?
Variable names can be arbitrarily long. They can contain both letters and
digits, but they have to begin with a letter or an underscore. Although it is
legal to use uppercase letters, by convention we don‘t. If you do, remember that
case matters.
Bruce and bruce are different variables.
The underscore character ( _) can appear in a name. Eg:
my_name
14. What are keywords?
Keywords are the reserved words in Python. We cannot use a keyword as
2. 42 Problem Solving and Python Programming
2. 14
variable name, function name or any other identifier. They are used to define
the syntax and structure of the Python language In Python, keywords are case
sensitive. There are 33 keywords in Python.
Eg
False, class, finally, return
15. What are the rules for writing an identifier?
££ Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_1
and print_this_to_screen, all are valid example.
££ An identifier cannot start with a digit. 1variable is invalid, but variable1
is perfectly fine. Keywords cannot be used as identifiers.
££ We cannot use special symbols like !, @, #, $, % etc. in our
££ identifier. Identifier can be of any length.
16. what are expressions?
An expression is a combination of values, variables, operators, and calls
to functions. If you type an expression at the Python prompt, the interpreter
evaluates it and displays the result:
>>> 1 + 1=2
17. What is a statement?
A statement is an instruction that the Python interpreter can execute. When
you type a statement on the command line, Python executes it. Statements
don‘t produce any result. For example, a = 1 is an assignment statement. if
statement, for statement, while statement etc. are other kinds of statements.
18. What is multiline 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
Data, Expressions Statements 2.43
2. 2
Review Questions
1. Explain the data types in python
2. Ilustrate interpreter and interactive mode in python with example. 3.Explain
Data, Expressions Statements 2.45