Python Notes 1-5 Detail_removed
Python Notes 1-5 Detail_removed
Programming language:
Python
Interpreter
Interpreter is a computer program that facilitates developer to run the source code
of particular language. The code directly runs on machine without any prior
arrangement like compiler.
Interpreter vs Compiler
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates it
time. as a whole into machine code.
It takes less amount of time to analyze It takes large amount of time to analyze
the source code but the overall the source code but the overall execution
execution time is slower. time is comparatively faster.
No intermediate object code is Generates intermediate object code
generated, hence are memory efficient. which further requires linking, hence
requires more memory.
Continues translating the program until It generates the error message only after
the first error is met, in which case it scanning the whole program. Hence
stops. Hence debugging is easy. debugging is comparatively hard.
Programming language like Python, Programming language like C, C++ use
Ruby use interpreters. compilers.
Story of python
Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68,SmallTalk and Unix shell and other scripting languages. Python is
copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL). Python is now maintained by a core development
team at the institute, although Guido van Rossum still holds a vital role in directing
its progress.
Python
Source code Interpreter Output
Interactive program
We execute Python from the command line with no script (no arguments), Python
gives you an interactive prompt. This is an excellent facility for learning Python
and for trying small snippets of code. Many of the examples that follow were
developed using the Python interactive prompt.
Start the Python interactive interpreter by typing python with no arguments at the
command line.
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is
no longer active.
Let us write a simple Python program in a script. All python files will have
extension .py. So put the following source code in a test.py file.
Here, Assumed that Python interpreter set in PATH variable. Now, run this
program as follows:
Python Identifiers
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Starting an identifier with a single leading underscore indicates that the
identifier is private.
• Starting an identifier with two leading underscores indicates a strongly
private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a
language-defined• special name.
Reserved Keywords:
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only.
Values And Types
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong
todifferentdatatypes.)
Data type:
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand. Python
has a number of operators which are classified below.
• Arithmetic operators
• Comparison (Relational) operators
• Logical (Boolean) operators
• Bitwise operators
• Assignment operators
• Special operators
Arithmetic operators
Comparison operators
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates
bit by bit, hence the name.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
Assignment operators
Special operators
Python language offers some special type of operators like the identity
operator or the membership operator. They are described below with examples.
Identity operators
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.
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).In a dictionary we can only test for presence of key, not the value.
➢ Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is
5, not 4, and 6+4/2 is 8, not 5.
➢ Operators with the same precedence are evaluated from left to right (except
exponentiation). So in the expression degrees / 2 * pi, the division happens first
and the result is multiplied by pi. To divide by 2π, you can use parentheses or
write degrees / 2 / pi.
Comment
In Python there are basically two ways to comment: Single line and
Multiple line. Single line commenting is good for a short, quick comment (or for
debugging), while the block comment is often used to describe something much
more in detail or to block out an entire chunk of code.
print("Not a comment")
#print("Am a comment")Result
output :
Not a comment
'''
print("We are in a comment")
print ("We are still in a comment")
'''
print("We are out of the comment")
Output
Expressions
5+4
Area=L*B
x + 17
Expressions need to be evaluated. If you ask Python to print an expression,
the interpreter evaluates the expression and displays the result.
The evaluation of an expression produces a value, which is why
expressions can appear on the right hand side of assignment statements.
Statements
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 various standard data types that are used to define the
operations possible on them and the storage method for each of them.
• Numbers
• String
• List
• Tuple
• Dictionary
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
➢ int (signed integers) − They are often called just integers or ints. They are
positive or negative whole numbers with no decimal point. Integers in Python 3
are of unlimited size. Python 2 has two integer types - int and long. There is no
'long integer' in Python 3 anymore.
➢ float (floating point real values) − Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and the
fractional parts. Floats may also be in scientific notation, with E or e indicating
the power of 10 (2.5e2 = 2.5 x 102 = 250).
➢ complex (complex numbers) − are of the form a + bJ, where a and b are floats
and J (or j) represents the square root of -1 (which is an imaginary number).
The real part of the number is a, and the imaginary part is b. Complex numbers
are not used much in Python programming.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator.
Python Lists
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
This produces the following result
Boolean
Booleans are either true or false. Python has two constants, cleverly named
True and False, which can be used to assign booleanvalues directly. Expressions
can also evaluate to a boolean value.
A tuple is a sequence of values. The values can be any type, and they are
indexed by integers, so in that respect tuples are a lot like lists. The main difference
between lists and tuples are, Lists are enclosed in square 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.
For example
Modules
Import Modules
This does not enter the names of the functions defined in example directly in
the current symbol table. It only enters the module name example there.
Using the module name we can access the function using dot (.) operation. For
example:
There are various ways to import modules. They are listed as follows.
We can import a module using import statement and access the definitions
inside it using the dot operator as described above. Here is an example.
When you run the program, the output will be :
We have renamed the math module as m. This can save us typing time in
some cases. Note that the name math is not recognized in our scope. Hence,
math.pi is invalid, m.piis the correct implementation.
We can import specific names from a module without importing the module
as a whole. Here is an example.
Output:
We imported only the attribute pi form the module.In such case we don't use
the dot operator. We could have imported multiple attributes as follows.
We can import all names (definitions) from a module using the following
construct.
We imported all the definitions from the math module. This makes all names
except those beginning with an underscore, visible in our scope. Importing
everything with the asterisk (*) symbol is not a good programming practice. This
can lead to duplicate definitions for an identifier. It also hampers the readability of
our code.
Python Functions
Syntax of Function
Above shown is a function definition which consists of following components.
Example of a function
Function Call
The return statement is used to exit a function and go back to the place from
where it was called.
Syntax of return:
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.
Example of return
Output:
FLOW OF EXECUTION
When we are working with functions it is really important to know the order
in which statements are executed. This is called the flow of execution
Execution always begins at the first statement of the program. Statements
are executed 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 are not executed until the function is called. Function calls are like a
detour in the flow of execution. Instead of going to the next statement, the flow
jumps to the first line of the called function, executes all the statements there, and
then comes back to pick up where it left off. It is shown pictorially below.
Consider the following Python code.
(A) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
(B) 1, 2, 3, 5, 6, 7, 9, 10, 11
(C) 9, 10, 11, 1, 2, 3, 5, 6, 7
(D) 9, 10, 5, 6, 7, 1, 2, 3, 11
(E)1, 5, 9, 10, 6, 2, 3, 7, 11
Python starts at line 1, notices that it is a function definition and skips over
all of the lines in the function definition until it finds a line that it no longer
included in the function (line 5).
It then notices line 5 is also a function definition and again skips over the
function body to line 9.
On line 10 it notices it has a function to execute, so it goes back and
executes the body of that function. Notice that that function includes another
function call. Finally, it will return to line 11 after the function square is complete.
Arguments
Arguments are part of a function call. There are four different kinds of
arguments:
Positional: Arguments without a name or is not followed by an equal sign (=) and
default value.
In the above code the first argument in the function call is equal to an
expression and the second argument contains a default value.
They perform an operation called 'packing'. True to it's name, what this does
is pack all the arguments that this method call receives into one single variable, a
tuple called args. You can use any variable name you want, of course, but args
seems to be the most common and Pythonic way of doing things.
The * operator can be used in the context of a method call. What it does now
is explode the args array and call the method as if you'd typed in each variable
separately.
Parameters
Parameters are part of a function definition. There are four different kinds of
parameters:
Here in the above program the various positional argument from the function
call is been packed into a tuple in the function definition.
ILLUSTRATIVE PROGRAMS
Output
C) Create a Python program to circulate the values of n variables. Try it using all
the concepts learnt as of now.
Question Bank
In python list is an ordered sequence of items. Items can be any type and it is
separated by comas. List is flexible data type. We can add and remove items
any time. List are inerrable it is access based on index value. Lists are
mutable.
The name that mentions the value is called variable. It is a specific location
in the memory where certain value or data stored. Variable names should be
unique. Each variables holds separate memory location.
Rules for usage of variable names:
1. Name may contain letters, numbers and underscore.
2. It must start with letter.
3. Special characters (@,$,#...etc) not allowed.
4. Variable names are case sensitive.
8. Write a program that receives two numbers from the user and find
which one is great?
• Simple
• Open source
• High-level
• Portable
• Object Oriented
• Interpreted
• Easy to maintain
• Scalable
• Arithmetic Operators
• Relational Operators
• Logical/Boolean Operators
• Bitwise Operator
• Assignment Operators
• Membership Operators
• Identity Operators
14.Define functions.
Functions are the block of reusable code that can be used to perform one or
more related operations. It ensures the modularity and reusability of the
program. Functions can be used anywhere and anytime within the program.
There are two types of functions [1. Built-in functions, User defined
functions].
• Based on Parameters
o Functions without parameters.
o Function with parameters.
• Based on arguments
o Default arguments.
o Keyword arguments.
o Arbitrary arguments.
The file in which the python code and function definitions are saved is
referred to as modules. Files are saved with extension (.py). Modules can be
imported in scripts.
a = 10
b = 20
print (“Before Swapping”)
print (“A is”, a, ”B is”, b)
temp = a
a=b
b = temp
print (“After Swapping”)
print (“A is”, a, ”B is”, b)
PART – B
BOOLEAN VALUES:
Boolean:
Boolean data type have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keyword.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic operators:
Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Membership Operators:
Evaluates to find a valueor a variable is in the specified sequence of string, list,
tuple, dictionary or not.
To check particular element is available in the list or not.
Operators are in and not in.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same part of
the memory.
Example
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True
CONDITIONALS
Conditional if
Alternative execution- if… else
Chained if…elif…else
Nested if….else
Inline if
Conditional (if):
Conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:
Flowchart:
Example:
1. Program to provide flat rs 500, if the purchase amount is greater than 2000.
2. Program to provide bonus mark if the category is sports.
Program to provide flat rs 500, if the purchase amount output
is greater than 2000.
purchase=eval(input(“enter your purchase amount”)) enter your purchase
if(purchase>=2000): amount
purchase=purchase-500 2500
print(“amount to pay”,purchase) amount to pay
2000
Program to provide bonus mark if the category is output
sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting
Odd or even number Output
n=eval(input("enter a number")) enter a number4
if(n%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
leap year or not Output
y=eval(input("enter a yaer")) enter a yaer2000
if(y%4==0): leap year
print("leap year")
else:
print("not leap year")
The if block can have only one else block. But it can have multiple elif blocks.
The way to express a computation like that is a chained conditional.
syntax:
Flowchart:
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
Syntax:
Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Inline if:
An inline if statement is a simpler form of if statement and is more convenient ,if we
need to perform simple task.
Example:
>>> b=True
>>> a=1 if b else None
>>> a
1
>>> b=False
>>> a=1 if b else None
>>> a
#None
ITERATION/CONTROL
STATEMENTS/LOOPs:
state
while
for
break
continue
pass
State:
Transition from one process to another process under specified condition with in a
time is called state.
While loop:
While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true.
In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression is True. After one iteration, the test
expression is checked again. This process continues until the test_expression
evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while starts with indentation and the first
unindented line marks the end.
Syntax:
Flowchart:
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
sum=sum+a
n=n//10
print(sum)
For loop:
for in range:
We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.
syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9
for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1
Examples:
1. print nos divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
Flowchart
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in
the loop.
Syntax: Continue
Flowchart
Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
It is used
when a statement is required syntactically but you don’t want any code to
execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
Fruitful Function
Fruitful function
Void function
Return values
Parameters
Local and global scope
Function composition
Recursion
Fruitful function:
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS:
Parameters are the variables which used in the function definition. Parameters
are
inputs to functions. Parameter receives the input from the function call.
It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with
number of arguments in the function call.
Example Output:
def student( name, roll ): George 98
print(name,roll)
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword parameter, the
order of the arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")
Default parameter:
Python allows function parameter to have default values; if the function is called
without the argument, the argument gets its default value in function definition.
Example Output:
def student( name, age=17): Kumar 17
print (name, age)
Ajay 17
student( “kumar”):
student( “ajay”):
Sometimes, we do not know in advance the number of arguments that will be
passed into a function.
Python allows us to handle
this kind of situation through function calls with
number of arguments.
In the function definition we use an asterisk(*) before the parameter name to
denote this is variable length of parameter.
Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name,mark)
student (“bala”,102,90)
Example: Output:
math.sqrt(math.log(10))
def add(a,b): 900
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)
Strings:
String is defined as sequence of characters represented in quotation marks
(either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative).
A index starts from 0 to n-1.
Strings are
immutable i.e. the contents of the string cannot be changed after it is
created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can be treated as
characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
>>>a=”HELLO” Positive indexing helps in accessing
indexing >>>print(a[0]) the string from the beginning
>>>H Negative subscript helps in accessing
>>>print(a[-1]) the string from the end.
>>>O
Print[0:4] – HELL The Slice[start : stop] operator extracts
Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
Stringname.method()
a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
14 a.isalnum() >>> a.isalnum() checks whether the string
False consists of alphanumeric
characters.
15 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.
16 a.isspace() >>> a.isspace() checks whether the string
False consists of whitespace only.
17 a.istitle() >>> a.istitle() checks whether string is title
False cased.
18 a.startswith(substring) >>> a.startswith("h") checks whether string starts
True with substring
19 a.endswith(substring) >>> a.endswith("y") checks whether the string
True ends with the substring
20 a.find(substring) >>> a.find("happy") returns index of substring, if
0 it is found. Otherwise -1 is
returned.
21 len(a) >>>len(a) Return the length of the
>>>14 string
22 min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
23 max(a) max(a) Return the maximum
>>>’y’ character in the string
String modules:
A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import
a module, we can reference or use to any of its functions or variables in
our code.
There is large number of standard modules also available in python.
Standardmodules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
Escape sequences in string
Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"")
(") "
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)
List as array:
Array:
Array is a collection of similar elements. Elements in the array can be accessed
by index. Index starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype
Example
Program to find sum of Output
array elements
import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Convert list into array:
fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
arrayname.fromlist(list_name)
Example
program to convert list Output
into array
import array 35
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Function:
Lambda function (Anonymous Functions)
A function is said to be anonymous function when it is defined without a
name and def keyword.
In python, normal function are defined using def keyword and
Anonymous function are defined using lambda keyword.
Lambda function can have any number of argument but only one
expression.The expression are evaluated and returned.
Example:
>>> a=lambda b: b*2+b
>>> print(a(3))
9
Or
def a(b):
return b*2+b
Part A:
1. What are Boolean values?
2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. define state
7. Write the syntax for while loop with flowchart.
8. Write the syntax for for loopwith flowchart.
9. Differentiate break and continue.
10. mention the use of pass
11. what is fruitful function
12. what is void function
13. mention the different ways of writing return statement
14. What is parameter and list down its type?
15. What is local and global scope?
16. Differentiate local and global variable?
17. What is function composition, give an example?
18. Define recursion.
19. Differentiate iteration and recursion.
20. Define string. How to get a string at run time.
>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
List slices:
List slicing is an operation
that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
default start value is 0
default stop value is n-1
[:] this will print the entire list
[2:2] this will create a empty slice
List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)
>>>a=[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 a.pop() >>> a.pop() Removes and
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1] returns an element
at the last element
8 a.pop(index) >>> a.pop(0) Remove the
8
>>>print(a)
[7, 6, 5, 4, 3, 2, 1, 0] particular element
and return it.
>>>a=[7, 6, 5, 4, 3, 2, 1]
9 a.remove(element) >>> a.remove(1) Removes an item
>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6]
10 a.count(element) >>> a.count(6) Returns the count of
2 number of items
passed as an
argument
>>>a=[7, 6, 5, 4, 3, 2]
11 a.copy() >>> b=a.copy() Returns a
>>> print(b) copy of the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
6 the length
>>>a=[7, 6, 5, 4, 3, 2]
17 sum(list) >>> sum(a) return the sum of
27 element in a list
14 max(list) >>> max(a) return the maximum
element in a list.
7
15 a.clear() >>> a.clear() Removes all items
>>> print(a) from the list.
[]
16 del(a) >>> del(a) delete the entire list.
>>> print(a)
Error: name 'a' is not
defined
List loops:
1. For loop
2. While loop
3. Infinite loop
List using For Loop:
The for loop in Python
is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
Iterating over a sequence is called traversal.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code using indentation.
Syntax:
for val in sequence:
Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16
Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without entirely
recreating it.
An item canbe changed in a list by accessing it directly as part of the assignment
statement.
Using the indexing operator (square brackets[ ]) on the left side of an assignment,
one of the list items can be updated.
Example description
changing single element
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing multiple element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]
Aliasing(copying):
Creating a copy of a list is called aliasing.
When
you create a copy both the list will be having same memory location.
changes in one list will affect another list.
Alaising refers to having different names for same list values.
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]
In this a single list object is created and modified using the subscript operator.
When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced.
This type of change is what is known as a side effect. This happens because
the assignment b=a, the variables a and b refer to the exact same list object.
after
They are aliases for the same object. This phenomenon is known as aliasing.
To prevent aliasing, a new object can be
created and the contents of the original
can be copied which is called cloning.
Clonning:
To avoid the disadvantages of copying we are using cloning.
Creating a copy of a same list of elements with two different memory locations is called cloning.
Changes in one list will not affect locations of aother list.
Cloning is a process of making a copy of the list without modifying the original list.
1. Slicing
2. list()method
3. copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
List as parameters:
In python, arguments are passed by reference.
If any changes are done in the parameter which refers within the function, then the
changes also reflects back in the calling function.
When a list to a function is passed, the function gets a reference to the list.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example 1`: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Example 2: Output
def inside(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Example 3 output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Tuple:
A tuple is same as list,
except that the set of elements is enclosed in parentheses instead
of square brackets.
A tuple is an immutable list. i.e. once a tuplehas been created, you can't add elements to
a tuple or remove elements from the tuple.
But tuple can be converted into list and list can be converted in to tuple.
Tuple Assignment:
Tuple assignment allows, variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.
Multiple assignment works by creating a tuple of expressions from the right hand
side, and
target.
a tuple of targets from the left, and then matching each expression to a
Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')
Dictionaries:
Dictionary is an unordered collection of elements. An element in dictionary has a key:
value pair.
All elements in dictionary are placed inside the curly braces i.e. { }
Elements in Dictionaries are accessed via keys and not by their position.
The values of a dictionary can be any data type.
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Operations Example Description
Methods in dictionary:
Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)
def divide(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = divide(x[:middle])
b = divide(x[middle:])
return merge(a,b)
x=[38,27,43,3,9,82,10]
c=divide(x)
print(c)
Histogram Output
def histogram(a): ****
for i in a: *****
sum = '' *******
while(i>0): ********
sum=sum+'#' ************
i=i-1
print(sum)
a=[4,5,7,8,12]
histogram(a)
Calendar program Output
import calendar enter year:2017
y=int(input("enter year:")) enter month:11
m=int(input("enter month:")) November 2017
print(calendar.month(y,m)) Mo Tu We Th Fr Sa Su
12345
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
PART - A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[‘p’,’r’,’i’,’n’,’t’,]
b. Print list[8:]
4. Give the syntax required to convert an integer number into string?
5. List is mutable. Justify?
6. Difference between del and remove methods in List?
7. Difference between pop and remove in list?
8. How are the values in a tuple accessed?
9. What is a Dictionary in Python
10. Define list comprehension
11. Write a python program using list looping
12. What do you meant by mutability and immutability?
13. Define Histogram
14. Define Tuple and show it is immutable with an example.
15. state the difference between aliasing and cloning in list
16. what is list cloning
17. what is deep cloning
18. state the difference between pop and remove method in list
19. create tuple with single element
20. swap two numbers without using third variable
21. define properties of key in dictionary
22. how can you access elements from the dictionary
23. difference between delete and clear method in dictionary
24. What is squeezing in list? give an example
25. How to convert a tuple in to list
26. How to convert a list in to tuple
27. Create a list using list comprehension
28. Advantage of list comprehension
29. What is the use of map () function.
30. How can you return multiple values from function?
31. what is sorting and types of sorting
32. Find length of sequence without using library function.
33. how to pass tuple as argument
34. how to pass a list as argument
35. what is parameter and types of parameter
36. how can you insert values in to dictionary
37. what is key value pair
38. mention different data types can be used in key and value
39. what are the immutable data types available in python
40. What is the use of fromkeys() in dictioanary.
PART-B
1. Explain in details about list methods
2. Discuss about operations in list
3. What is cloning? Explain it with example
4. What is aliasing? Explain with example
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples
7. write a program for matrix multiplication
8. write a program for matrix addition
9. write a program for matrix subtraction
10. write a program for matrix transpose
11. write procedure for selection sort
12. explain merge sort with an example
13. explain insertion with example
14. Explain in detail about dictionaries and its methods.
15. Explain in detail about advanced list processing.
UNIT V FILES, MODULES, PACKAGES
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
programs: word count, copy file.
FILES
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is
turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied with the file are freed. Hence, in Python, a
file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a file
Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read
'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode
or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing
with non-text files like image or exe files.
Hence, when working with files in text mode, it is highly recommended to specify the
encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')
Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done using the
close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file
operations f.close()
This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file. A safer way is to use a
try...finally block.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when
the block inside with is exited.
We don't need to explicitly call the close() method. It is done internally.
with open("test.txt",encoding = 'utf-8') as f:
# perform file operations
If the file already exists, opening it in write mode clears out the old data and starts
fresh, so be careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n"
>>> fout.write(line1)
2
Again, the file object keeps track of where it is, so if you call write again, it adds the new data
to the end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()
Format operator
The argument of write has to be a string, so if we want to put other values in a file, we have
to convert them to strings. The easiest way to do that is with str:
>>> x = 52
>>> fout.write(str(x))
An alternative is to use the format operator, %. When applied to integers, % is the modulus
operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences, which
specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be formatted as
an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value in a
sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' %
camels 'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has to be a tuple.
Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point number
and '%s' to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple has to match the number of format sequences in
the string. Also, the types of the elements have to match the format sequences:
cwd stands for “current working directory.” The result in this example is /home/dinsdale,
which is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative to the current
directory. To find the absolute path to a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
To demonstrate these functions, the following example “walks” through a directory, prints
the names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print path
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.
EXCEPTION
Python (interpreter) raises exceptions when it encounters errors. Error caused by not
following the proper structure (syntax) of the language is called syntax error or parsing error.
>>> if a < 3
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax
Errors can also occur at runtime and these are called exceptions. They occur, for example,
when a file we try to open does not exist (FileNotFoundError), dividing a number by zero
(ZeroDivisionError), module we try to import is not found (ImportError) etc.
Whenever these type of runtime error occur, Python creates an exception object. If not
handled properly, it prints a traceback to that error along with some details about why that
error occurred.
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
>>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
6
Python Exception Handling
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it to the calling
process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and an exception
occurs in function C. If it is not handled in C, the exception passes to B and then to A.
If never handled, an error message is spit out and our program come to a sudden, unexpected
halt.
randomList = ['a', 0, 2]
The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
In this program, we loop until the user enters an integer that has a valid reciprocal. The
portion that can cause exception is placed inside try block.
7
If no exception occurs, except block is skipped and normal flow continues. But if any
exception occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function inside sys module and ask
the user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes
ZeroDivisionError.
try...finally
The try statement in Python can have an optional finally clause. This clause is
executed no matter what, and is generally used to release external resources.
For example, we may be connected to a remote data center through the network or working
with a file or working with a Graphical User Interface (GUI).
In all these circumstances, we must clean up the resource once used, whether it was
successful or not. These actions (closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee execution. Here is an example of file operations
to illustrate this.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
MODULES
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named wc.py with the following code:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the file, which is 7.
You can also import it like this:
>>> import wc
7
Now you have a module object wc:
>>> print wc
<module 'wc' from 'wc.py'>
>>> wc.linecount('wc.py')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it executes the
test code at the bottom. Normally when you import a module, it defines new functions
but it doesn’t execute them.
Programs that will be imported as modules often use the following
idiom: if __name__ == '__main__':
8
print linecount('wc.py')
__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 is
executed. Otherwise, if the module is being imported, the test code is skipped. Eg:
# import module
import calendar
yy = 2017
mm = 8
PACKAGE
A package is a collection of modules. A Python package can have sub-packages and
modules.
A directory must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
package in this file.
Here is an example. Suppose we are developing a game, one possible organization of
packages and modules could be as shown in the figure below.
If this construct seems lengthy, we can import the module without the package prefix as follows.
from Game.Level import start
Yet another way of importing just the required function (or class or variable) form a module
within a package would be as follows.
from Game.Level.start import select_difficulty
Although easier, this method is not recommended. Using the full namespace avoids confusion
and prevents two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path, similar as
for module search path.
ILLUSTRATION PROGRAM
Word Count of a file:
import sys
fname=sys.argv[1]
n=0
with open(fname,'r') as f:
for line in f:
words=line.split()
n+=len(words)
print("Number of words:",n)
Copy file:
f1=open(“sourcefile.txt”,”r”)
f2=open(“destinationfile.txt”,”w”)
for line in f1:
f2.write(“\n”+line)
f1.close( )
f2.close( )
print(“Content of Source file:”)
f1=open(“sourcefile.txt”,”r”)
print(f1.read( ))
print(“Content of Copied file:”)
f2=open(“destinationfile.txt”,”r”)
print(f2.read( ))