Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Python Notes 1-5 Detail_removed

Uploaded by

abhaysinghverma7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Notes 1-5 Detail_removed

Uploaded by

abhaysinghverma7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

UNIT I

Introduction: The Programming Cycle for Python, Python IDE,


Interacting with Python Programs, Elements of Python, Type
Conversion.
Basics: Expressions, Assignment Statement, Arithmetic Operators,
Operator Precedence, Boolean Expression.

DATA, EXPRESSIONS, and STATEMENTS

Programming language:

A programming language is a vocabulary and set of grammatical rules for


instructing a computer or computing device to perform specific tasks. The term
programming language usually refers to high-level languages, such as BASIC, C,
C++, COBOL, Java, FORTRAN, Ada, and Pascal.

Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-


level programming language.

• Python is designed to be highly readable.


• Need not compile the program before executing it.

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.

Why choose python as your first language?

• Easy to learn, read, maintain.


• Broad library support
• Interactive mode
• Portable
• Extendable
• Easy to connect with databases.
• GUI support
• Scalable
Features of Python

• It supports functional and structured programming methods as well as OOP.


• It can be used as a scripting language or can be compiled to byte-code for
building large applications.
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java
Python Interpreter

Python
Source code Interpreter Output

Python Interpreter`s Mode of operation:

• Python has two basic modes: normal and interactive.


• The normal mode is the mode where the scripted and finished .py files
are run in the Python interpreter.
• Interactive mode is a command line shell which gives immediate
feedback for each statement, while running previously fed statements in
active memory.
• As new lines are fed into the interpreter, the fed program is evaluated
both in part and in whole.

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

A Python identifier is a name used to identify a variable, function, class, module or


other object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within


identifiers.

Python is a case sensitive programming language. Thus, Manpower and manpower


are two different identifiers in Python.

Here are naming conventions for 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:

Every value in Python has a data type.


It is a set of values, and the allowable operations on those values.

Python has four standard data types:

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

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication etc.

Operator Meaning Example


+ Add two operands or unary plus x + y+2
- Subtract right operand from the left or unary minus x - y-2
* Multiply two operands x*y
Divide left operand by the right one (always results
/ x/y
into float)
Modulus - remainder of the division of left operand x % y (remainder
%
by the right of x/y)
Floor division - division that results into whole
// x // y
number adjusted to the left in the number line
x**y (x to the
** Exponent - left operand raised to the power of right
power y)

Comparison operators

Comparison operators are used to compare values. It either returns True or


False according to the condition.

Operator Meaning 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
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than or
>= x >= y
equal to the right
Less than or equal to - True if left operand is less than or equal
<= x <= y
to the right
Logical operators

Logical operators are the and, or, not operators.

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Bitwise operators

Bitwise operators act on operands as if they were string of binary digits. It operates
bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)

Operator Meaning Example


& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

Assignment operators

Assignment operators are used in Python to assign values to variables. a = 5


is a simple assignment operator that assigns the value 5 on the right to the variable
a on the left. There are various compound operators in Python like a += 5 that adds
to the variable and later assigns the same. It is equivalent to a = a + 5.

Operator Example Equivalent to


= 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
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

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.

Operator Meaning Example


is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the x is not
is not
same object) True

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.

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x
Precedence Of Operators

When more than one operator appears in an expression, the order of


evaluation depends on the rules of precedence. For mathematical operators, Python
follows mathematical convention. The acronym PEMDAS is a useful way to
remember the rules:

➢ Parentheses have the highest precedence and can be used to force an


expression to evaluate in the order you want. Since expressions in parentheses
are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use
parentheses to make an expression easier to read, as in (minute * 100) / 60, even
if it doesn’t change the result.

➢ Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and


3*1**3 is 3, not 27.

➢ 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.

One Line Comments


Typically, you just use the # (pound) sign to comment out everything that follows
it on that line.
Example

print("Not a comment")
#print("Am a comment")Result
output :

Not a comment

Multiple Line Comments


Multiple line comments are slightly different. Simply use three single quotes
before and after the part you want commented.
Example

'''
print("We are in a comment")
print ("We are still in a comment")
'''
print("We are out of the comment")

Output

We are out of the comment

Expressions

An expression is a combination of values, variables, and operators. A value


all by itself is considered an expression, and so is a variable, so the following are
all legal expressions

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

A statement is a unit of code that the Python interpreter can execute. We


have seen two kinds of statement: print and assignment. Technically an expression
is also a statement, but it is probably simpler to think of them as different things.
The important difference is that an expression has a value; a statement does not.
Consider the example below,

When we enter the assignment statement, y=3.14, only the prompt is


returned. There is no value. This is due to the fact that statements, such as the
assignment statement, do not return a value. They are simply executed. On the
other hand, the result of executing the assignment statement is the creation of a
reference from a variable, y, to a value, 3.14When we execute the print function
working on y, we see the value that y is referring to. In fact, evaluating y by itself
results in the same response.

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.

Python has five standard data types

• 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

Python supports different numerical types,

➢ 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.

int float complex


10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
-0490 -90. -.6545+0J
-0×260 -32.54e100 3e+26J
0×69 70.2-E12 4.53e-7j
Python Strings

Strings in Python are identified as a contiguous set of characters represented


in the quotation marks. Python allows either pair of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 to the
end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator.

This will produce the following result,

Python Lists

A list contains items separated by commas and enclosed within square


brackets ([]).To some extent, lists are similar to arrays in C.One of the differences
between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and
[:]) with indexes starting at 0 in the beginning of the list and working their way to
end -1.The plus (+) sign is the list concatenation operator, and the asterisk (*) is the
repetition operator.

For example
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.

In certain places (like if statements), Python expects an expression to


evaluate to a boolean value. These places are called boolean contexts. You can use
virtually any expression in a boolean context, and Python will try to determine its
true value
Tuples

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

This produces the following result

Modules

Modules refer to a file containing Python statements and definitions. A file


containing Python code, for e.g.: example.py, is called a module and its module
name would be example. We use modules to break down large programs into small
manageable and organized files.

Furthermore, modules provide reusability of code. We can define our most


used functions in a module and import it, instead of copying their definitions into
different programs.

Let us create a module. Type the following and save it as example.py.


Here, we have defined a function add () inside a module named example. The
function takes in two numbers and returns their sum.

Import Modules

We can import the definitions inside a module to another module or the


interactive interpreter in Python. We use the import keyword to do this. To import
our previously defined module example we type the following in the Python
prompt.

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.

Python import statement

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 :

Import with renaming

We can import a module by renaming it as follows.

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.

Python from...import statement

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.

Import all names

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

Function is a group of related statements that perform a specific


task.Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.Furthermore, it avoids repetition and makes code reusable.

Syntax of Function
Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same
rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They
are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function
does.
6. One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function

Function Call

Once we have defined a function, we can call it from another function,


program or even the Python prompt. To call a function we simply type the function
name with appropriate parameters.

The return statement

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.

Here, None is the returned value.

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.

PARAMETERS AND ARGUMENTS

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.

Here 7,2 are the positional arguments.

Keyword:A keyword argument is followed by an equal sign and an expression


that gives its 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.

Packed positional: These arguments by *.Then theargument is unpacked, and the


values are treated as separate positional arguments. That * and the ** operators
both perform two different, but complementary operations depending on where
they're used.

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.

Packed keyword: An argument which is treated as a mapping will be preceded by


**

In the above example the dictionary data kwargs is packed by ** during


function call. In the function definition this kwargs is unpacked and each parameter
is considered as a keyword and it is been mapped with the arguments passed and
the corresponding value is taken for that parameter.

Parameters

Parameters are part of a function definition. There are four different kinds of
parameters:

Positional-or-keyword: Normal parameters in a function definition, with or


without default values.
In the example above the function definition contains a default parameter for
the breadth, so even though the caller has not supplied the necessary argument the
default parameter value is taken in to consideration.

Positional-only:This Positional-only parameterAccepts argument without default


value.

Var-positional: This kind of parameter accepts variable number of arguments


without any default value and the parameter is usually preceded with *.

Here in the above program the various positional argument from the function
call is been packed into a tuple in the function definition.

Var-keyword:This type of parameter is used to take or accept variable length


argument from a function call with default value. This kind of argument ispreceded
with **.
In the above example the default valued arguments from the function call is been
packed into a dictionary in the function definition. It can be simply displayed in the
print statement or it can be iterated.

ILLUSTRATIVE PROGRAMS

A) Exchange the values of two variables

Output

B) Test for leap year


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

1. Give a short note on python.

Python is an interpreted high-level programming language for general-


purpose programming. It is dynamically object oriented programming. It is
and open source software.

2. What are all the data types supported by python?

The following data types are supported by the python language.


• Integer [Binary, Octal, Hexadecimal]
• Float
• String
• List
• Tuple

3. Define list in python.

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.

Eg: a_list = [1,3,2,5,6]

4. Define tuple in python.

In python tuple is an ordered unchangeable sequence of items. Items cam be


any types and each one separated by comas. The accessing of elements is
based on index and it is inerrable like list. Tuple’s are immutable. Once it is
created we can’t change the elements by number’s or values.

Eg: a_tupple = (1,2,3,5,4,7)

5. What is variable in python?

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.

6. What is identifier in python?

A valid string that can be used as name in programming languages it is


known as identifiers. Variable name, class names, function names are all
known as identifiers.

Rules for usage of identifiers:

1. Name may contain letters, numbers and underscore.


2. It must start with letter.
3. Keyword should not be used as identifiers.
4. Special characters (@,$,#...etc) not allowed.

7. What is the difference between (and) operator and (&) operator?

Both are recognized as operators in python with operands.


• and – is logical operator that checks for Boolean values of both
operands. If both values are true then and expression evaluation is
true. Eg True and True – True , True and False – False
• & - Is a bitwise operator it receives two integer operands and performs
bitwise comparison of the operands binary values. Eg: 4&5 – 4 [100
& 101 - 100] .

8. Write a program that receives two numbers from the user and find
which one is great?

a = int(input(“enter number 1”)


b = int(input(“enter number 1”)
if (a>b):
print(“number 1 is great”)
else
print(“number 2 is great”)

9. List the features of python language.

• Simple
• Open source
• High-level
• Portable
• Object Oriented
• Interpreted
• Easy to maintain
• Scalable

10.List the operators supported by the python language.

• Arithmetic Operators
• Relational Operators
• Logical/Boolean Operators
• Bitwise Operator
• Assignment Operators
• Membership Operators
• Identity Operators

11.What is bit wise operator?

Bitwise operators are operators that works on binary values of an integer


numbers. It receives integer operands and perform bitwise logic on the
binary representation of an integer numbers. The following operators are
knows as bitwise operators.
| [OR], & [AND], ~ [Negotiation], ^ [XOR], >> [Right shift], << [Left
Shift].

12.What is use of membership operator in python?

It is special type of operators it works on sequences. It checks for an item is


present or not present in a sequence. The sequence can be anything lists,
tuples, strings. There are two membership operators available.

in = it checks for item is present in the sequence. If an item present it returns


true else it returns false.
not in = it checks for an item not present in the sequence. If not returns true
else it returns false.
Eg:
alist = [1,4,5,6]
print( 4 in alist ) – True
print ( 10 not in alist ) – True
13.Evaluate expressions based on operator precedence.
a. 45+5*7/4-2 [ Answer = 51.75 ]
b. 4**2/4+3-1 [ Answer = 6.0 ]

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].

15.List four in-built in functions with its descriptions.

abs() – It returns an absolute value of number.


chr() – It returns character from the integer.
bin() – It converts integer into binary.
min() – It finds minimum in a sequence.

16.List down the types of functions.

• Based on Parameters
o Functions without parameters.
o Function with parameters.
• Based on arguments
o Default arguments.
o Keyword arguments.
o Arbitrary arguments.

17.What are modules in python?

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.

18.Write a program that helps to convert Celsius to Fahrenheit.

temp_c = float(input(“Enter temperature in Celsius : ”))


temp_f = (temp_c * (9/5))+32
print (“Temperature in Fahrenheit :”,temp_f)
19.Write a program that swaps the values of two variables.

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)

20.Write a function that helps to find the factorial of a number.


def fact_finder(number):
result = 1
while (number > 0):
result = result * number
number = number – 1

PART – B

1. Explain about data types supported by python language with simple


examples.
2. Explain about arithmetic and comparison operators supported by python
with simple examples.
3. Explain about assignment operators and identify operators with
examples.
4. Explain about bitwise and logical operators with example and distinguish
them.
5. Explain about types of functions based on arguments with simple
examples.
6. Write a program that helps to find the given year is leap year or not. if it
is leap year find that year is sum of digits of the year. [Eg – 2012 is leap
sum of digits is 5].
7. Write a program that helps to find the square root of the given number
using newton’s iterative method.
8. Write a program that helps to find the e power x with a help of user
defined functions.
9. Create a module for simple calculator operations and import them into
another program.
10.Write a program that helps to calculate the grade of the student based on mark
obtained in five subjects.
UNIT III
CONTROL FLOW, FUNCTIONS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else),
chained conditional (if-elif-else); Iteration: state, while, for, break, continue, pass;
Fruitful functions: return values, parameters, scope: local and global, composition,
recursion; Strings: string slices, immutability, string functions and methods, string
module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum the
array of numbers, linear search, binary search.

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:

They are used to perform mathematical operations like addition, subtraction,


multiplication etc.
Operator Description Example
a=10,b=20
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and b % a = 0
returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the
operators power 20
// Floor Division - The division of operands where the 5//2=2
result is the quotient in which the digits after the
decimal point are removed

Comparison (Relational) Operators:


  
Comparison operators are used to compare values.
 
It either returns True or False according to the condition.

Operator Description Example


a=10,b=20
== If the values of two operands are equal, then the condition (a == b) is not
becomes true. true.
!= If values of two operands are not equal, then condition becomes (a!=b) is true
true.
> If the value of left operand is greater than the value of right (a > b) is not
operand, then condition becomes true. true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value (a >= b) is not
of right operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to left c = a + b assigns
side operand value of a + b into c
+= Add AND It adds right operand to the left operand and c += a is equivalent
assign the result to left operand to c = c + a
-= Subtract AND It subtracts right operand from the left operand c -= a is equivalent
and assign the result to left operand to c = c - a
*= Multiply AND It multiplies right operand with the left operand
c *= a is equivalent
and assign the result to left operand to c = c * a
/= Divide AND It divides left operand with the right operand and
c /= a is equivalent
assign the result to left operand to c = c / ac /= a is
equivalent to c = c
/a
%= Modulus AND It takes modulus using two operands and assign c %= a is
the result to left operand equivalent to c = c
%a
**= Exponent AND Performs exponential (power) calculation on c **= a is
operators and assign value to the left operand equivalent to c = c
** a
//= Floor Division It performs floor division on operators and c //= a is
assign value to the left operand equivalent to c = c
// a
Logical Operators:
Logical operators are and, or, not operators.

Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Membership Operators:

 Evaluates to find a valueor 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

Alternative execution (if-else)


In the alternative the condition must be true or false. In this else statement can be
combined with if statement. The else statement contains the block of code that executes
when the condition is false. If the condition is true statements inside the if get executed
otherwise else part gets executed. The alternatives are called branches, because they are
branches in the flow of execution.
syntax:

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")

greatest of two numbers Output


a=eval(input("enter a value:")) enter a value:4
b=eval(input("enter b value:")) enter b value:7
if(a>b): greatest: 7
print("greatest:",a)
else:
print("greatest:",b)
eligibility for voting Output
age=eval(input("enter ur age:")) enter ur age:78
if(age>=18): you are eligible for vote
print("you are eligible for vote")
else:
print("you are eligible for vote")
Chained conditionals(if-elif-else)
 The elif is short for else if.

 This is used to check more than one condition.

 If the condition1 is False, it checks the condition2 of the elif block. If all the
conditions are False, then the else part is executed.

Among the several if...elif...else part, only one part is executed according to
the condition.

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

student mark system Output


mark=eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
compare two numbers Output
x=eval(input("enter x value:")) enter x value:5
y=eval(input("enter y value:")) enter y value:7
if(x == y): x is less than y
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Roots of quadratic equation output
a=eval(input("enter a value:")) enter a value:1
b=eval(input("enter b value:")) enter b value:0
c=eval(input("enter c value:")) enter c value:0
d=(b*b-4*a*c) same and real roots
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")
Nested conditionals
One conditional can also be nested within another. Any number of condition can be
nested inside one another. In this, if the condition is true it checks another if condition1.
If both the conditions are true statement1 get executed otherwise statement2 get
execute. if the condition is false statement3 gets executed

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)

positive negative or zero output


n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")

Inline if:
An inline if statement is a simpler form of if statement and is more convenient ,if we
need to perform simple task.

Syntax: do task A if condition is true else do task B

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)

Factorial of a numbers: output


n=eval(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)

Sum of digits of a number: output


n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 6
a=n%10

sum=sum+a
n=n//10
print(sum)

Reverse the given number: output


n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)
Armstrong number or not output
n=eval(input("enter a number")) enter a number153
org=n The given number is Armstrong number
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong
number")
else:
print("The given number is not
Armstrong number")

Palindrome or not output


n=eval(input("enter a number")) enter a number121
org=n The given no is palindrome
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")

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.

Sequence can be a list, strings or tuples

s.no sequences example output


R
1. For loop in string for i in "Ramu": A
print(i) M
U

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

print nos divisible by 5 not by 10 output


n=eval(input("enter a")) enter a:30
for i in range(1,n,1): 5
if(i%5==0 and i%10!=0): 15
print(i) 25

Fibonacci series output


a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=eval(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c
find factors of a number Output
n=eval(input("enter a number:")) enter a number:10
for i in range(1,n+1,1): 1
if(n%i==0): 2
print(i) 5
10

check the no is prime or not output


n=eval(input("enter a number")) enter a no:7
for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")
check a number is perfect number or not Output
n=eval(input("enter a number:")) enter a number:6
sum=0 the number is perfect number
for i in range(1,n,1):
if(n%i==0):
sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")
Program to print first n prime numbers Output
number=int(input("enter no of prime enter no of prime numbers to be
numbers to be displayed:")) displayed:5
count=1 2
n=2 3
while(count<=number): 5
for i in range(2,n): 7
if(n%i==0): 11
break
else:
print(n)
count=count+1
n=n+1
Program to print prime numbers in range output:
lower=eval(input("enter a lower range")) enter a lower range50
upper=eval(input("enter a upper range")) enter a upper range100
for n in range(lower,upper + 1): 53
if n > 1: 59
for i in range(2,n): 61
if (n % i) == 0: 67
break 71
else: 73
print(n) 79
83
89
97
Loop Control Structures
BREAK
  Break statements can alter the flow of a loop.
 
 It terminates the current
 
 loop and executes the remaining statement outside the loop.

If the loop has
 else statement, that will also gets terminated and come out of the loop
completely.
Syntax:
break

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

Difference between break and continue


break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
syntax: syntax:
break continue
for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
w w
e e
l l
o
m
e
else statement in loops:
else in for loop:

 If else statement is
used in for loop, the else statement is executed when the loop has
reached the limit.
 
The statements inside for loop and statements inside else will also execute.
example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6
else in while loop:

 If else statement is used
within while loop , the else part will be executed when the
condition become false.
 
The statements inside for loop and statements inside else will also execute.
Program output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5

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”):

Variable length parameter


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)

Local and Global Scope


Global Scope
  The scope of a variable refers to the places that you can see or access a variable.
 
 A variable with global scope can be used anywhere in the program.
 
It can be created by defining a variable outside the function.
Example output
a=50
def add():
Global Variable
b=20 70
c=a+b
print© Local Variable
def sub():
b=30
c=a-b 20
print©
print(a) 50
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20
c=a+b 70
Local Variable
print©
def sub():
b=30 20
c=a-b Local Variable
print©
print(a) error
print(b) error
Function Composition:
 
 Function Composition is the ability to call one function from within another function

It is a way of combining functions
 such that the result of each function is passed as the
 argument of the next function.

In other words the output of one
function is given as the input of another function is
known as function composition.

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)

find sum and average using function output


composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)
Recursion
A function calling itself till it reaches the base value - stop point of function
call. Example: factorial of a given number using recursion
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)

n=eval(input("enter no. to find


fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation

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)

n=eval(input("enter no. to find


sum:"))
sum=sum(n)
print("Fact is",sum)
Strings:
  Strings
  
String slices
  
Immutability
  
String functions and methods
 String module

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.

a=”save” The + operator joins the text on both


Concatenation b=”earth” sides of the operator.
>>>print(a+b)
saveearth

a=”panimalar ” The * operator repeats the string on the


Repetitions: >>>print(3*a) left hand side times the value on right
panimalarpanimalar hand side.
panimalar

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present
>>> "a" not in s
True
String slices:
 
 A part of a string is called string slices.
 The process of extracting a sub string from a string is called slicing.
Print[0:4] – HELL The Slice[n : m] operator extracts sub
Slicing: Print[ :3] – HEL string from the strings.
a=”HELLO” 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.

operations Example output


element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment

element deletion a=”PYTHON” TypeError: 'str' object


del a[0] doesn't support element
deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a is not defined
print(a)
string built in functions and methods:
A method is a function that “belongs to” an object.

Syntax to access the method

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.

Standardmodules 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)

Methods in array a=[2,3,4,5]


Syntax example Description
1 array(data type, array(‘i’,[2,3,4,5]) This function is used to create
value list) an array with data type and
value list specified in its
arguments.
2 append() >>>a.append(6) This method is used to add the
[2,3,4,5,6] at the end of the array.
3 insert(index,element >>>a.insert(2,10) This method is used to add the
) [2,3,10,5,6] value at the position specified in
its argument.

4 pop(index) >>>a.pop(1) This function removes the


[2,10,5,6] element at the position
mentioned in its argument, and
returns it.
5 index(element) >>>a.index(2) This function returns the index
0 of value
6 reverse() >>>a.reverse() This function reverses the
[6,5,10,2] array.
a.count() This is used to count number of
7 count() 4 elements in an array
ILLUSTRATIVE PROGRAMS:

Square root using newtons method: Output:


def newtonsqrt(n): enter number to find Sqrt: 9
root=n/2 3.0
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output
n1=int(input("Enter a number1:")) Enter a number1:8
n2=int(input("Enter a number2:")) Enter a number2:24
for i in range(1,n1+1): 8
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Exponent of number Output:
def power(base,exp): Enter base: 2
if(exp==1): Enter exponential value:3
return(base) Result: 8
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
sum of array elements: output:
a=[2,3,4,5,6,7,8] the sum is 35
sum=0
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output
a=[20,30,40,50,60,70,89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
Binary search output
a=[20, 30, 40, 50, 60, 70, 89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("elemrnt found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")

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.

Syntax: lambda arguments: expression

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.

21. What is slicing? Give an example.


22. What is immutability of string?
23. List out some string built in function with example?
24. Define string module?
25. How can list act as array?
26. write a program to check the number is odd or even.
27. write a program to check the number positive or negative
28. write a program to check the year is leap year or not
29. write a program to find greatest of two numbers
30. write a program for checking eligibility for vote
31. write a program to find sum of n numbers
32. write a program to find factorial of given numbers
33. write a program to find sum of digits of a number
34. Write a program to reverse the given number.
35. Write a program to check the given number is palindrome or not.
36. write a program to check the given number is Armstrong or not
37. how can you use for loop in sequence.
38. how can you use else statement if loops.
39. What is the use of map() function?
Part B:
1. Explain conditional statements in detail with example(if, if..else, if..elif..else)
2. explain in detail about operators in detail
3. Explain in detail about iterations with example.(for, while)
4. Explain the usage of else statements in loops
5. Explain in detail about using for loop in sequence.
6. Explain in detail about string built in function with suitable examples?
7. Explain about loop control statement(break, continue, pass)
8. Breifly discuss about fruitful function.
9. Discuss with an example about local and global variable
10. Discuss with an example about function composition
11. Explain in detail about recursion with example.
12. Explain in detail about strings and its operations(slicing,immutablity)
13. Program to find square root of a given number using newtons method
14. program to find gcd of given nnumber
15. program to find exponentiation of given number using recursion
16. program to find sum of array elements.
17. program to search an element using linear search.
18. program to search an element using binary element.
19. program to find factorial of a given number using recursion
&
COMPOUND DATA: LISTS, TUPLES, DICTIONARIES
Lists, list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples, tuple assignment, tuple as return value; Dictionaries:
operations and methods; advanced list processing - list comprehension, Illustrative
programs: selection sort, insertion sort, merge sort, quick sort.
Lists
  List is an ordered sequence of items. Values in the list are called elements / items.

It can be written
 as a list of comma-separated items (values) between square
brackets[ ].

Items in the lists can be of different data types.
Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty
list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison

operations examples description


create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0]) Accessing the item in the
Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>b=[20,30] Adding and printing the


Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same list.

>>> 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





slices example description


a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from
>>> a[0:3] 0 to 2.
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. so
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]

slices example description

a[2:2] >>> a[2:2] print an empty slice


[]
a[0:6:2] >>> a=[9,8,7,6,5,4] Slicing list values with step
>>> a[0:6:2] size 2.(from index[0] to 2nd
[9, 7, 5] element and from that
>>> a[0:6:3] position to next 2nd element
[9,6]

List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)

syntax example description


1 >>> a=[1,2,3,4,5]
>>> a.append(6) Add an element to
a.append(element) >>> print(a) the end of the list
[1, 2, 3, 4, 5, 6]
2 a.insert(index,element) >>> a.insert(0,0) Insert an item at the
>>> print(a) defined index
[0, 1, 2, 3, 4, 5, 6]
3 a.extend(b) >>> a=[1,2,3,4,5]
>>> b=[7,8,9]
>>> a.extend(b) Add all elements of a
>>> print(a) list to the another
[0, 1, 2, 3, 4, 5, 6, 7, 8,9] list
4 >>>a=[0, 1, 2, 3, 8,5, 6, 7, 8,9] Returns the index of
a.index(element) >>> a.index(8) the first matched
4 item
5 >>> a=[1,2,3,4,5]
>>> sum(a) Sort items in a list in
sum()
>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
6 >>> a.reverse()
Reverse the order of
a.reverse() >>> print(a)
items in the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]

>>>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:

Accessing element output


a=[10,20,30,40,50] 10
for i in a: 20
print(i) 30
40
50
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
List using While loop

The while loop in Python is used to iterate over a block of code as long as the test
 expression (condition) is true.

When the condition is tested and the result is false, the
 loop body will be skipped and the
first statement after the while loop will be executed.
Syntax:
while (condition):
body of while

Sum of elements in list Output:


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

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 canbe 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

clonning using Slicing


>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False #because they have different memory location
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using 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 tuplehas 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.

methods example description


list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:
  Tuples are faster than lists.
 
 If the user wants to protect the data from accidental changes, tuple can be used.
 
Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> 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 tuple. 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
Tuple methods:

Tuple is immutable
 so changes cannot be done on the elements of a tuple once it is
assigned.
methods example description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire 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 return value:


 A Tuple is a comma separated sequence of items.
 
 It is created with or without ( ).

A function can return one value. if you wantto return more than one value from a
function. we can use tuple as return value.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

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

Creating a >>> a={1:"one",2:"two"} Creating the dictionary with


dictionary >>> print(a) elements of different data types.
{1: 'one', 2: 'two'}
accessing an >>> a[1] Accessing the elements by using
element 'one' keys.
>>> a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new value.
{1: 'ONE', 2: 'two'}
add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present in
>>> 1 in a dictionary. Otherwise returns false.
True
>>> 3 not in a
False

Methods in dictionary:

Method Example Description

a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the


>>> b=a.copy() dictionary. here copy of
>>> print(b) dictionary ’a’ get stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘b’
a.items() >>> a.items() Return a new view of
dict_items([(1, 'ONE'), (2, 'two'), (3, the dictionary's items. It
'three')]) displays a list of
dictionary’s (key, value)
tuple pairs.
a.keys() >>> a.keys() It displays list of keys in
dict_keys([1, 2, 3]) a dictionary
a.values() >>> a.values() It displays list of values
dict_values(['ONE', 'two', 'three']) in dictionary
a.pop(key) >>> a.pop(3) Remove the element
'three' with key and return its
>>> print(a) value from the
{1: 'ONE', 2: 'two'} dictionary.
setdefault(key,value) >>> a.setdefault(3,"three") If key is in the
'three' dictionary, return its
>>> print(a) value. If key is not
{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with
>>> a.setdefault(2) a value of dictionary and
'two' return dictionary.
a.update(dictionary) >>> b={4:"four"}
It will add the dictionary
>>> a.update(b)
with the existing
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} dictionary
fromkeys() >>> key={"apple","ball"} It creates a dictionary
>>> value="for kids" from key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of
>>>lena(a) the list.
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements
>>>a.clear() form the dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.

Difference between List, Tuples and dictionary:

List Tuples Dictionary


A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in Tuples are enclosed in parenthesis ( ) Tuples are enclosed in
brackets[ ] and their and cannot be updated curly braces { } and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":
Or 24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])
Can contain duplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
  
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical

doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
 
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.

Dictionary is used
when data is being
constantly modified.

Advanced list processing:


List Comprehension:
  
List comprehensions provide a concise way to apply operations on a list.

It creates
 a new list in which each element is the result of applying a given operation in a
 list.
 
It consists of brackets containing an expression followed by a “for” clause, then a list.
 
The list comprehension always returns a result list.
Syntax
list=[ expression for item in list if conditional ]
List Comprehension Output

>>>L=[x**2 for x in range(0,5)] [0, 1, 4, 9, 16]


>>>print(L)
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2] [1, 4, 9]
>>> [x**2 for x in mixed if type(x)==int]

>>>[x+3 for x in [1,2,3]] [4, 5, 6]

>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]

>>> num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]


>>> [x for x in num if x>=0]

>>> str=["this","is","an","example"] ['t', 'i', 'a', 'e']


>>> element=[word[0] for word in str]
>>> print(element)
Nested list:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57

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)

Matrix multiplication 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)):
for k in range(len(b)):
c[i][j]=a[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)

Matrix transpose Output


a=[[1,3],[1,2]] [1, 1]
c=[[0,0],[0,0]] [3, 2]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
for i in c:
print(i)
Illustrative programs:
Selection sort Output
a=input("Enter list:").split() Enter list:23 78 45 8 32 56
a=list(map(eval,a)) [8,2 3, 32, 45,56, 78]
for i in range(0,len(a)):
smallest = min(a[i:])
sindex= a.index(smallest)
a[i],a[sindex] = a[sindex],a[i]
print (a)

Insertion sort output


a=input("enter a list:").split()
a=list(map(int,a))
for i in a: enter a list: 8 5 7 1 9 3
j = a.index(i) [1,3,5,7,8,9]
while j>0:
if a[j-1] > a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print (a)
Merge sort output
def merge(a,b):
c = [] [3,9,10,27,38,43,82]
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c=c+b
else:
c=c+a
return c

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.

Python File Modes


Mode Description
'r' Open a file for reading. (default)
Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w'
exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
Open for appending at the end of the file without truncating it. Creates a new file if it
'a'
does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and w

f = open("test.txt") # equivalent to 'r' or 'rt'


f = open("test.txt",'w') # write in text mode
1
f = open("img.bmp",'r+b') # read and write in binary mode

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

Reading and writing


A text file is a sequence of characters stored on a permanent medium like a hard drive, flash
memory, or CD-ROM.
To write a file, you have to open it with mode 'w' as a second parameter:
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>

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:

>>> '%d %d %d' % (1, 2)


TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation
Filenames and paths
Files are organized into directories (also called “folders”). Every running program
has a “current directory,” which is the default directory for most operations. For example,
when you open a file for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (“os” stands for
“operating system”). os.getcwd returns the name of the current directory:
>>> import os
>>> cwd = os.getcwd()
>>> print cwd
/home/dinsdale

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'

os.path.exists checks whether a file or directory exists:


>>> os.path.exists('memo.txt')
True

If it exists, os.path.isdir checks whether it’s a directory:


>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
True

Similarly, os.path.isfile checks whether it’s a file.


os.listdir returns a list of the files (and other directories) in the given directory:
>>> os.listdir(cwd) ['music',
'photos', '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'

Python Built-in Exceptions


Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that
are raised when corresponding errors occur. We can view all the built-in exceptions using the
local() built-in functions as follows.
>>> locals()['__builtins__']

This will return us a dictionary of built-in exceptions, functions and attributes.


Some of the common built-in exceptions in Python programming along with the error that
cause then are tabulated below.

Python Built-in Exceptions


Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
Raised when result of an arithmetic operation is too large to be
OverflowError
represented.
Raised when a weak reference proxy is used to access a garbage
ReferenceError
collected referent.
RuntimeError Raised when an error does not fall under any other category.
Raised by next() function to indicate that there is no further item to
StopIteration
be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
Raised when a function or operation is applied to an object of
TypeError
incorrect type.
Raised when a reference is made to a local variable in a function or
UnboundLocalError
method, but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
Raised when a function gets argument of correct type but improper
ValueError
value.
ZeroDivisionError Raised when second operand of division or modulo operation is zero.
We can handle these built-in and user-defined exceptions in Python using try, except and
finally statements.

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.

Catching Exceptions in Python


In Python, exceptions can be handled using a try statement.
A critical operation which can raise exception is placed inside the try clause and the code that
handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.
# import module sys to get the type of
exception import sys

randomList = ['a', 0, 2]

for entry in randomList:


try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
Output
The entry is a
Oops! <class 'ValueError'> occured.
Next entry.

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

# To ask month and year from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))

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.

Importing module from a package


We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as
follows. import Game.Level.start
9
Now if this module contains a function named select_difficulty(), we must use the full name to
reference it.
Game.Level.start.select_difficulty(2)

If this construct seems lengthy, we can import the module without the package prefix as follows.
from Game.Level import start

We can now call the function simply as follows.


start.select_difficulty(2)

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

Now we can directly call this function.


select_difficulty(2)

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( ))

You might also like