python part 1
python part 1
PYTHON PROGRAMMING
[R17A0554]
LECTURE NOTES
B.TECH III YEAR – II SEM (R17)
(2019-20)
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
PYTHON PROGRAMMING III YEAR/II SEM MRCET
SYLLABUS
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
UNIT II
CONTROL FLOW, LOOPS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional
(if-elif-else); Iteration: while, for, break, continue.
UNIT III
FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function composition,
recursion; Strings: string slices, immutability, string functions and methods, string module; Python
arrays, Access the Elements of an Array, array methods.
UNIT IV
LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple comprehension;
Dictionaries: operations and methods, comprehension;
UNIT V
FILES, EXCEPTIONS, MODULES, PACKAGES
Files and exception: text files, reading and writing files, command line arguments, errors and
exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module), Explore
packages.
PYTHON PROGRAMMING III YEAR/II SEM MRCET
OUTCOMES: Upon completion of the course, students will be able to
Read, write, execute by hand simple Python programs.
Structure simple Python programs for solving problems.
Decompose a Python program into functions.
Represent compound data using Python lists, tuples, dictionaries.
Read and write data from/to files in Python Programs
TEXT BOOKS
1.Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016.
2.R. Nageswara Rao, “Core Python Programming”, dreamtech
3. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
REFERENCE BOOKS:
1. Core Python Programming, W.Chun, Pearson.
2. Introduction to Python, Kenneth A. Lambert, Cengage
3. Learning Python, Mark Lutz, Orielly
PYTHON PROGRAMMING III YEAR/II SEM MRCET
INDEX
UNIT TOPIC PAGE NO
INTRODUCTION DATA,
EXPRESSIONS, STATEMENTS
1
Introduction to Python and installation 1
data types: Int 6
float 7
Boolean 8
string 8
List 10
I variables 11
expressions 13
statements 16
precedence of operators 17
comments 18
modules 19
functions ---- function and its use 20
flow of execution 21
parameters and arguments 26
CONTROL FLOW, LOOPS 35
Conditionals: Boolean values and 35
operators,
II conditional (if) 36
alternative (if-else) 37
chained conditional (if-elif-else) 39
Iteration: while, for, break, continue. 41
FUNCTIONS, ARRAYS 55
Fruitful functions: return values 55
parameters 57
local and global scope 59
function composition 62
III recursion 63
Strings: string slices 64
immutability 66
string functions and methods 67
string module 72
Python arrays 73
Access the Elements of an Array 75
Array methods 76
PYTHON PROGRAMMING III YEAR/II SEM MRCET
LISTS, TUPLES, DICTIONARIES 78
Lists 78
list operations 79
list slices 80
list methods 81
list loop 83
mutability 85
aliasing 87
IV cloning lists 88
list parameters 89
list comprehension 90
Tuples 91
tuple assignment 94
tuple as return value 95
tuple comprehension 96
Dictionaries 97
operations and methods 97
comprehension 102
V FILES, EXCEPTIONS, 103
MODULES, PACKAGES
Files and exception: text files 103
reading and writing files 104
command line arguments 109
errors and exceptions 112
handling exceptions 114
modules (datetime, time, OS , calendar, 121
math module)
Explore packages 134
PYTHON PROGRAMMING III YEAR/II SEM MRCET
UNIT – I
Introduction to Python and installation, data types: Int, float, Boolean, string, and list;
variables, expressions, statements, precedence of operators, comments; modules, functions--
- function and its use, flow of execution, parameters and arguments.
Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions- Python 2 and Python 3.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
# Script Begins
Statement1
1
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Statement2
Statement3
# Script Ends
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python
2
PYTHON PROGRAMMING III YEAR/II SEM MRCET
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
5. It’s Portable
Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
3
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.
PVM
m.py m.pyc
4
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.
hello world
>>> x=[0,1,2]
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter
replies 8.
5
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Alternatively, programmers can store Python script source code in a file with
the .py extension, and use the interpreter to execute the contents of the file. To execute the
script by the interpreter, you have to tell the interpreter the name of the file. For example, if
you have a script name MyFile.py and you're working on Unix, to run the script you have to
type:
python MyFile.py
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute them immediately, but when the code is more
than 2-4 lines, using the script for coding can help to modify and use the code in future.
Example:
Data types:
The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and
the storage method for each of them.
Int:
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
6
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
7
PYTHON PROGRAMMING III YEAR/II SEM MRCET
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
• Strings can be output to screen using the print function. For example: print("hello").
mrcet college
<class 'str'>
8
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> print('mrcet college')
mrcet college
''
If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:
Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
quote character:
The following is a table of escape sequences which cause Python to suppress the usual
special interpretation of a character in a string:
>>> print('a\
....b')
a....b
>>> print('a\
b\
c')
9
PYTHON PROGRAMMING III YEAR/II SEM MRCET
abc
>>> print('a \n b')
a
b
>>> print("mrcet \n college")
mrcet
college
In Python (and almost all other common computer languages), a tab character can be
specified by the escape sequence \t:
>>> print("a\tb")
a b
List:
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
10
PYTHON PROGRAMMING III YEAR/II SEM MRCET
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:
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.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different 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.
11
PYTHON PROGRAMMING III YEAR/II SEM MRCET
For example −
c = "John" # A string
print (a)
print (b)
print (c)
100
1000.0
John
Multiple Assignment:
For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example −
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
Variables do not need to be declared with any particular type and can even change type after
they have been set.
12
PYTHON PROGRAMMING III YEAR/II SEM MRCET
x=5 # x is of type int
x = "mrcet " # x is now of type str
print(x)
Output: mrcet
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Expressions:
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
13
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
>>> y=20
>>> y
20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is
an identifier.
Literals: These are language-independent terms in Python and should exist independently in
any programming language. In Python, there are the string literals, byte literals, integer
literals, floating point literals, and imaginary literals.
Operators: In Python you can implement the following operations using the corresponding
tokens.
14
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Operator Token
add +
subtract -
multiply *
Integer Division /
remainder %
and &
or \
Check equality ==
15