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

I Year Python Material

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 136

I B.

SC CS

VIVEKANANDHA ARTS AND SCIENCE COLLEGE FOR WOMEN

VEERACHIPALAYAM

DEPARTMENT OF COMPUTER SCIENCE AND APPLICATIONS

PYTHON PROGRAMMING

Unit I: Basics of Python Programming: History of Python-Features of Python - Literal -


Constants-Variables - Identifiers–Keywords-Built-in Data Types-Output Statements –
Input Statements - Comments – Indentation- Operators-Expressions-Type
conversions. Python Arrays: Defining and Processing Arrays – Array methods.

Unit II: Control Statements: Selection/Conditional Branching statements: if, if-else,


nested if and if-elif-else statements. Iterative Statements: while loop, for loop, else
suite in loop and nested loops. Jump Statements: break, continue and pass statements.

Unit III: Functions: Function Definition – Function Call – Variable Scope and its
Lifetime- Return Statement. Function Arguments: Required Arguments, Keyword
Arguments, Default Arguments and Variable Length Arguments-Recursion. Python
Strings: String operations- Immutable Strings - Built-in String Methods and Functions
- String Comparison. Modules: import statement- The Python module – dir() function
– Modules and Namespace – Definingour own modules.

Unit IV: Lists: Creating a list -Access values in List-Updating values in Lists-Nested
lists – Basic list operations-List Methods. Tuples: Creating, Accessing, Updating and
Deleting Elements in a tuple – Nested tuples– Difference between lists and
tuples. Dictionaries:
Creating, Accessing, Updating and Deleting Elements in a Dictionary – Dictionary
Functionsand Methods - Difference between Lists and Dictionaries.

Unit V: Python File Handling: Types of files in Python - Opening and Closing files-
Readingand Writing files: write() and writelines() methods- append() method –read()
and readlines() methods – with keyword – Splitting words – File methods - File
Positions- Renaming and deleting files.

Textbooks:

1. ReemaThareja, “Python Programming using problem solving approach”, First


Edition,2017, Oxford University Press.

2. Dr. R. NageswaraRao, “Core Python Programming”, First Edition, 2017, Dream


techPublishers.
I B.SC CS

Python Programming
1. Features and History of Python:
1.1Features of Python
 Simple: Reading a program written in Python feels almost like reading english. The
main strength of Python which allows programmer to concentrate on the solution
to the problem rather than language itself.
 Easy to Learn: Python program is clearly defined and easily readable. The
structure of the program is simple. It uses few keywords and clearly defined syntax.
 Versatile: Python supports development of wide range of applications such as
simple text processing, WWW browsers and games etc..
 Free and Open Source: It is a Open Source Software. So, anyone can freely
distribute it, read the source code, edit it, and even use the code to write new (free)
programs.
 High-level Language: While writing programs in Python we do not worry about
the low-level details like managing memory used by the program.
 Interactive: Programs in Python work in interactive mode which allows interactive
testing and debugging of pieces of code. Programmer can easily interact with the
interpreter directly at the python prompt to write their programs.
 Portable: It is a portable language and hence the programs behave the same on wide
variety of hardware platforms with different operating systems.
 Object Oriented: Python supports object-oriented as well as procedure-orientedstyle
of programming .While object-oriented technique encapsulates data and functionality
with in objects, Procedure oriented at other hand, builds programs around procedure
or functions.
 Interpreted: Python is processed at runtime by interpreter. So, there is no need
to compile a program before executing it. You can simply run the program. Basically
python converts source program into intermediate form called byte code.
I B.SC CS

 Dynamic and strongly typed language: Python is strongly typed as the interpreter
keeps track of all variables types. It's also very dynamic as it rarely uses what it
knows to limit variable usage.
 Extensible: Since Python is an open source software, anyone can add low-level
modules to the python interpreter. These modules enable programmers to add to
or customize their tools to work more efficiently.
 Embeddable: Programmers can embed Python within their C, C++, COM, ActiveX,
CORBA and Java Programs to give „scripting „capability for users.
 Extensive Libraries: Python has huge set of libraries that is easily portable across
different platforms with different operating systems.
 Easy maintenance: Code Written in Python is easy to maintain.
 Secure: This Programming language is secure for tampering. Modules can be
distributed to prevent altering of source code. Additionally, Security checks can be
easily added to implement additional security features.
 Robust: Python Programmers cannot manipulate memory directly, errors are raised
as exceptions that can be catch and handled by the program code. For every
syntactical mistake, a simple and easy to interpret message is displayed. All these make
python robust.
 Multi-threaded: Python supports executing more than one process of a program
simultaneously with the help of Multi Threading.
 Garbage Collection: The Python run-time environment handles garbage
collection of all python objects. For this, a reference counter is maintained to assure
that no object that is currently in use is deleted.

History of Python.
 Python was first developed by Guido van Rossum in the late 80‟s and early 90‟s
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
 It has been derived from many languages such as ABC, Modula-3, C, C++, Algol-
68, SmallTalk, UNIX shell and other scripting languages.
 Since early 90‟s Python has been improved tremendously. Its version 1.0 was
released in 1991, which introduced several new functional programming tools.
I B.SC CS

 While version 2.0included list comprehension was released in 2000 by the Be Open
Python Labs team.
 Python 2.7 which is still used today will be supported till 2020.
 Currently Python 3.6.4 is already available. The newer versions have betterfeatures
like flexible string representation e.t.c,
 Although Python is copyrighted, its source code is available under GNU General
Public License (GPL) like that Perl.
 Python is currently maintained by a core development team at the institute which
is directed by Guido Van Rossum.
 These days, from data to web development, Python has emerged as very powerful
and popular language. It would be surprising to know that python is actually older
than Java, R and JavaScript.
Applications of Python:
 Embedded scripting language: Python is used as an embedded scripting language
for various testing/ building/ deployment/ monitoring frameworks, scientific apps,
and quick scripts.
 3D Software: 3D software like Maya uses Python for automating small user tasks,
or for doing more complex integration such as talking to databases and asset
management systems.
 Web development: Python is an easily extensible language that provides good
integration with database and other web standards.
 GUI-based desktop applications: Simple syntax, modular architecture, rich text
processing tools and the ability to work on multiple operating systems makes Python
a preferred choice for developing desktop-based applications.
 Image processing and graphic design applications: Python is used to make 2D
imaging software such as Inkscape, GIMP, Paint Shop Pro and Scribus. It is also used
to make 3D animation packages, like Blender, 3ds Max, Cinema 4D, Houdini, Light
wave and Maya.
 Scientific and Computational applications: Features like high speed, productivity
and availability of tools, such as Scientific Python and Numeric Python, have made
Python a preferred language to perform computation and
I B.SC CS

processing of scientific data. 3D modeling software, such as FreeCAD, and finite


element method software, like Abaqus, are coded in Python.
 Games: Python has various modules, libraries, and platforms that support
development of games. Games like Civilization-IV, Disney's Toontown Online, Vega
Strike, etc. are coded using Python.
 Enterprise and Business applications: Simple and reliable syntax, modules and
libraries, extensibility, scalability together make Python a suitable coding
language for customizing larger applications. For example, Reddit which was
originally written in Common Lips, was rewritten in Python in 2005. A large part
of Youtube code is also written in Python.
 Operating Systems: Python forms an integral part of Linux distributions.

Keyword in Python:

 Keywords are the reserved words in Python. We cannot use a keyword as


variable name, function name or any other identifier.
 Here's a list of all keywords in Python Programming.
 There are 33 keywords in Python 3.3. This number can vary slightly in course
of time.
 All the keywords except True, False and None are in lowercase and they must
be written as it is. The list of all the keywords are given below.

Keywords in Python Programming Language

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with


I B.SC CS

as elif if or yield

assert else import pass

break except in raise

2. Literal Constants
 In programming constants are referred to variables that cannot be changed.
 Generally Literal constants are classified in to three types.

Literal Constants

Numeric Literals Boolean Literals String Literals

Numeric Literals
 The value of a literal constant can be used directly in programs. For example,
7, 3.9, 'A', and "Hello" are literal constants.
 Numbers refers to a numeric value. You can use four types of numbers inPython
program- integers, long integers, floating point and complex numbers.
 Numbers like 5 or other whole numbers are referred to as integers. Bigger whole
numbers are called long integers. For example, 535633629843L is a long integer.
 Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers.
 Numbers of a + bj form (like -3 + 7j) are complex numbers.
I B.SC CS

Python Programming

Boolean Literals
 A Literals Boolean type can have one of the two values- True or False.

Examples:

String Literals
 A string is a group of characters.
 Using Single Quotes ('): For example, a string can be written as 'HELLO'.
 Using Double Quotes ("): Strings in double quotes are exactly same as those in single
quotes. Therefore, 'HELLO' is same as "HELLO".
 Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes. You
can use as many single quotes and double quotes as you want in a string within
triple quotes.
I B.SC CS

Examples:

Unicode Strings

 Unicode is a standard way of writing international text. That is,if you want to
write some text in your native language like hindi,then you need to have a
Unicode-enable text editor.
 Python allows you to specify Unicode text by prefixing the string with a u or U.
 For Example: u”Sample Unicode string”
Note :The „U‟ prefix specifies that the file contains text written in language
other than English

Escape Sequences

 Some characters (like ", \) cannot be directly included in a string. Such


characters must be escaped by placing a backslash before them.

Raw Strings

 If you want to specify a string that should not handle any escape sequences
and want to display exactly as specified then you need to specify that string as
a raw string. A raw string is specified by prefixing r or R to the string.
I B.SC CS

Example:

3. Data types
 The variables can hold values of different type called Data Type.
 Data type is a set of values and the allowable operations on those values.
 Python has a great set of useful data types. Python's data types are built in the
core of the language. They are easy to use and straightforward.
 Example a person age is stored in a number ,his name is made only with
characters, and his address is made with mixture of numbers and characters.
 Python ha various standard data types to define the operations possible on
them and storage method for each of them.
 Python supports the following five standard data types
1.Numbers

2.Strings

3.Lists

4.Tuple

5.Dictionary

Note: Python is pure object oriented programming language.it refers to


everything as an object including numbers and strings.

 The Following Diagram shows the classification of Python Data Types.


I B.SC CS

Assigning or Initializing Values to Variables


 In Python, programmers need not explicitly declare variables to reserve memory
space. The declaration is done automatically when a value is assigned to the
variable using the equal sign (=). The operand on the left side of equal sign is the
name of the variable and the operand on its right side is the value to be stored
in that variable. Example: Program to
display data of different types using variables and literal constants.

 In Python , you can reassign variables as many times as you want to change
the value stored in them. You may even store value of one data type in a
statement and other data type in subsequent statement. This is possible because
Python variables do not have specific types, i.e., we can assign integer to the
variable, later we assign string to the same variable. 
Example:Program to reassign value to a variable

val = „Hello‟

print(val)

val = 100

print(val)

val=10.32
I B.SC CS

print(val)

Output

Hello

100

10.32

Multiple Assignments
 Python allows programmers to assign single value to more than one variable
simultaneously.
 For example
>>>sum = flag = a = b = 0

 In the above statement, all four integer variables are assigned a value 0.You
can also assign different values to multiple variables simultaneously as shown
below
 For example
>>>sum, a, b, mesg = 0, 3, 5, “Result”

Here, variable sum,a and b are integers(numbers) and mesg is assigned


“Result”.

Note: Removing a variable means that the reference from the name to the value has
been deleted.However, deleted variables can be used again in the code if and only if
you reassign them some value.

Boolean Type
A variable of Boolean type can have one of the two values- True or False.

Similar to other variables, the Boolean variables are also created while we assign a
value to them or when we use a relational operator on them.
I B.SC CS

Tuples

 A tuple is similar to the list as it also consists of a number of values separated by


commas and enclosed within parentheses.
 The main difference between lists and tuples is that you can change the values
in a list but not in a tuple. This means that while tuple is a read only data type,
the list is not.

Examples:

Lists
 Lists are the most versatile data type of Python language.
 A list consist of items separated by commas and enclosed within square brackets
The values stored in a list are accessed using indexes.
 The index of the first element being 0 and n-1 as that of the last element, where
n is the total number of elements in the list. Like strings, you can alsouse the
slice, concatenation and repetition operations on lists.
 Example program to demonstrate operations on lists
list = ['a', 'bc', 78, 1.23]

list1 = ['d', 78]

print(list)

print(list[0])
I B.SC CS

print(list[1:3])

print(list[2:])

print(list * 2)

print(list + list1)

Output:

['a', 'bc', 78, 1.23]

['bc', 78]

[78, 1.23]

['a', 'bc', 78, 1.23, 'a', 'bc', 78, 1.23]

['a', 'bc', 78, 1.23, 'd', 78]

Dictionary
 Python‟s dictionaries stores data in key-value pairs.
 The key values are usually strings and value can be of any data type. The key value
pairs are enclosed with curly braces ({ }).
 Each key value pair separated from the other using a colon (:). To access any
value in the dictionary, you just need to specify its key in square braces ([]).Basically
dictionaries are used for fast retrieval of data.

Example
I B.SC CS

4. Variables and Identifiers

Variables

 Variable means its value can vary. You can store any piece of information in a
variable.
 Variables are nothing but just parts of your computer‟s memory where information
is stored. To identify a variable easily, each variable is given an appropriate name.

Identifiers
Identifiers are names given to identify something. This something can be a
variable, function, class, module or other object. For naming any identifier, there are
some basic rules like:

 The first character of an identifier must be an underscore ('_') or a letter (upper


or lowercase).
 The rest of the identifier name can be underscores ('_'), letters (upper or
lowercase), or digits (0-9).
 Identifier names are case-sensitive. For example, myvar and myVar are not the
same.
 Punctuation characters such as @, $, and % are not allowed within identifiers.
 Examples of valid identifier names are sum, my_var, num1, r, var_20, First,
etc.
 Examples of invalid identifier names are 1num, my-var, %check, Basic Sal,
H#R&A, etc.,

5. 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.
 For example:
>>> 2+3

Here, + is the operator that performs addition. 2 and 3 are the operands
and 5 is the output of the operation.
I B.SC CS

 Python supports the following operators


1. Arithmetic operators
2. Comparison (Relational) operators
3. Unary Operators
4. Bitwise operators
5. Shift Operators
6. Logical Operators
7. Membership and Identity Operators
8. Assignment operators
9. Special operators
Arithmetic Operators
 Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
 This operator will work on two operands.
 Example: If a=100 and b=200 then look at the table below, to see the result of
arithmetic operations.

Comparision (Relational) Operators


 A Relational or Comparison operator checks the relationship between two
operands. If the relation is true, it returns 1; if the relation is false, it returns value
0
I B.SC CS

 For Example assuming a=100 and b=2000,we can use the comparison
operators on them as specified in the following table.

Unary Operator
 Unary operators act on single operands. Python supports unary minus
operator.
 Unary minus operator is strikingly different from the arithmetic operator that
operates on two operands and subtracts the second operand from the first
operand.
 When an operand is preceded by a minus sign, the unary operator negates its
value.
 For example, if a number is positive, it becomes negative when preceded with a
unary minus operator. Similarly, if the number is negative, it becomes positive
after applying the unary minus operator. Consider the given example.
b = 10 a = -(b)

 The result of this expression, is a = -10, because variable b has a positivevalue.


After applying unary minus operator (-) on the operand b, the value becomes -
10, which indicates it as a negative value.
I B.SC CS

Bitwise Operators
 As the name suggests, bitwise operators perform operations at the bit level.
 These operators include bitwise AND, bitwise OR, bitwise XOR, and shift
operators.
 Bitwise operators expect their operands to be of integers and treat them as a
sequence of bits.
 The truth tables of these bitwise operators are given below.

 Example: If a=60 and b=13 then look at the table below, to see the result of
Bitwise operations.

Operator Description Example

& Operator copies a bit to the result if it


(a & b) =12
exists in both operands
(means 0000 1100)
Binary AND

| It copies a bit if it exists in either


(a | b) = 61
operand.
(means 0011 1101)
Binary OR

^ It copies the bit if it is set in one


(a ^ b) = 49
operand but not both.
(means 0011 0001)
Binary XOR

~ (~a ) = -61
It is unary and has the effect of (means 1100 0011
Binary Ones 'flipping' bits. in 2's complement
Complement form due to a
signed binary
I B.SC CS

number.

<< The left operands value is moved left


by the number of bits specified by the a << 2 = 240
Binary Left right operand. (means 1111 0000)
Shift

>> The left operands value is moved right


by the number of bits specified by the a >> 2 = 15
Binary Right right operand. (means 0000 1111)
Shift

Shift Operators
 Python supports two bitwise shift operators. They are shift left (<<) and shift
right (>>).
 These operations are used to shift bits to the left or to the right. The syntax for
a shift operation can be given as follows:

Examples:

Logical Operators

 Logical operators are used to simultaneously evaluate two conditions or


expressions with relational operators.
 Logical AND (and) If expressions on both the sides (left and right side) of the
logical operator are true, then the whole expression is true.
For example, If we have an expression (a>b) and (b>c), then the whole
expression is true only if both expressions are true. That is, if b is greater than
a and c.
I B.SC CS

 Logical OR (or) operator is used to simultaneously evaluate two conditions or


expressions with relational operators. If one or both the expressions of the
logical operator is true, then the whole expression is true.
For example, If we have an expression (a>b) or (b>c), then the whole expression
is true if either b is greater than a or b is greater than c.

 Logical NOT (not) operator takes a single expression and negates the value of
the expression. Logical NOT produces a zero if the expression evaluates to a non-
zero value and produces a 1 if the expression produces a zero. In other words, it
just reverses the value of the expression.
For example, a = 10; b = not a; Now, the value of b = 0.

Membership and Identity Operators


Membership Operator

Python supports two types of membership operators–in and not in. These operators, test
for membership in a sequence such as strings, lists, or tuples.

 in Operator: The operator returns true if a variable is found in the specified


sequence and false otherwise. For example, a in nums returns 1, if a is a member
of nums.
 not in Operator: The operator returns true if a variable is not found in the specified
sequence and false otherwise. For example, a not in nums returns 1,if a is not
a member of nums.

Identity Operators

 is Operator: Returns true if operands or values on both sides of the operator


point to the same object and false otherwise. For example, if a is b returns 1, if
id(a) is same as id(b).
 is not Operator: Returns true if operands or values on both sides of the operator
does not point to the same object and false otherwise. For example, ifa is not b
returns 1, if id(a) is not same as id(b).

Assignment Operators
 Assignment operators are used in Python to assign values to variables.
I B.SC CS

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

Assignment operators in Python

Operator Example Equivatent 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


I B.SC CS

<<= x <<= 5 x = x << 5

Operator Precedence
 The operator precedence in Python are listed in the following table. It is in
descending order, upper group has higher precedence than the lower ones.

Operator precedence rule in Python

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

Multiplication, Division, Floor division,


*, /, //, %
Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is,


Comparison, Identity, Membership operators
is not, in, not in
I B.SC CS

not Logical NOT

and Logical AND

or Logical OR

6. Input Operation
 To take input from the users, Python makes use of the input( ) function. Theinput(
) function prompts the user to provide some information on which theprogram can
work and give the result.
 However, we must always remember that the input function takes user‟s input
as a string.

Example:

7. Comments

 Comments are the non-executable statements in a program. They are just added
to describe the statements in the program code. 
 Comments make the program easily readable and understandable by the
programmer as well as other users who are seeing the code. The interpreter
simply ignores the comments. 
 In Python, a hash sign (#) that is not inside a string literal begins a comment. All
characters following the # and up to the end of the line are part of the comment
I B.SC CS

Example:

 Note: For writing Multi line comments. Make sure to indent the leading „ „
„ appropriately to avoid an Indentation Error
„„„

This is a multiline

comment.

„„„

8. Indentation
 Whitespace at the beginning of the line is called indentation. These whitespaces
or the indentation are very important in Python.
 In a Python program, the leading whitespace including spaces and tabs at the
beginning of the logical line determines the indentation level of that logical line. 

Example:

9. Expressions
 An expression is any legal combination of symbols (like variables, constants
and operators) that represents a value.
I B.SC CS

 In Python, an expression must have at least one operand (variable or constant)


and can have one or more operators. On evaluating an expression, we get a value.
Operand is the value on which operator is applied.
 Generally Expressions are divided into the following types
1. Constant Expressions: One that involves only constants.
Example: 8 + 9 – 2

2. Integral Expressions: One that produces an integer result after evaluating


the expression.
Example:a = 10

3. Floating Point Expressions: One that produces floating point results.


Example: a * b / 2.0

4. Relational Expressions: One that returns either true or false value.


Example: c = a>b

5. Logical Expressions: One that combines two or more relational expressions


and returns a value as True or False.
Example: a>b and y! = 0

6. Bitwise Expressions: One that manipulates data at bit level.


Example: x = y&z

7. Assignment Expressions: One that assigns a value to a variable.


Example: c = a + b or c = 10

Example Program:

Give the output for the following statements.( April 2018 Regular)

a = 20

b = 10

c = 15

d=5

print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))

e = (a + b) * c / d
I B.SC CS

print ("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d

print ("Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d)

print ("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d

print ("Value of a + (b * c) / d is ", e)

Output:

a:20 b:10 c:15 d:5

Value of (a + b) * c / d is 90.0

Value of ((a + b) * c) / d is 90.0

Value of (a + b) * (c / d) is 90.0

Value of a + (b * c) / d is 50.0

10.Type Conversion
 In Python, it is just not possible to complete certain operations that involves
different types of data.
 For example, it is not possible to perform "2" + 4 since one operand is an
integer and the other is of string type.
>>>”20” + “30” >>> int(“2”) + int(“3”)

Output Output

„2030‟ 5

 Another situation in which type conversion is must when we want to accept a


non string value(integer or float) as an input.we know that input function returns
string,so we must typecast the input to numbers to performcalculations on them.
 Example1:
x=input(“Enter the first number”)

y=input(“Enter the second number”)


I B.SC CS

print(x+y)

output

Enter the first number 6

Enter the second number 7

67

 Example2:
x=int(input(“Enter the firstnumber))

y=int(input(“Enterthesecondnumber))

print(x+y)

Output

Enterthefirstnumber6

Enterthesecondnumber7

13

 Python provides various built-in functions to convert value from one data type
to another datatype.The following are the functions return new object representing
the coverted value. Some of them are given in the following table.

print(str("The sum of two numbers is"))

print(str(num1)+"+"+str(num2)+"="+str(res))

Output:

Enter first number 10 12Type Casting vs Type Coercion


 we have done explicit conversion of a value from one data type to another. This
is known as type casting.
 However, in most of the programming languages including Python, there is an
I B.SC CS

implicit conversion of data types either during compilation or during run-time.


This is also known type coercion.
 For example, in an expression that has integer and floating point numbers (like
21 + 2.1 gives 23.1), the compiler will automatically convert the integer into
floating point number so that fractional part is not lost.
I B.SC CS

Assignment-Cum-Tutorial Questions
A. Objective Questions
1. Literal is of the form a+bj is called
2. Identify the words which describes Python [ ]
a)Interpreted b)simple c)reliable d)all of these

3. Python allows you to specify Unicode Text by prefixing the string with which
character [ ]
a) U b)R c)S d)A

4. Which of the following is a valid string literal [ ]


a)”computer” b)‟computer‟ c)‟‟‟computer‟‟‟ d) all of these

5. Which of this is valid variable name in Python [ ]


a) This is a variable b)This_is_a_variable c)This-is-a-variable d)^var

6. A Comments in python start with which symbol


7. All spaces and tabs with in a string are preserved in quotes [True/False]
8. Bitwise Operator can be applied on which data type [ ]
a)integer b)float c)string d)list

9. Identify valid assignment statements [ ]


a)=b+1 b)a=a+1 c)a+b=10 d)a+1=1

10. operator perform logical negation on each bit of the operand.


11. What should be written in the blank to generate ZeroDivisionError in the
case of (25+36)/(-8+ )
12. Predict the output of the following program [ ]
>>spam=”eggs”

>>print(spam*3)

a) spamspamspam b)eggseggseggs c)”spamspamspam” d)spam*3

13. Which of the following returns true [ ]


a)>>>9=9 and 1==1

b)>>>3==5 and 7==3


I B.SC CS

c)>>>7!=1 and 5==5

d)>>>4<1 and 1>6

14. Identify the valid numeric literals in Python [ ]


a)5678 b)5,678 c)5678.0 d)0.5678 e)0.56+10

15. You can print string without using print function


[True/False]
16. Predict the output of the following program [ ]
>>>print (format(56.78901,‟.3f‟))

a)56.789 b)5.6789 c)0.56789 d)56789

17. The following statement will produce lines of output [ ]


>>print(„Good\nMorning\nWorld\n---Bye‟)

a)1 b)2 c)3 d)4

18. Identify the correct arithmetic expression in python [ ]


a)11(12+13) b)(5*6)(7+8) c)4*(3-2) d)5***3

19. Which line of code produce error [ ]


a)”one”+”2” b)‟5‟+6 c)3+4 d)”7”+‟eight‟

20. Predict the output of the following program [ ]


>>>print(abs(10-20)*3)

a)-30 b)30 c)-50 d)none of these

B. Subjective Questions
1. Describe the features of Python
2. Differentiate between literals and variables in python.
3. What are literals? Explain with the help of suitable examples?
4. Explain the significance of Escape sequences with relevant examples
5. Write briefly about Data types in Python
6. Explain in detail about Membership and Identity Operators.
7. How can the ternary operator used in python?
I B.SC CS

8. Give the operator precedence in python.


9. Define Expression? Explain different types of Expressions supported by Python?
10. Differentiate string with slicing operator.
11. What is tuple? What are the different operations performed on tuple? Explain with
an example?
12. Write briefly about Type Conversion process in Python.Write the meaning for the
following.
str(x), chr(x), float(x), ord(x)(Momentum is calculated as, e=mc2, where m is the mass of
the object and c is the velocity. Write a Python program that accepts object‟s mass (in
kilograms) andvelocity (in meters per second) and displays its momentum.
13. a)Write a Python Program to convert temperature in Celsius to Fahrenheit
b) Write a Python Program to convert Fahrenheit to Celsius.

14. Write a Python program to calculate the area of triangle using Heron‟s formula

Hint:√𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)

15. Evaluate the following Expression


a) True and False

b) (100<0) and (100>20)

c) not(true) and false

d) not true and false or true

e) not(100<0 or 100>20)

f)100<0 and not 100>20

16. Give an appropriate boolean expression for the each of the following
a)check if variable v is greater than or equal to 0,and less than 10

b) check if variable v is less than 10 and greater than or equal to 0,or it is equal
to 20.

c) check if either the name „cse‟ or „it‟ appears in the list of names assigned to
variable last_names.
I B.SC CS

d) check if the name „cse‟ appears and the name „it‟does not appear in the list
of last name assigned to variable last_names.

17. Identify the datatype is best suitable to represent the following data values
a)Number of days in the year

b) The circumference of a rectangle

c) Yours father salary

d) Distance between moon and earth

e) Name of your best friend

f)Whether you go for the party

ooo
I B.SC CS

UNIT-II

Syllabus: Decision Control and Looping Statements


Control Statements:

 A control statement is a statement that determines the control flow of a set of


instructions, i.e., it decides the sequence in which the instructions in a program
are to be executed.

 Types of Control Statements —

 Selection/Conditional Control: To execute only a selected set of


statements.

 Iterative Control: To execute a set of statements repeatedly.

 Un-conditional Control:

1. Selection /Conditional Branching Statements:

 Python language supports different types of conditional branching statements


which are as follows:

 if Statement

 if-else Statement

 Nested if statement

 if-elif-else statement.

1. 1 if Statement:

 An if statement is a selection control statement which is based on the value


of a given Boolean Expression.

Syntax:

if test_expression:
statement 1

.....

statement n

statement x

 if structure may include 1 or n statements enclosed within if block.


 First, test expression is evaluated. If the test expression is true, the
statement of if block (statement 1 to n) are executed, otherwise these
statements will be skipped and the execution will jump to statement x.
I B.SC CS

Flow chart:

Example:

if else Statement:

 The if ...... else statement executes a group of statements when a test


expression is true; otherwise, it will execute another group of statements.

Syntax:

if (test expression):

statement_block 1

else:

statement_block 2

statement x

 If the condition is true, then it will execute statement block 1 and if the
condition is false then it will execute statement block 2.

Flowchart:

Example: Write a program to determine whether a person is eligible to vote:


I B.SC CS

Nested if Statements :

 A statement that contains other statements is called a compound statement.

 To perform more complex checks, if statements can be nested, that is, can
be placed one inside the other.

 In such a case, the inner if statement is the statement part of the outer one.

 Nested if statements are used to check if more than one conditions are
satisfied.

 if statements can be nested resulting in multi-way selection.

var = 100

if var < 200:

print( "Expression value is less than 200")

if var == 150:

print ("Which is 150‖)

elif var == 100:

print ("Which is 100")

elif var == 50:

print ("Which is 50")

elif var < 50:

print ("Expression value is less than 50")

else:

print ("Could not find true expression")

print ("Good bye!")


I B.SC CS

UNIT-2

Output:-

Expression value is less than 200

Which is 100

Good bye!

if-elif-else Statement :

 Python supports if-elif-else statements to test additional conditions apart


from the initial test expression.
 The if-elif-else construct works in the same way as a usual if-else statement.

 If-elif-else construct is also known as nested-if construct.

 A series of if and elif statements have a final else block, which is executed if
none of the if or elif expressions is True.

Syntax:

if (test expression 1):

statement block1

elif (test expression 2):

statement block2
. . . . . . . . . . . . . . ..

elif( test expression N):

statement block N

else:

statement block X
I B.SC CS

Flowchart:

Program: To test whether a number entered by the user is negative, positive, or zero

2. Looping Statements/Iterative Structure:

 Iterative statements are decision control statements that are used to repeat the
execution of a list of statements.

 Python supports 2 types of iterative statements-while loop and for loop.

while Loop :
 The While loop provides a mechanism to repeat one or more statements
while a particular condition is TRUE.

Syntax:

Statement x

while (condition):

Statement block

Statement y
I B.SC CS

UNIT-2

 In while loop, the condition is tested before any of the statements in the
statement block is executed.

 If the condition is TRUE, only then the statements will be executed


otherwise if the condition is False, the control will jump to statement y, that
is the immediate statement outside the while loop block.

Flowchart:

Example: Program to print first 10 numbers using a while loop

i=0

while(i<=10):

print(i, end=‖ ―)

i=i+1

Output: 0 1 2 3 4 5 6 7 8 9 10

for Loop:
 For loop provides a mechanism to repeat a task until a particular condition
is True. It is usually known as a determinate or definite loop because the
programmer knows exactly how many times the loop will repeat.

 The for...in statement is a looping statement used in Python to iterate over a


sequence of objects.

Syntax:

for loop_control_var in sequence:

statement block
I B.SC CS

Flowchart:

for Loop and range() Function :


o The range( ) function is a built-in function in Python that is used to iterate
over a sequence of numbers.

Syntax:

range(beg, end, [step])


o The range( ) produces a sequence of numbers starting with beg (inclusive)
and ending with one less than the number end.

o The step argument is option (that is why it is placed in brackets). By default,


every number in the range is incremented by 1 but we can specify a
different increment using step. It can be both negative and positive, but not
zero.

Example: Program to print first n numbers using the range() in a for loop

o If range( ) function is given a single argument, it produces an object with


values from 0 to argument-1. For example: range(10) is equal to writing
range(0, 10).
o If range( ) is called with two arguments, it produces values from the first to
the second. For example, range(0, 10) gives 0-9.
I B.SC CS

o If range( ) has three arguments then the third argument specifies the
interval of the sequence produced. In this case, the third argument must be
an integer. For example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16, 19.
Example:

1. Program that accepts an integer (n) and computes the value of n+nn+nnn.
(Eg. If n=5, find 5+55+555).

n = int(input("Enter a number: "))

str_n = str(n)

sum = n

sum_str = str(n)

for i in range(1, 3):

sum_str = sum_str + str_n

sum = sum + int(sum_str)

print(sum)

2. Program that accepts a word from the user and reverse it

s = input("Enter a word: ")

str = ""

for i in s:

str = i + str

print("Reverse of", s, "is:", str)

Nested Loops :

 Python allows its users to have nested loops, that is, loops that can be
placed inside other loops.
 Although this feature will work with any loop like while loop as well as for
loop.

 A for loop can be used to control the number of times a particular set of
statements will be executed.
I B.SC CS

 Another outer loop could be used to control the number of times that a
whole loop is repeated.

 Loops should be properly indented to identify which statements are


contained within each for statement.

Example:

1. Program to print the following pattern

2. Program to display multiplication tables from 1 to 10


for i in range(1, 11):

for j in range(1, 11):

print(i, '*', j, '=', i*j)

Condition-controlled and Counter-controlled Loops :

The Break Statement:


 The break statement is used to terminate the execution of the nearest
enclosing loop in which it appears.

 The break statement is widely used with for loop and while loop.

 When compiler encounters a break statement, the control passes to the


statement that follows the loop in which the break statement appears.

Syntax:
I B.SC CS

UNIT-2

Break

Example: Program to demonstrate the break statement

 Above code is meant to print first 10 numbers using a while loop, but it
will actually print only numbers from 0 to 4. As soon as i becomes equal to
5, the break statement is executed and the control jumps to the following
while loop.

 Hence, the break statement is used to exit a loop from any point with in its
body, by passing its normal termination expression. Below, Figure shows
the transfer of control when the break statement is encountered.

The Continue Statement:


 Like the break statement, the continue statement can only appear in the
body of a loop.
 When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally
transferred to the loop-continuation portion of the nearest enclosing loop.
I B.SC CS

UNIT-2

 Note that the code is meant to print numbers from 0 to 10.But as soon as i
becomes equal to 5, the continue statement is encountered, so rest of the
statements in the loop are skipped. In the output, 5 is missing as continue
caused early increment of i and skipping of statement that printed the value
of i on screen.

 Below figure illustrates the use of continue statement in loops.

 It can be concluded that the continue statement is somewhat the opposite of


the break statement. It forces the next iteration of the loop to take place,
skipping any code in between itself and the test condition of the loop.

 The continue statement is usually used to restart a statement sequence


when an error occurs.

The Pass Statement:


 Pass statement is used when a statement is required syntactically but no
command or code has to be executed.

 It specified a null operation or simply No Operation (NOP) statement.


Nothing happens when the pass statement is executed.

 The difference between a comment and pass statement is that while the
interpreter ignores a comment entirely, pass is not ignored.

 Comment is not executed but pass statement is executed but nothing


happens.
 Pass is a null statement.
I B.SC CS

UNIT-2

Example:

1. Program to demonstrate pass statement

Difference between break, continue and pass

 The break statement terminates the execution of the nearest enclosing loop
in which it appears.

 The continue statement skips the rest of the statements in the loop transfer
the control un-conditionally to the loop-continuation portion of the nearest
enclosing loop.

 The pass statement is a do-nothing statement in a loop. It is just added to


make the loop syntactically correct. i.e, a pass statement is written as we
can not have an empty body of the loop.

The Else Statement Used With Loops:


 In Python you can have the else statement associated with a loop
statements.
 If the else statement is used with a for loop, the else statement is executed
when the loop has completed iterating.
 But when used with the while loop, the else statement is executed when the
condition becomes false.
Examples:
I B.SC CS

UNIT-2

3. Programs:

3. 1 Write a python program to Test whether a given number is even or odd.

num = int(input("Enter a number: "))

if (num % 2==0):

print(num, "is an even number.")

else:

print(num, "is an odd number.")

Output:

Enter a number: 5

5 is an odd number.

3. 2 Write a python program to Print out the decimal equivalents of 1/1, 1/2, 1/3,
1/4 .......... 1/10 using for loop.

i=1

for i in range(1,11):

value=1.0/i
print("1/", i, "=", value)

Output:

1/ 1 = 1.0
1/ 2 = 0.5

1/ 3 = 0.333333333333

1/ 4 = 0.25

1/ 5 = 0.2

1/ 6 = 0.166666666667

1/ 7 = 0.142857142857

1/ 8 = 0.125

1/ 9 = 0.111111111111

1/ 10 = 0.1
I B.SC CS

)
UNIT-2

3. 3. Write a python program to Print a count down from the given number to zero
using a while loop.

num=int(input("Enter a number: "))

print("count down from ", num, "to 0 :")

while (num >= 0):

print(num)

num = num - 1

Output:

Enter a number: 6

count down from 6 to 0:


6

0
3.4. Write a python program to Find the sum of all the primes below hundred.

sum=0

for j in range(1,100):
for i in range(2,j):

if (j% i) == 0:

break

else:

sum=sum+j #where j is a prime number

print("Sum of prime numbers up to 100 is", sum)

utput:
Sum of prime numbers up to 100 is 1061
I B.SC CS

3. 5. Write a python program to find the factorial of a given number.

num=int(input("Enter a number: "))

fact=1

while (num>0):

fact=fact*num

num=num-1

print("Factorial of", num, "is",fact)

Output:

Enter a number: 6

Factorial of 6 is 720
I B.SC CS

Assignment-Cum-Tutorial Questions

A. Objective Questions

1. Python uses to form a block of code.

2. Which part of if statement should be indented [ ]

a) The first statement b) All the statements

c) Statements within the if block d)None of these

3. Which of the following is placed after the if condition [ ]

a) ; b) . c) : d) ,

4. elif and else blocks are optional [True/False]

5. How many lines will be printed by this code?

while False:
print(“hello”) [ ]

a) 1 b) 0 c) 10 d) countless

6. is a built-in function that is used to over a sequence of numbers.

7. Which statement is used to stop the current iteration of the loop and continue
with the next one? [ ]

a) pass b) break c)continue d)jump

8. Which statement is used to terminate the execution of the nearest enclosing


loop in which it appears? [ ]

a) pass b)break c)continue d)jump

9. Which statements indicates a NOP [ ]

a) pass b)break c)continue d)jump

10. It is possible to use ‗else suite‘ along with loops. [True/False]

11. x=100 [ ]

y=200

x>y

print (“in if”)


I B.SC CS

UNIT-2

print (“in else”)

a) if , else b) if ; else c)if : else : d) if | else

12. How many numbers will be printed? [ ]

i=5

while i>=0:

print(i)

i=i-1
a) 5 b) 6 c) 4 d)0

13. What is the output of the following code? [ ]

i=1

while true:

if i%3 == 0:

break

print(i)

i+=1

a) 1 2 b) 1 2 3 c) error d) none of the mentioned

14. What is the output of the following code? [ ]

for i in range(2.0):

print(i)

a) 0.0 1.0 b) 0 1
c) error d) none of the mentioned

15. What is the output of the following code? [ ]

for i in range(10):

if i == 5:

break

else:

print(i)
else:
I B.SC CS

print("here")

a) 0 1 2 3 4 here b) 0 1 2 3 4 5 here c) 0 1 2 3 4 d) 1 2 3 4 5

B. Descriptive Questions

1. Explain Conditional Statements in Python with examples.

2. Write syntax and logical flow for if-elif-else.

3. Explain the significance of for loop with else using an example.

4. Differentiate between counter-controlled loops and sentinel-controlled loops.

5. Write the differences between iteration and recursion.

6. Explain the utility of break and continue statements with the help of an
example.

7. What is pass statement in python?

8. Explain with an example, how continue statement is used in python.


9. Write a program to display multiplication tables from 1 to 10.

10. Write a Python program that accepts a word from the user and reverse it

11. Write a Python program that accepts an integer (n) and computes the value of
n+nn+nnn. (Eg. If n=5, find 5+55+555).

12. Write a program to find the factorial of a given number.


I B.SC CS

UNIT-3

Unit-III
Functions and Strings

Functions
 A function is a block of organized and reusable program code that performs a
single, specific, and well-defined task.
 Python enables its programmers to break up a program into functions, each of
which can be written more or less independently of the others. Therefore, the
code of one function is completely insulated from the codes of the other
functions.

Figure 1: Calling a function

 In figure 1 which explains how a function func1() is called to perform a well-


defined task. As soon as func1() is called, the program control is passed to the
first statement in the function. All the statements in the function are executed
and then the program control is passed to the statement following the one that
called the function.

Figure 2: Function calling another function


 In figure 2 func1() calls function named func2(). Therefore, func1() is known as
the calling function and func2() is known as the called function. The moment the
compiler encounters a function call, instead of executing the next statement in
the calling function, the control jumps to the statements that are a part of the
I B.SC CS

called function. After called function is executed, the control is returned back
to the calling program.
 It is not necessary that the func1() can call only one function, it can call as
many functions as it wants and as many times as it wants. For example, a
function call placed within for loop or while loop may call the same function
multiple times until the condition holds true.

Need for Functions:

Figure 3: Top-down approach of solving a problem


 Each function to be written and tested separately.
 Understanding, coding and testing multiple separate functions are far easier
than doing the same for one huge function.
 When a big program is broken into comparatively smaller functions, then
different programmers working on that project can divide the workload by
writing different functions.
 All the libraries in Python contain pre-defined and pre-tested functions which
the programmers are free to use directly in their programs, without worrying
about their code details. This speed up program development.
 Like Python libraries, programmers can also make their own functions and use
them from different points in the main program or any other program that
needs its functionalities. So code reuse is one of the most prominent reasons
to use functions.
Function Declaration and Definition:
• A function, f that uses another function g, is known as the calling function and g is
known as the called function.
I B.SC CS

• The inputs that the function takes are known as arguments/parameters.


• When a called function returns some result back to the calling function, it is said to
return that result.
• The calling function may or may not pass parameters to the called function. If the
called function accepts arguments, the calling function will pass parameters, else
not.
• Function declaration is a declaration statement that identifies a function with its
name, a list of arguments that it accepts and the type of data it returns.
• Function definition consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function.
Function Definition
There are two basic types of functions
1. built-in functions eg: dir(), len(), abs() etc.,
2. user defined functions.
 Function blocks starts with the keyword def.
 The keyword is followed by the function name and parentheses (( )).
 After the parentheses a colon (:) is placed.
 Parameters or arguments that the function accept are placed within
parentheses.
 The first statement of a function can be an optional statement - the
docstringdescribe what the function does.
 The code block within the function is properly indented to form the block code.
 A function may have a return[expression] statement. That is, the return
statement is optional.
 You can assign the function name to a variable. Doing this will allow you to call
same function using the name of that variable.
I B.SC CS

Figure 4: Program that subtracts two numbers using a function.

Figure 5: The syntax of a function definition.


Function Call
 Defining a function means specifying its name, parameters that are
expected, and the set of instructions.
 The function call statement invokes the function. When a function is
invoked the program control jumps to the called function to execute the
statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function.
Function Parameters
 A function can take parameters which are nothing but some values that are
passed to it so that the function can manipulate them to produce the desired
result. These parameters are normal variables with a small difference that the
values of these variables are defined (initialized) when we call the function and
are then passed to the function.
 Function name and the number and type of arguments in the function call
must be same as that given in the function definition.
 If the data type of the argument passed does not matches with that expected in
function then an error is generated.
I B.SC CS

)
UNIT-3

Figure 6: a function that displays string repeatedly.

Figure 7: Program to demonstrate mismatch of name of function parameters and


arguments.
Note: Names of variables in function call and header of function definition may vary.

Figure 8: Arguments may be passed in the form of expressions to the called function.

Figure 9: Program to add two integers using functions


I B.SC CS

Variable scope and lifetime:


In python, you cannot just access any variable from any part of your program. Some
of the variables may not even exist for the entire duration of the program. In which
part of the program you can access a variable and in which parts of the program a
variable exits depends on how the variable has been declared. Therefore, we need to
understand these two things:
1. Scope of the variable: Part of the program in which a variable is accessible is called
its scope.
2. Lifetime of the variable: Duration for which the variable exits it‟s called its lifetime.
Local and Global variables:
A variable which is defined within a function is local to that function. A local variable
can be accessed from the point of its definition until the end of the function in which
it is defined. It exists as long as the function is executing. Function parameters behave
like local variables in the function. Moreover, whenever we use the assignment
operator (=) inside a function, a new local variable is created.
Global variables are those variables which are defined in the main body of the program
file. They are visible throughout the program file. As a good programming habit, you
must try to avoid the use of global variables because they may get alteredby mistake
and then result in erroneous output.

Figure 10: lists the differences between global and local variables.
I B.SC CS

Comparison between global and local variables


Global variables Local variables
They are defined in the main body of They are defined within a function and
the program file. is local to that function.
They can be accessed throughout the They can be accessed from the point of
program life. its definition until the end of the block
in which it is defined.
Global variables are accessible to all They are not related in any way to
functions in the program. other variables with the same names
used outside the function.

Using the Global Statement


To define a variable defined inside a function as global, you must use the global
statement. This declares the local or the inner variable of the function to have module
scope.
Key points to remember:
You can have a variable with the same name as that of a global variable in the
program. In such a case a new local variable of that name is created which is
different from the global variable.

Figure 11: Program to demonstrate the use of global statement.


I B.SC CS

Resolution of names
Scope defines the visibility of a name within a block. If a local variable is defined in a
block, its scope is that particular block. If it is defined in a function, then its scope is all
blocks within that function.
When a variable name is used in a code block, it is resolved using the nearest
enclosing scope. If no variable of that name is found, then a NameError is raised. In
the code given below, str is a global string because it has been defined before calling
the function.

Figure 12: Program that demonstrates using a variable defined in global namespace.
The Return Statement
The syntax of return statement is,
return [expression]
The expression is written in brackets because it is optional. If the expression is
present, it is evaluated and the resultant value is returned to the calling function.
However, if no expression is specified then the function will return none.
The return statement is used for two things.
• Return a value to the caller
• To end and exit a function and go back to its caller

Figure 13: Program to write another function which returns an integer to the caller.
More on defining functions:
In this section we will discuss some more ways of defining a function.
1. Required arguments
I B.SC CS

2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
In the required arguments, the arguments are passed to a function in correct
positional order. Also, the number of arguments in the function call should exactly
match with the number of arguments specified in the function definition
Example:

Keyword Arguments
When we call a function with some values, the values are assigned to the arguments
based on their position. Python also allow functions to be called using keyword
arguments in which the order (or position) of the arguments can be changed. The
values are not assigned to arguments according to their position but based on their
name (or keyword).
Keyword arguments are beneficial in two cases.
• First, if you skip arguments.
• Second, if in the function call you change the order of parameters.
Example:

Default Arguments
Python allows users to specify function arguments that can have default values. This
means that a function can be called with fewer arguments than it is defined to have.
I B.SC CS

That is, if the function accepts three parameters, but function call provides only two
arguments, then the third parameter will be assigned the default (already specified)
value. The default value to an argument is provided by using the assignment operator
(=). Users can specify adefault value for one or more arguments.
Example:

Variable-length Arguments
In some situations, it is not known in advance how many arguments will be passed to
a function. In such cases, Python allows programmers to make function calls with
arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable length arguments, then the function
definition use an asterisk (*) before the parameter name. The syntax for a function
using variable arguments can be given as,

Example:

Lambda Functions or Anonymous Functions


Lambda or anonymous functions are so called because they are not declared as other
functions using the def keyword. Rather, they are created using the lambda keyword.
I B.SC CS

Lambda functions are throw-away functions, i.e. they are just needed where they
have been created and can be used anywhere a function is required. The lambda
feature was added to Python due to the demand from LISP programmers.
Lambda functions contain only a single line. Its syntax can be given as,

Example

Documentation Strings
Docstrings (documentation strings) serve the same purpose as that of comments, as
they are designed to explain code. However, they are more specific and have a proper
syntax.

Example:

Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller version
of its task until a final call is made which does not require a call to itself. Every
recursive solution has two major cases, which are as follows:
• base case, in which the problem is simple enough to be solved directly without
making any further calls to the same function.
• recursive case, in which first the problem at hand is divided into simpler sub parts.
Recursion utilized divide and conquer technique of problem solving.
I B.SC CS

Example:

Recursion vs Iteration:
Recursion is more of a top-down approach to problem solving in while the original
problem is divided into smaller sub-problems.
Iteration follows a bottom-up approach that begins with what is known and then
constructing the solution step-by-step.
Pros The benefits of using a recursive program are:
 Recursive solutions often tend to be shorter and simpler than non-recursive
ones.
 Code is clearer and easier to use.
 Recursion uses the original formula to solve a problem.
 It follows a divide and conquer technique to solve problems.
 In some instances, recursion may be more efficient.
Cons The limitations of using a recursive program are:
 For some programmers and readers, recursion is difficult concept.
 Recursion is implemented using system stack. If the stack space on the system
is limited, recursion to a deeper level will be difficult to implement.
 Aborting a recursive process in midstream is slow and sometimes nasty.
 Using a recursive function takes more memory and time to execute as
compared to its non-recursive counterpart.
 It is difficult to find bugs, particularly when using global variables.
Conclusion: The advantages of recursion pays off for the extra overhead involved in
terms of time and space required.
Modules
 We have seen that functions help us to reuse a particular piece of code.
Module goes a step ahead. It allows you to reuse one or more functions in your
I B.SC CS

programs, even in the programs in which those functions have not been
defined.
 Putting simply, module is a file with a.py extension that has definitions of all
functions and variables that you would like to use even in other programs. The
program in which you want to use functions or variables defined in the module
will simply import that particular module (or .py file).
 Modules are pre-written pieces of code that are used to perform common tasks
like generating random numbers, performing mathematical operations, etc.
 The basic way to use a module is to add import module_name as the first line
of your program and then writing module_name.var to access functions and
values with the name var in the module.
The from…import Statement
A module may contain definition for many variables and functions. When you import
a module, you can use any variable or function defined in that module. But if you
want to use only selected variables or functions, then you can use the from...import
statement. For example, in the aforementioned program you are using only the path
variable in the sys module, so you could have better written from sys import path.
Example:

To import more than one item from a module, use a comma separated list. For
example, to import the value of pi and sqrt() from the math module you can write,

Making your own Modules


Every Python program is a module, that is, every file that you save as .py extension is
a module.
 Modules should be placed in the same directory as that of the program in which
it is imported. It can also be stored in one of the directories listed in sys.path.
I B.SC CS

The dir() function


dir() is a built-in function that lists the identifiers defined in a module. These
identifiers may include functions, classes and variables. If no name is specified, the
dir() will return the list of names defined in the current module.
Example: demonstrate the use of dir() function.

The Python Module:


 We have seen that a Python module is a file that contains some definitions and
statements. When a Python file is executed directly, it is considered the main
module of a program.
 Main modules are given the special name main and provide the basis for a
complete Python program.
 The main module may import any number of other modules which may in turn
import other modules. But the main module of a Python program cannot be
imported into other modules.
Modules and Namespaces
I B.SC CS

A namespace is a container that provides a named context for identifiers. Two


identifiers with the same name in the same scope will lead to a name clash. In simple
terms, Python does not allow programmers to have two different identifiers with the
same name. However, in some situations we need to have same name identifiers. To
cater to such situations, namespaces is the keyword. Namespaces enable programs
to avoid potential name clashes by associating each identifier with the namespace
from which it originates.
Example:

Local, Global, and Built-in Namespaces


During a program‟s execution, there are three main namespaces that are referenced-
the built-in namespace, the global namespace, and the local namespace. The built-in
namespace, as the name suggests contains names of all the built-in functions,
constants, etc that are already defined in Python. The global namespace contains
identifiers of the currently executing module and the local namespace has identifiers
defined in the currently executing function (if any).
When the Python interpreter sees an identifier, it first searches the local namespace,
then the global namespace, and finally the built-in namespace. Therefore, if two
identifiers with same name are defined in more than one of these namespaces, it
becomes masked.
Example: Program to demonstrate name clashes in different namespaces.
I B.SC CS

Module Private Variables


 In Python, all identifiers defined in a module are public by default. This means
that all identifiers are accessible by any other module that imports it. But, if
you want some variables or functions in a module to be privately used within
the module, but not to be accessed from outside it, then you need to declare
those identifiers as private.
 In Python identifiers whose name starts with two underscores ( ) are known
as private identifiers. These identifiers can be used only within the module. In
no way, they can be accessed from outside the module.
 Therefore, when the module is imported using the import * form modulename,
all the identifiers of a module‟s namespace is imported except the private ones
(ones beginning with double underscores). Thus, private identifiers become
inaccessible from within the importing module.
Advantages of Modules:
 Python modules provide all the benefits of modular software design. These
modules provide services and functionality that can be reused in other
programs.
 Even the standard library of Python contains a set of modules. It allows you to
logically organize the code so that it becomes easier to understand and use.
Programs:
I B.SC CS

1. Write a function cumulative product to compute cumulative product of a list of


numbers.
Program:
def cumulative_product():
list=[1,2,3,4]
prod=1
for i in list:
prod=prod*i
print prod
cumulative_product()
Output:

2. Write function to compute gcd, lcm of two numbers. Each function shouldn‟t
exceed one line.
Program:
from fractions import gcd
print gcd(5,25)
def lcm():
a=60
b=40
print (a * b) // gcd(a, b)
lcm()
output:
I B.SC CS

3. Find the sum of the even-valued terms in the Fibonacci sequence whose values do
not exceed ten thousand.
program:
i=0
j=1
sum=0
while(i<10000):
i=i+j
j=i-j
if(i%2==0):
sum+=i
print sum

output:
I B.SC CS

Strings

 Python treats strings as contiguous series of characters delimited by single,


double or even triple quotes. Python has a built-in string class named "str" that
has many useful features. We can simultaneously declare and define a string by
creating a variable of string type. This can be done in several ways which are as
follows:
 name = "India" graduate = 'N' country = name nationality = str("Indian")

 Indexing: Individual characters in a string are accessed using the subscript ([ ])


operator. The expression in brackets is called an index. The index specifies a
member of an ordered set and in this case it specifies the character we want to
access from the given set of characters in the string.
 The index of the first character is 0 and that of the last character is n-1 where n is
the number of characters in the string. If you try to exceed the bounds (below 0 or
above n-1), then an error is raised.
 Traversing a String: A string can be traversed by accessing character(s) from one
index to another. For example, the following program uses indexing to traverse a
string from first character to the last.
Example:

Concatenating, Appending and Multiplying Strings


Example: Program to concatenate two strings using + operator
I B.SC CS

Example: Program to repeat a string using * operator

Example: Program to append a string using += operator

Strings are Immutable


Python strings are immutable which means that once created they cannot be
changed. Whenever you try to modify an existing string variable, a new string is
created.
Example:
I B.SC CS

String Formatting Operator


 The % operator takes a format string on the left (that has %d, %s, etc) and the
corresponding values in a tuple on the right. The format operator, % allow
users to construct strings, replacing parts of the strings with the data stored in
variables. The syntax for the string formatting operation is:
 "<Format>" % (<Values>)
Example:
I B.SC CS

Built-in String Methods and Functions


I B.SC CS

Programs:
1. Write a program that accepts a string from a user and re-displays the same after
removing vowels from it.
Program:
while True:
print('Enter x for exit.')
string = raw_input('Enter any string: ')
if string == 'x':
break
else:
newstr = string
print("\nRemoving vowels from the given string...")
I B.SC CS

vowels = ('a', 'e', 'i', 'o', 'u')


for x in string.lower():
if x in vowels:
newstr = newstr.replace(x,"")
print("New string after successfully removing all vowels!")
print(newstr,"\n")
output:

2. Write a program to calculate the length of a string.


Program:
string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
I B.SC CS

output:

3. Write a function to reverse a given string.


Program:
def reverse(text):
lst = []
count = 1
for i in range(0,len(text)):
lst.append(text[len(text)-count])
count += 1
lst = ''.join(lst)
return lst
print reverse('Python Programming')

output:
I B.SC CS

Assignment-Cum-Tutorial Questions

A) Objective Questions
1. User-defined functions are created by using the keyword.

2. The is used to uniquely identify the function.

3. The return statement is optional [Yes/No]

4. DRY principle makes the code [ ]

a) Reusable b) Loop forever c)Bad and repetitive d) Complex

5. of a variable determines the part of the program in which it is accessible


[ ]

a) Scopeb) Lifetime c) Data Type d) Value

6. Arbitrary arguments have which symbol in the function definition before the
parameter name? [ ]

a) & b) # c) % d) *

7. dir() is built-in function that lists the identifiers defined in a module.

8. Arguments may be passed in the form of expressions to the called function


[yes/No]

9. In Python a string is appended to another string by using which operator? [ ]

a) + b)* c)[] d)+=

10. Which error is generated when a character in a string variable is modified? [ ]

a) IndexError b) NameError c) TypeError d)BoundError

11. The code will print how many numbers? [ ]

def display(x):

fori in range(x):

print(i)

return

display(10)

a) 0 b) 1 c) 9 d) 10
I B.SC CS

12. How many times will the print() execute in the code given below? [ ]

def display():

print(„a‟)

print(„b‟)

return

print(„c‟)

print(„d‟)

a) 1 b) 2 c) 3 d)4

13. What is the output of this code? [ ]

import random as r

print(random.randomint(1,10))

a) An error occurs b) 1 c) 10 d) any random value.

14. Identify the correct way of calling a function named display() that prints Hello on
the screen.

a) print(display) b) displayHello [ ]

c) result = display() d) displayHello()

15. Find the error in following Python code. [ ]

Def func():

Print(“Hello world”)

a) Hello world b) “Hello world” c) no function call d) none of the above


16. Find the output of the following Python code. [ ]

deffunc(var):

var+=1

var *=2

print(var)

func(9)
I B.SC CS

print(var)

a) 20 20 b) 20 c) 9 d) 20'var' is not defined

17. Find the output in following Python code. [ ]

Def func():

global x

print(“x=”,x)

x=100

print(„x is now = „,x)

x=10

func()

print(„x =‟,x)

a) 100 10 100 b) 100 10 10

c) NameError: name 'x' is not defined d) Error 100 10

18. Find the output in following Python code. [ ]

def display(name, deptt, sal):

print(“Name:”, name)

print(“Department: “, deptt)

print(“Salary: “, sal)

display (sal = 100000, name=”Tavisha”, deptt = “sales”)

display (deptt = “HR”, name=”Dev”, sal = 50000)

a) Name: Tavisha c) Name: Tavisha


Department: sales Department: sales

Salary: 100000 Salary: 100000

Name: Dev Sequence Error:

Department: HR

Salary: 50000
I B.SC CS

b) Name: Tavisha d) Indentation Error:


Department: sales

Salary: 100000

Department: HR

Name: Dev

Salary: 50000

19. “Cool” become “COOL”, which two functions must have been applied?[ ]

a) strip() and upper() b) strip() and lower()

c) strip() and capitalize() d) lstrip() and rstrip()

20. Find the error in following Python code. [ ]

str = “Hello world”

str[6] = „w‟

print(str)

a) Hello world c) in line 2 use double quotes


b) 'str' object does not support item assignment d) Hello wworld
B) Subjective Questions
1. Define function and give its advantages.
2. Differentiate between local and global variables.
3. What are modules? How do you use them in your programs?
4. Write short notes on
a) Keyword arguments
b) Default arguments
5. What are docstrings?
6. Write short note on format operator.
7. With the help of an example, explain how we can create string variables in
Python.
8. What are user-defined functions? Explain with the help of example.
9. Briefly describe String formatting operator with an example.
10. List out Advantages and disadvantages of Recursion.
11. Write a python program to find the factorial of a given number using
recursion.
12. Write any 5 Built-in string methods and functions usage and example.
I B.SC CS

Unit-4 Tuples and Lists

Tuple Definition:

1. A tuple is a sequence of immutable objects. That is, you can change the value of
one or more items in a list; you cannot change the values in a tuple.

2. Tuples use parenthesis to define its elements. Whereas lists use square brackets.

Creating a Tuple:

Creating a tuple is as simple as putting different comma-separated values. Optionally


you can put these comma-separated values between parentheses.

Syntax: Tup1=(val1,val2,….)

Where val (or values) can be an integer, a floating number, a character, or a string.

Examples:

1) Tup1=( ) #creates an empty tuple.


print(Tup1)

output:

note: no ouput will be displayed.

2) Tup1=(5) #creates a tuple with single element


print(Tup1)

Output:

3) Tup1=(1,2,3,4,5) #creates a tuple of integers


print (Tup1)

Tup2=(„a‟,‟b‟,‟c‟,‟d‟) #creates a tuple of characters

print(Tup2)
I B.SC CS

Tup3=(“abc”,”def”,”ghi”) #creates a tuple of strings

print(Tup3)

Tup4=(1.2,2.3,3.4,4.5,5.6) #creates a tuple of floating point numbers

print(Tup4)

Tup5=(1,”abc”,2.3,‟d‟) #creates a tuple of mixed values

print(Tup5)

Output:

1,2,3,4,5

„a‟,‟b‟,‟c‟,‟d‟

„abc‟,‟def‟,‟ghi‟

1.2,2.3,3.4,4.5,5.6

1,‟abc‟,2.3,‟d‟

4) A Tuple with parenthesis


print(„a‟,”bcd”,2,4.6)

Output:

A bcd2 4.6

5) Default Tuple without parenthesis


a,b=10,20

print(a,b)

Output:

10 20
I B.SC CS

Accessing values of tuples:

 Like strings and lists tuples indices also starts with 0.


 The operations performed are slice, concatenate etc.,
 To access values in tuple, slice operation is used along with the index.

Example :

1) Tup1=(1,2,3,4,5,6,7,8,9,10)

print(“Tup[3:6]=”,Tup1[3:6])

print(“Tup[:8]=”,Tup1[:4])

print(“Tup[4:]=”,Tup1[4:])

print(“Tup[:]=”,Tup1[:])

Output:

Tup[3:6]=(4,5,6)

Tup[:8]=(1,2,3,4)

Tup[4:]=5,6,7,8,9,10)

Tup[:]=(1,2,3,4,5,6,7,8,9,10)

The tuple values can be accessed using square brackets:

2) Tuple =(1,2,3,4,5.5,‟str‟)

Input:

1. print tuple

2.print tuple[5]

3.print tuple[1:5]
I B.SC CS

Output:

1.1,2,3,4,5.5,‟str‟

2. ‟str‟

3.2,3,4,5.5

Updating tuples:

As we all know tuples are immutable objects so we cannot update the values but we
can just extract the values from a tuple to form another tuple.

Example:

1) Tup1=(1,2,3,4,5)
Tup2=(6,7,8,9,10)

Tup3=Tup1+Tup2

print(Tup3)

Output:

(1,2,3,4,5,6,7,8,9,10)

2) Tup1=(1,2,3,4,5)

Tup2=(„sree‟,‟vidya‟,‟ram‟)

Tup3=Tup1+Tup2

print Tup3

Output:

(1,2,3,4,5,‟sree‟,‟vidya‟,‟ram‟)
I B.SC CS

Deleting elements of a tuple:

1. Deleting a single element in a tuple is not possible as we know tuple is a immutable


object.

Hence there is another option to delete a single element of a tuple i.e..,you can create
a new tuple that has all elements in your tuple except the ones you don‟t want.

Example:

1) Tup1=(1,2,3,4,5)

del Tup1[3]

print Tup1

Output:

Traceback (most recent call last):


File "test.py", line 9, in <module>

del Tup1[3]

Type error: „tuple‟ object doesn‟t support item deletion

2) however, you can always delete the entire tuple by using del statement.

Tup1=(1,2,3,4,5)

del Tup1

print Tup1

Output:

Traceback (most recent call last):


File "test.py", line 9, in <module>
print Tup1;
NameError: name 'Tup1' is not defined
I B.SC CS

Key Note: Note that exception is raised because you are now trying to print a tuple
that has already been deleted.

Basic tuple operations:

Like strings and lists,you can also perform operations like concatenation,
repetition,etc. on tuples. The only difference is that a new tuple should be created
when a change is required in an existing tuple.

Operation Expression Output

Length len((1,2,3,4,5,6)) 6

Concatenation (1,2,3)+(4,5,6) (1,2,3,4,5,6)

Repetition („Good..‟)*3 „Good ..Good..Good‟

Membership 5 in (1,2,3,4,5,6,7,8,9) True

Iteration for i in 1,2,3,4,5,6,7,8,910


(1,2,3,4,5,6,7,8,9,10):

print(i,end=‟ „)

Comparision(Use >,<,==) Tup1=(1,2,3,4,5) False

Tup2=(1,2,3,4,5)

print(Tup1>Tup2)

Maximum max(1,0,3,8,2,9) 9

Minimum min(1,0,3,8,2,9) 0

Convert to tuple(converts tuple(“Hello”) („H‟,‟e‟,‟l‟,‟l‟,‟o‟)


a sequence into a tuple)
tuple([1,2,3,4,5]) (1,2,3,4,5)

Sorting( The sorted( ) t=(4,67,9) [4, 9, 67]


function takes elements
I B.SC CS

in a tuple and returns a sorted(t)


new sorted list (does not
sort the tuple itself)).

1) Length of the tuple:

Ex:

Input:

Tup1= (1,2,3,4,5)

print len (Tup1)

Output:

2) Concatenation:

Ex:

Input:

Tup1=(1,2,3,4)

Tup2=(5,6,7)

print tup1+tup2

Output:

(1,2,3,4,5,6,7)

3) Repetition:

Ex:

Input:

Tuple1=(„my‟)
I B.SC CS

print tuple1*3

Output:

(„my‟,‟my‟,‟my‟)

4) Membership:

Ex:

Input:

Tuple1=(1,2,3,4,6,7)

5) Iteration:

Ex:

Input:

For i in (1,2,3,4,5,6,7,8,9,10):

print (i,end=‟ „)

Output:

1,2,3,4,5,6,7,8,9,10

6) Comparison:

Ex:

Input:

Tup1 = (1,2,3,4,5)

Tup2 =(6,7,8,9,10)

print(Tup1<tup2)

Output:
I B.SC CS

True

7) Maximum:

Ex:

Input:

Max(1,2,6,5,4)

Output:

8) Minimum:

Ex:

Input:

Min(1,2,3,4,5)

Output:

9) Convert to tuple:

Ex:

Input:

Tuple(“vidya”)

Output:

(„v‟,‟i‟,‟d‟,‟y‟,‟a‟)
I B.SC CS

LISTS

The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero, the second
index is one, and so forth. There are certain things you can do with all sequence types.
These operations include indexing, slicing, adding, multiplying, and checking for
membership.

Creating a List:

Creating a list is as simple as putting different comma-separated values


between square brackets. Similar to string indices, list indices start at 0, and lists
can be sliced, concatenated and so on.

Syntax:

List_variable = [val1,val2,…]

Example:

1) list_A =[1,2,3,4]
print(list_A)

Output

[1,2,3,4]

2) list_C=[„Good”,”Going”]
print(list_C)

Output

[‘Good’,’Going’]

Accessing values in lists:

 Similar to strings, lists can be sliced and concatenated.


 To access values in lists, square brackets are used to slice along with index or
indices to get value stored at that index.
I B.SC CS

 syntax

s=list[start:stop:step]

For Example:

Seq=List[::2] # get every other element, starting with index 0.

Seq=List[1::2] # get every other element, starting with index 1.

Example 1:

num_list=[1,2,3,4,5,6,7,8,9,10]

print(“num_list is:”,num_list)

print(“first elemnent in the list is”,num_list[0])

print(“num_list[2:5]=”,num_list[2:5])

print(“num_list[::2]=”,num_list[::2])

print(“num_list[1::3]=”,num_list[1::3])

Output:

num_list is: [1,2,3,4,5,6,7,8,9,10]

first elemnent in the list is 1

num_list[2:5]= [3,4,5]

num_list[::2]= [1,3,5,7,9]

num_list[1::3]= [2,5,8]

Updating values in the lists:

 once created, one or more elements of a list can be easily updated by giving the
slice on the left-hand side of the assignment operator.
I B.SC CS

 You can also append new values in the list and remove existing values from the
list using the append( ) method and del statement respectively.

Example:

1) num_list= [1,2,3,4,5,6,7,8,9,10]
print(“list is:”,num_list)

num_list[5]=100

print(“List after updation is:”,num_list)

num_list.append(200)

print(“List after appending a value is: “,num_list)

del num_list[3]

print(“List after deleting a value is:”,num_list)

Output:

list is: [1,2,3,4,5,6,7,8,9,10]

List after updation is: [1,2,3,4,5,100,7,8,9,10]

List after appending a value is: [1,2,3,4,5,100,7,8,9,10,200]

List after deleting a value is: [1,2,3,5,100,7,8,9,10,200]

Basic list operations:

Operatio Description Example Output


n

len Returns length of list len([1,2,3,4,5,6,7,8,9,1 10


0])

concatena Joins two lists [1,2,3,4,5]+[6,7,8,9,10] [1,2,3,4,5,6,7,8,9,10]


I B.SC CS

tion

repetition Repeats elements in the “Hello”,”World”*2 [„Hello‟,‟World‟,‟Hello‟


lists ,‟World‟]

in Checks if the value is „a‟ in[„a‟,‟e‟,‟i‟,‟o‟,‟u‟] True


present in the list

not in Checks if the value is not 3 not in [0,2,4,6,8] True


present in the list

max Returns maximum value num_list=[6,3,7,0,1,2, 9


in the list 4,9]

print(max(num_list))

min Returns minimum value num_list=[6,3,7,0,1,2, 0


in the list 4,9]

print(min(num_list))

sum Adds the values in the num_list=[1,2,3,4,5,6, SUM=55


list that has numbers 7,8,9,10]

print(“SUM=”,sum(nu
m_list))

all Returns True if all num_list=[0,1,2,3] False


elements of the list are
print(all(num_list))
true(or if the list is
empty)

any Returns True if any num_list=[6,3,7,0,1,2, True


element of the list is 4,9]
true. if the list is empty
print(any(num_list))
return false
I B.SC CS

list Converts list1=list(“HELLO”) [„H‟,‟E‟,‟L‟,‟L‟,‟O‟]


iterable(tuple,string,set,d
print(list1)
ictionary)

sorted Returns a new sorted list1=[3,4,1,2,7,8] [1,2,3,4,7,8]


list. The original list not
list2=sorted(list1)
sorted
print(list2)

Mutability of lists:

 Unlike strings, lists are mutable.


 This means we can change an item 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,
we can update one of the list items.

Example:

fruit = ["banana", "apple", "cherry"]

print(fruit)

fruit[0] = "pear"

fruit[-1] = "orange"

print(fruit)

Output:
I B.SC CS

Functional Programming:

Functional Programming decomposes a problem into a set of functions. The


map(),filter(), and reduce() functions.

1) map( ) Function:
The map() function applies a particular function to every element of a
list.

Syntax:

map(function,sequence)

After applying the specified function in the sequence, the map( ) function
returns the modified list.

Ex: Program that adds 2 to every value in the list.

def add_2(x):

x+=2

return x

num_list=[1,2,3,4,5,6,7]

print(“original list is:”,num_list)

new_list=list(map(add_2,num_list))

print(“modified list is:”,new_list)

output:

original list is: [1,2,3,4,5,6,7]

modified list is:[3,4,5,6,7,8,9]

2) reduce ( ):
I B.SC CS

The reduce( ) function with syntax as given below returns a single value
generated by calling the function on the first two items of the sequence, then
on the result and the next item and so on.

Syntax: reduce(function,sequence)

Ex: Program to calculate the sum of values in a list using the reduce( )
function.

import functools # functools is a module that contains the function


reduce( )

def add(x,y):

return x+y

num_list=[1,2,3,4,5]

print(“sum of values in list=”)

print(functools.reduce(add,num_list))

Output:

sum of values in list= 15

3) filter( ) function:
It constructs a list from those elements of the list for which a function
returns True.

Syntax:

filter(function,sequence)

As per the syntax filter( ) function returns a sequence that contains items from
the sequence for which the function is True. If sequence is a string, Unicode, or a
tuple, then the result will be the same type;
I B.SC CS

Ex: Program to create a list of numbers divisible by 2 or 4 using list


comprehension.

def check(x):

if(x%2==0 or x%4 ==0):

return 1

#call check( ) for every value between 2 to 21

evens=list(filter(check,range(2,22))

print(evens)

Output:

[2,4,6,8,10,12,14,16,18,20]

programs:

1. Write a program to swap two values using Tuple assignments.

Program: (val1,val2,val3)=(1,2,3)

(tup1,tup2,tup3)=(4,5,6)

(a,b,c)=(val1,val2,val3)

(val1,val2,val3)=(tup1,tup2,tup3)

(tup1,tup2,tup3)=(a,b,c)

print (val1,val2,val3)

print (tup1,tup2,tup3)

Output:

(4, 5, 6)

(1, 2, 3)
I B.SC CS

2. Write a program to sort a Tuple of values.

Program: tup=[5,1,40,8,6,2,1]

print(sorted(tup))

Output:

[1, 1, 2, 5, 6, 8, 40]

3. Write program that scans an email address and forms a tuple of user name and
domain name.

Program:
addr =input('Enter email address:')
(uname, domain) = addr.split('@')
print('Username:',uname)
print('domain name:',domain)

Output:

Enter email address:gec@gmail.com


Username: gec
domain name: gmail.com

4. Write a program to print sum and average of the elements present in the list.

Program:

lst = [ ]

num = int(input('How many numbers: '))

for n in range(num):

numbers = int(input('Enter number '))


I B.SC CS

lst.append(numbers)

print("Sum of elements in given list is :", sum(lst))

avg=sum(lst)/num

print(avg)

Output:

How many numbers: 7

Enter number 1

Enter number 2

Enter number 3

Enter number 4
Enter number 5
Enter number 6
Enter number 7
Sum of elements in given list is : 28

5. Write a program that forms a list of first character of every word present in another
list.
Program:

b= [ ]

l= ["gudlavalleru","engineering","college"]

for item in l:

b.append(item[0])

print(b)

Output: [„g‟,‟e‟,‟c‟]
I B.SC CS

Assignment-Cum-Tutorial Questions

A) Objective Questions

1. If list=[1,2,3,4,5] then the list[5] will result in-------------------- [ ]


(a) 4 (b) 3 (c) 2 (d) Index Error
2. If List=[1,2,3,4,5] and rewrite List[3]=List[1], then what will be the List[3][ ]
(a) 1 (b) 3 (c) 2 (d) 4
3. In lists index value starts from Zero. [True/False] [ ]
4. print len((1,2,3,4,5,6)) is [ ]
(a) 5 (b) 6 (c) 21 (d) 7
5. Tuple is immutable and list is mutable. [True/False]
6. It is possible to add, edit, and delete elements from a list. [True/False]
7. list=['a','b','c','d','e'] output for print list[2:5] = ['c', 'd', 'e'].
8. tuple=('abcd',23,2.4,1)
print tuple[:3] what is the output? [ ]
a) ('abcd',23,2.4) b) (1) c) (23,2.4,1) d) ('abcd',23,2.4,1)
9. what is the output of print tuple[2:] if tuple=('abcd',786,2.23,1,2) [ ]
a) (cd,786,2.23,1,2) b) (2.23,1,2) c) (786,2.23,1,2) d) (1,2)
10. Suppose t = (1, 2, 4, 3), which of the following is incorrect? [ ]
a) print(t[3]) b) t[3] = 45
c) print(max(t)) d) print(len(t))
11. What is the output of the program: [ ]
for fruit in ['apple','banana','mango']:
print("I like",fruit)
a) [apple‟,‟banana‟,‟mango‟] b) I like „apple‟ c) I like apple
d) I like
I like „banana‟ I like banana I like
I like „mango‟ I like mango I like
12. What is the output of the program [ ]
my_list = ['p','r','o','b','l','e','m']
print('p' in my_list)
I B.SC CS

print('a' in my_list)
print('c' not in my_list)
a) True b)True c)False d) False
False True True True
True False False True
13. What is the output of the program [ ]
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[-6])
a) t b) t c) p d) t
p t p NULL
14. What is the output of the program [ ]
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:-7])
print(my_tuple[7:])
print(my_tuple[:])
a) ('r', 'o', 'g') b) („p‟,‟r‟,‟o‟)
('p', 'r') („r‟,‟p‟)
('i', 'z') („z‟,‟‟i‟)
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') ('p','r','o','g','r','a','m','i','z')
c)('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') d) ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
('r', 'o', 'g') ('i', 'z')
('p', 'r') ('p', 'r')
('i', 'z') ('r', 'o', 'g')
15. What is the output of the program [ ]
print((1, 2, 3) + (4, 5, 6))
print(("Repeat",) * 3)
a) (1, 2, 3, 4, 5, 6) b) („Repeat‟,Repeat‟,‟Repeat‟)
('Repeat', 'Repeat', 'Repeat') (1,2,3,4,5,6)
c)(1,2,3)+(4,5,6) d) (“Repeat”,)*3
I B.SC CS

“Repeat” (1,2,3)+(4,5,6)
16. What is the output of the program [ ]
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p'))
print(my_tuple.index('l'))
a) 2 b) 2 c) 3 d) 3
3 2 2 3
17. What is the output of the program [ ]
pow2 = [2 ** x for x in range(10)]
print(pow2)
a) [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
b) [512,256,128,64,32,16,8,4,2,1]
c) [1,2,3,4,5,6,7,8,9,10]
d) [1,3,5,7,9]
18. What is the output of the program [ ]
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
a) e b) e c) p d) e
NULL p e e
19. What is the output of the program [ ]
odd=[1,3,5]
Print(odd+[9,7,5])
Print([“re”]*3)
a) [1,3,5,9,7,5] b) [1,3,5,9,7]
[“re”,”re”,”re”] [“re”,”re”,”re”]
c) (odd+[9,7,5]) d) [1,3,5]
([“re”]*3) ([“re”]*3)
20. What is the output of the program [ ]
odd = [1, 9]
odd.insert(1,3)
print(odd)
odd[2:2] = [5, 7]
I B.SC CS

print(odd)
a) [1, 3, 9] b) [1,3,5,7,9] c) [1,9,3] d) [1,9,1,3]
[1, 3, 5, 7, 9] [1,3,5,7,9] [1,9,3,5,7]
[1,9,1,3,5,7]
B) Subjective Questions
1. What is negative index in list and tuple? [ April-2018]
2. What is tuple? What are the different operations performed on tuple? Explain
with an example? [ NOV-2018]
3. Illustrate the ways of creating the tuple and the tuple assignment with suitable
programs. [ April-2018]
4. Summarize basic List operations with examples. [ NOV-2018]
5. How can you access and update values in a list?
6. Explain mutability of lists?
7. Write a set of commands that covers at least five tuple functions and five list
functions?
8. Write a program to find sum of all even numbers in a list?
9. Write a program that reverses a list using a loop?
10. Write a program to find whether a particular element is present in the list?
11. Write a program that finds the sum of all the numbers in a list using a while
loop?
12. Write a program that forms a List of first character of every word present in
another List. [ NOV-2018]
13. Write a program that creates a list[„a‟,‟b‟,‟c‟], then create a tuple from that list.
14. Write a program that converts a list of characters into their corresponding
ASCII values using map( ) function.
15. Write a program using filter function to list cubes of numbers from 1-10.
16. Write a code snippet in Python to Access Elements of a Tuple. [ NOV-2018]
17. Write code snippets in Python for modifying and deleting Elements of Tuple. [
NOV-2018]
18. “Tuples are immutable”. Explain with examples. [ April-2018]
I B.SC CS

UNIT-IV
Dictionaries

 Dictionary:
o It is a data structure in which we store values as a pair of key and value.
o Each key is separated from its value by a colon (:), and consecutive items
are separated by commas.
o The entire items in a dictionary are enclosed in curly brackets ({}).
Syntax:

dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}


If there are many keys and values in dictionaries, then we can also write just one
key-value pair on a line to make the code easier to read and understand. This is
shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3 , ….}
o Keys in the dictionary must be unique and be of any immutable data type (like
Strings, numbers, or tuples), there is no strict requirement for uniqueness and type
of values.
o Values of a key can be of any type.
o Dictionaries are not Sequences, rather they are mappings.
o Mappings are collections of objects that are store objects by key instead of by
relative position.
Creating a Dictionary:
o The Syntax to create an empty dictionary can be given as:
Dictionary_variable= { }
o The Syntax to create a dictionary with key-value pair is:
Dictionary_variable= {key1:val1, key2:val2……}
o A dictionary can be also created by specifying key-value pairs separated
by a colon in curly brackets as shown below.
o Note that one key value pair is separated from the other using a comma.
Example:
d= {'roll_no':'18/001','Name:':'Arav','Course':'B.tech'}
print(d)
Output: {'Name:': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
I B.SC CS
I B.SC CS

Accessing Values:
 In Dictionary, through key accessing values,
 Example:
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
 Adding and Modifying an Item in a Dictionary:
 To add a new entry or a key-value pair in a dictionary, just specify the key-
value pair as you had done for the existing pairs.
Syntax: dictionary_ variable[key ]= val
Example:
1. Program to add a new item in the dictionary
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
I B.SC CS

Modifying an Entry:
 To modify an entry, just overwrite the existing value as shown in the following
example:
1. program to modify an item in the dictionary
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
d[‘Course’]=’BCA’ #Updated entry
print('d[course]:',d['Course'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
d[course]: BCA

 Deleting Items :
 You can delete one or more items using the del keyword.
 To delete or remove all the items in just one statement, use the clear ()
function.
 Finally, to remove an entire dictionary from the memory, we can gain use
the del statement as del Dict_name.
 The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:
1. Program to demonstrate the use of del statement and clear() function
I B.SC CS

 Keys must have unique values.


 Not even a single key can be duplicated in a dictionary. If you try to add a
duplicate key, then the last assignment is retained.
 In a dictionary, keys should be strictly of a type that is immutable. This means
that a key can be of strings, numbers, or tuple type but it cannot be a list
which is mutable.
 In case you try to make your key of mutable type, then a Type error will be
granted.
 Tuples can be used as keys only if they contain immutable objects like strings,
numbers, or other tuples.
 If a tuple used as key contains any mutable object either directly or indirectly,
then an error is generated.
 The in keyword can be used to check whether a single key is present in the
dictionary.
I B.SC CS

 Sorting Items in a Dictionary:


 The keys() method of dictionary returns a list of all the keys used in the
dictionary in a arbitrary order.
 The sorted() function is used to sort the keys as shown below:
Example:
1. Program to sort keys of a dictionary
d={'roll_no':653,'name':'python','course':'b.tech'}
print(sorted(d.keys()))
output:
['course', 'name', 'roll_no']
 Looping Over a Dictionary:
You can loop over a dictionary to access only values, only keys,and both using the for
loop as shown the code given below:
1. Program to access
d={'roll_no':653,'name':'python','course':'b.tech'}
print("KEYS:",end=' ')
for key in d:
print(key,end=' ')
print("\n VALUES:",end=' ')
for val in d.values():
print(val,end=' ')
print("\n Dictionary:",end=' ')
for key,val in d.items():
print(key,val,end=';')
output:
KEYS: course name roll_no
VALUES: b.tech python 653
Dictionary: course b.tech;name python;roll_no 653;
I B.SC CS

 Built-in Dictionary Functions and Methods:

 Nested Dictionaries :
Dictionary with in another dictionary is called Nested dictionary.
I B.SC CS

Python Programming UNIT-5


(Prepared by: Sri. I. Lakshmi Narayana, Mr. B. Sobhan Babu)

Example:
students={'cse1':{'c':90,'ds':89,'python':98},
'cse2':{'c':90,'ds':99,'python':98},
'cse3':{'c':99,'ds':99,'python':98}}
for key,value in students.items():
print(key,value)
Output:
cse3 {'python': 98, 'c': 99, 'ds': 99}
cse2 {'python': 98, 'c': 90, 'ds': 99}
cse1 {'python': 98, 'c': 90, 'ds': 89}
Difference between a List and a Dictionary:
 First, a list is an ordered set of items. But, a dictionary is a data structure that
is used for matching one item (key) with another (value).
 Second, in lists, you can use indexing to access a particular item. But, these
indexes should be a number. In dictionaries, you can use any type (immutable)
of value as an index. For example, when we write Dict['Name'], Name acts as
an index but it is not a number but a string.
 Third, lists are used to look up a value whereas a dictionary is used to take
one value and look up another value. For this reason, dictionary is also known
as a lookup table.
I B.SC CS

 Fourth, the key-value pair may not be displayed in the order in which it was
specified while defining the dictionary. This is because Python uses complex
algorithms (called hashing) to provide fast access to the items stored in the
dictionary. This also makes dictionary preferable to use over a list of tuples.
 String Formatting with Dictionaries:
Python also allows you to use string formatting feature with dictionaries. So you can
use %s, %d, %f, etc. to represent string, integer, floating point number, or any other
data.
Example:
Program that uses string formatting feature to print the key-value pairs stored in the
dictionary.
d={"cse":98,"ece":99,"eee":90}
for key,value in d.items():
print("%s branch:%d"%(key,value))
output:
ece branch:99
cse branch:98
eee branch:90
Lab Programs:
5a.Write a program to count the number of characters in the string and store
them in dictionary
n=int(input("Enter the number"))
i=0;
dict1={}
while(i<n):
str1=input("Enter the string")
length=len(str1)
dict1[str1]=length
i=i+1;
print('Entered dictionary elements are')
print(dict1)
I B.SC CS

Enter the stringhari


Enter the stringchennai
Entered dictionary elements are
{'hari': 4, 'chennai': 7}
5b.Write a program to sort keys in a Dictionary
Dict1={'Course':'B.Tech','Rollno':'565','Address':'GDV'}
for key in sorted(Dict1):
print("%s%s"%(key,Dict1[key]))
Output
AddressGDV
CourseB.Tech
Rollno565
5c.Write a Program that prints maximum and minimum value in a dictionary
Dict1={'Course':'B.Tech','Rollno':'565','Address':'GDV'}
print('Minimum value is ',min(Dict1.values()))
print('Maximum value is',max(Dict1.values()))
Output
>>>
Minimum value is 565
Maximum value is GDV
I B.SC CS

Assignment-Cum-Tutorial Questions
I) Objective Questions
1) Which of these about a dictionary is false? [ ]
a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren‟t ordered
d) Dictionaries are mutable
2) Which of the following statements create a dictionary? [ ]
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned

3) Which of the following is not a declaration of the dictionary? [ ]


a) {1: „A‟, 2: „B‟}
b) dict ([[1,”A”],[2,”B”]])
c) {1,”A”,2,”B”}
d) { }

4) What is the output of the following code? [ ]


A = {1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")

a) 1 A 2 B 3 C b) 1 2 3 c) A B C d) 1:”A” 2:”B” 3:”C”


5) Which of the following isn‟t true about dictionary keys? [ ]
a) More than one key isn‟t allowed
b) Keys must be immutable
c) Keys must be integers
d) When duplicate keys encountered, the last assignment wins
I B.SC CS

6) Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do
we use [ ]
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”].
d) del d(“john”:40)

7) Suppose d = {“john”:40, “peter”:45}, what happens when we try to retrieve a value


using the expression d[“susan”]? [ ]

a) Since “susan” is not a value in the dictionary, Python raises a KeyError exception
b) It is executed fine and no exception is raised, and it returns None
c) Since “susan” is not a key in the dictionary, Python raises a KeyError exception
d) Since “susan” is not a key in the set, Python raises a syntax error
8) What gets printed? [ ]
foo = {1:'1', 2:'2', 3:'3'}
del foo[1]
foo[1] = '10'
del foo[2]
print(len(foo))
a) 1 b) 2 c) 3 d) 4 e) An Exception is thrown

9) If Dict = {1:2, 3:4, 4:11, 5:6, 7:8}, then print(Dict(Dict[3])) will print ? [ ]
a) 2 b) 8 c) 11 d) 6
10) Which Data type does not support indexing? [ ]
a) List b) Tuple c) Dictionary d) Set
11) Which function is used to delete all entries in the dictionary _?

12) Which methods will return all the keys and Values in a Dictionary
?
13) What are the Data types supported for Key in Dictionary Data type ?
I B.SC CS

14) Fill in the blanks to create a Dictionary.


Dict = dict(1 “abc” 2 ”hai”)
Dict1= 1:”abc”,2:”hai”
15) Find the output of the below program?
D={"India":"Delhi", "Nepal":"Kathmandu", "USA":"DC"}
del D["Nepal"]
for key,val in D.items():
print(key)
II) Subjective Questions
1) Explain the importance of Dictionary data type in python?

2) List-out various operations can be performed on Dictionary Data type?


(Nov-2018)
3) List-out the Built-in functions and methods of Dictionary Data type in python?
(Nov-2018)
4) Write a Python program to check if all dictionaries in a list are empty or not.
5) How to delete items from a dictionary? Explain with an example. Write a Python
script to sort (ascending and descending) a dictionary by value.
6) Write a Python script to generate and print a dictionary that contains a number
(between 1 and n) in the form (x, x*x).
Sample:
Dictionary (n = 5):
Expected Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
7) Write a Python script to print a dictionary where the keys are numbers between 1
and 15 (both included) and the values are square of keys.
Sample Dictionary:
{1: 1, 2: 5, 3: 9, 4: 15, 5: 25, 6: 36, 7: 49, 80: 64, 9: 80, 90: 100, 11: 121, 12: 144, 13:
169, 14: 200, 105: 225}
8) Write a Python program to map two lists into a dictionary.
I B.SC CS

9) Write a python program to check if all dictionaries in a list are empty or not?

10) Write a Python program to combine two dictionary adding values for
commonkeys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200,‟d‟:400}
Sample output: {'a': 400, 'b': 400,‟d‟: 400, 'c': 300}
11) Write a Python program to create and display all combinations of
letters, selecting each letter from a different key in a dictionary
Sample data: {'1':['a','b'], '2':['c','d']}
Expected Output:
ac
ad
bc
bd
12) Write a Python program to get the top three items in a shop.
Sample data: {'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24}
Expected Output:
item4: 55
item1: 45.5
item3: 41.3
I B.SC CS

UNIT-V
File Handling
File types, File path, File operations-open, close, read, write, Types of arguments.

1. Introduction to Files:
 When a program is being executed, its data is stored in RAM. Though RAM can
be accessed faster by the CPU,it is also volatile, which means when the
program ends, or the computer shuts down, all the data is lost. If you want to
use the data in future,then you need to store this data on a permanent or non-
volatile storage media such as hard disk, USB drive and DVD e.t.c.,
 A file is a collection of data stored on a secondary storage device like hard disk.
 A file is basically used because real-life applications involve large amounts of
data and in such situations the console oriented I/O operations pose two
majorproblems:
 First, it becomes cumbersome and time consuming to handle huge amount of
data through terminals.
 Second, when doing I/O using terminal, the entire data is lost when either the
program is terminated or computer is turned off. Therefore, it becomes
necessary to store data on a permanent storage (the disks) and read whenever
necessary, without destroying the data.
2. File Types
 Like C and C++,Python also supports two types of files
1. ASCII Text Files
2.Binary Files
2.1ASCII Text Files
 A text file is a stream of characters that can be sequentially processed by a
computer in forward direction. For this reason a text file is usually opened for
only one kind of operation (reading, writing, or appending) at any given time.
 Because text files can process characters, they can only read or write data one
character at a time. In Python, a text stream is treated as a special kind of file.
 Depending on the requirements of the operating system and on the operation
that has to be performed (read/write operation) on the file, the newline
characters may be converted to or from carriage-return/linefeed combinations.
I B.SC CS

 Besides this, other character conversions may also be done to satisfy the
storage requirements of the operating system. However, these conversions
occur transparently to process a text file. In a text file, each line contains zero
or more characters and ends with one or more characters.
 Another important thing is that when a text file is used, there are actually two
representations of data- internal or external. For example, an integer value will
be represented as a number that occupies 2 or 4 bytes of memory internally
but externally the integer value will be represented as a string of characters
representing its decimal or hexadecimal value.
Note: In a text file, each line of data ends with a newline character. Each file ends with
a special character called end-of-file (EOF) Marker.
Binary Files
 A binary file is a file which may contain any type of data, encoded in binary
form for computer storage and processing purposes. It includes files such as
word processing documents, PDFs, images, spreadsheets, videos, zip files and
other executable programs.
 Like a text file, a binary file is a collection of bytes. A binary file is also referred
to as a character stream with following two essential differences.
 A binary file does not require any special processing of the data and each byte
of data is transferred to or from the disk unprocessed.
 Python places no constructs on the file, and it may be read from, or written to,
in any manner the programmer wants.
 While text files can be processed sequentially, binary files, on the other
hand, can be either processed sequentially or randomly depending on the
needs of the application.
Note:Binary files store data in the internal representation format.Therefore, an integer
value will be stored in binary form as 2 byte value.The same format is used to store
data in memory as well as in files.Like Text files,Binary files also ends with an EOF
Marker
I B.SC CS

3. File Path:
 Files that we use are stored on a storage medium like the hard disk in such a
way that they can be easily retrieved as and when required.
 Every file is identified by its path that begins from the root node or the root
folder. In Windows, C:\ (also known as C drive) is the root folder but you can
also have a path that starts from other drives like D:\, E:\, etc. The file path is
also known as pathname.
 In order to access a file on a particular disk we have two paths.
1. Absolute Path
2. Relative Path

 While an absolute path always contains the root and the complete directory
list to specify the exact location the file.
Example:To access BTech_CS.docx,The absolute path is
C:\Students\Under Graduate\BTech_CS.docx
 Relative path needs to be combined with another path in order to access a
file. It starts with respect to the current working directory and therefore lacks
the leading slashes.
Example: Suppose you are working on current directory Under Graduate in order to
access BTech_CS.docx,The Relative path is
Under Graduate\BTech_CS.docx
I B.SC CS

4. File Operations

 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.
 Python has many in-built functions and methods to manipulate files.These
 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
 Before reading from or writing to a file, you must first open it using Python‟s
built-in open() function. This function creates a file object, which will be used
to invoke methods associated with it.
 The Syntax of open() is:
fileObj = open(file_name [, access_mode])
Where file_name is a string value that specifies name of the file that you want to
access. access_mode indicates the mode in which the file has to be opened, i.e., read,
write, append, etc.
 Example:Write a Program to print the details of file object

Note:Access mode is an optional parameter and the default file access mode is
read(r).

Access modes
 Python supports the following access modes for opening a file those are
I B.SC CS

The File Object Attributes


 Once a file is successfully opened, a file object is returned. Using this file
object, you can easily access different type of information related to that file.
This information can be obtained by reading values of specific attributes of the
file.
 The Following table shows list attributes related to file object.

 Example: Program to open a file and print its attribute values.


I B.SC CS

Closing A File
 The close() method is used to close the file object. Once a file object is closed,
you cannot further read from or write into the file associated with the file
object.
 While closing the file object the close() flushes any unwritten information.
Although, Python automatically closes a file when the reference object of a file
is reassigned to another file, but as a good programming habit you should
always explicitly use the close() method to close a file.
 The syntax of close() is
fileObj.close()
 The close() method frees up any system resources such as file descriptors, file
locks, etc. that are associated with the file.
 Once the file is closed using the close() method, any attempt to use the file
object will result in an error.
Example2: Write a Python program to assess if a file is closed or not..

file = open('File1.txt','wb')
print('Name of the file :',file.name)
print('File is closed:',file.closed)
print('File is now being closed')
file.close()
print('File is closed',file.closed)
I B.SC CS

print(file.read())
Output:
Name of the file : File1.txt
File is closed: False
File is now being closed
File is closed True
Traceback (most recent call last):
File "D:/Python/sample.py", line 7, in <module>
print(file.read())
io.UnsupportedOperation: read
Writing A File
 The write() method is used to write a string to an already opened file. Of course
this string may include numbers, special characters or other symbols.
 While writing data to a file, you must remember that the write() method does
not add a newline character ('\n') to the end of the string.
 The syntax of write() method is:
fileObj.write(string)
Example:Program that writes a message in the file,data.txt
file=open('data.txt','w')
file.write('hello cse we are learning python programming')
file.close() data.txt
print('file writing successful')
hello cse we are learning python programming
Output:
file writing successful
writeline() method:
 The writelines() method is used to write a list of strings.
Example:Program to write to afile using the writelines() method
file=open('data.txt','w')
lines=['hello','cse','hope to enjoy','learning','python programming']
file.writelines(lines) data.txt
file.close() hellocsehope to enjoylearningpython programming
I B.SC CS

print('file writing successful')


Output:
file writing successful
append() method:
 Once you have stored some data in a file,you can always open that file again to
write more data or append data to it.
 To append a file, you must open it using „a‟ or „ab‟ mode depending on whether
it is text file or binary file.
 Note that if you open a file with „w‟ or „wb‟ mode and then start writing data
into it, then the existing contents would be overwritten.
Example:Program to append data to an already existing file
file=open('data.txt','a')
file.write('\nHave a nice day')
file.close()
print('Data appended successful')
Output:
Data appended successful
data.txt

hellocsehope to enjoylearningpython programming

Have a nice day


Reading A File
 The read() method is used to read a string from an already opened file.As said
before, the string can include, alphabets, numbers, characters or other
symbols.
 The syntax of read() method is
fileObj.read([count])
Where In the above syntax, count is an optional parameter which if passed to the
read() method specifies the number of bytes to be read from the opened file.
 The read() method starts reading from the beginning of the file and if count is
missing or has a negative value then, it reads the entire contents of the file (i.e.,
till the end of file).
I B.SC CS

Example1:Program to print the first 8 characters of the file data.txt


file=open('data.txt','r') data.txt
print(file.read(8))
hellocsehope to enjoylearningpython programming
file.close()
Have a nice day
Output:
hellocse
Example2:Program to display the content of file using for loop
file=open('data.txt','r')
for line in file: data.txt
print(line)
hellocsehope to enjoylearningpython programming
file.close()
Have a nice day
Output:
hellocsehope to enjoylearningpython programming
Have a nice day
Note:read() methods returns a newline as „\n‟
readline() Method
 It is used to read single line from the file.
 This method returns an empty string when end of the file has been reached.
ExampleProgram to demonstrate the usage of readline() function
file=open('data.txt','r')
print('firtsline:',file.readline())
data.txt
print('second line:',file.readline())
print('third line:',file.readline()) hellocsehope to enjoylearningpython programming

file.close() Have a nice day


Output:
firtsline: hellocsehope to enjoylearningpython programming
second line: Have a nice day
third line:
readlines() Method
 readlines() Method is used to read all the lines in the file.
I B.SC CS

Example:Program to demonstrate readlines() function


file=open('data.txt','r') data.txt
print(file.readlines())
hellocsehope to enjoylearningpython programming
file.close()
Have a nice day
Output:
['hellocsehope to enjoylearningpython programming\n', 'Have a nice day']
list() Method
 list() method is also used to display entire contents of the file.you need to pass
the file object as an argument to the list() method.
Example: Program to display the contents of the file data.txt using the list()
method
file=open('data.txt','r') data.txt

print(list(file)) hellocsehope to enjoylearningpython programming


file.close() Have a nice day
Output:
['hellocsehope to enjoylearningpython programming\n', 'Have a nice day']
Opening a file using with keyword:
 It is good programming habit to use the with keyword when working with file
objects.
 This has the advantage that the file is properly closed after it is used even if an
error occurs during read or write operation or even when you forget to explicitly
close the file.

Note: When you open a file for reading, or writing, the file is searched in the current
I B.SC CS

directory. If the file exists somewhere else then you need to specify the path of the
file.
Splitting Words:
 Python allows you to read line(s) from a file and splits the line (treated as a
string) based on a character. By default, this character is space but you can
even specify any other character to split words in the string.
Example: Program to split the line into series of words and use space to perform the
split operation
with open('data.txt','r') as file:
data.txt
line=file.readline()
hellocsehope to enjoylearningpython programming
words=line.split()
print(words)
Output:

['hellocsehope', 'to', 'enjoylearningpython', 'programming']


Some Other Useful File Methods:
 The following are some of additional methods which will work on files
I B.SC CS

File Positions:
 With every file, the file management system associates a pointer often known
as file pointer that facilitates the movement across the file for reading and/ or
writing data.
 The file pointer specifies a location from where the current read or write
operation is initiated. Once the read/write operation is completed, the pointer
is automatically updated.
 Python has various methods that tells or sets the position of the file pointer.
I B.SC CS

 For example, the tell() method tells the current position within the file at which
the next read or write operation will occur. It is specified as number of bytes
from the beginning of the file.
 When you just open a file for reading, the file pointer is positioned at location
0, which is the beginning of the file.
 The syntax for seek() function is
seek(offset[, from])
 The offset argument indicates the number of bytes to be moved and the from
argument specifies the reference position from where the bytes are to be
moved.
Example: Program that tells and sets the position of file pointer
File1.txt
Hello All,
Hope you are enjoying learning python

Renaming and Deleting Files:


 The os module in Python has various methods that can be used to perform file-
processing operations like renaming and deleting files. To use the methods
defined in the os module, you should first import it in your program then call
any related functions.
I B.SC CS

 The rename() Method: The rename() method takes two arguments, the current
filename and the new filename.
Its syntax is: os.rename(old_file_name, new_file_name)
 The remove() Method: This method can be used to delete file(s). The method
takes a filename (name of the file to be deleted) as an argument and deletes
that file.
Its syntax is: os.remove(file_name)
Example: Program to rename file ‘File1.txt’ to ‘student.txt’

Example: Program to delete a file named File1.txt

5. Types of Arguments
Command line Arguments:
 The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes −
 sys.argv is the list of command-line arguments.
 len(sys.argv) is the number of command-line arguments.
 Here sys.argv[0] is the program ie. script name.

Example1:Write a Python program to demonstrate the usage of Command Line


Arguments
I B.SC CS

sample11.py
#!/usr/bin/python
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
Output:

Example2: Write a Python program to copy the content of one file to another
using command line arguments.
sample12.py input.txt
Hello hi
#!/usr/bin/python How are you
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
with open(str(sys.argv[1])) as f:
with open((sys.argv[2]), "w") as f1: output.txt
Hello hi
for line in f:
How are you
f1.write(line)
print('File Copied Success')

6. File Handling Programs


1. Write a program to print each line of a file in reverse order
Program:
input.txt
with open('input.txt','r') as fp: Hello hi
for line in fp: How are you

print (line[::-1])
Output:
ih olleH
uoy era woH
I B.SC CS

2. Write a program to compute the number of characters, words and lines in a


file
Program:
fname = "data.txt"
data.txt
num_lines = 0
hellocsehope to enjoylearningpython programming
num_words = 0
num_chars = 0 Have a nice day

with open(fname, 'r') as f:


for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
print('The no of lines in a given file is',num_lines)
print('The no of words in a given file is',num_words)
print('The no of chars in a given file is',num_chars)
Output:
The no of lines in a given file is 2
The no of words in a given file is 8
The no of chars in a given file is 63
3. Write a program to copy contents of one file to another file
Program:
with open("data.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
Output:

data.txt

hellocsehope to enjoylearningpython programming

Have a nice day


I B.SC CS

out.txt

hellocsehope to enjoylearningpython programming

Have a nice day

4. Write a Python Program to count number of Vowels and Number of


Consonants in a given file. (November 2018 Supplementary)
Program:
infile = open("data.txt", "r")
vowels = set("AEIOUaeiou")
cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
countV = 0
countC = 0
for c in infile.read():
if c in vowels:
countV += 1
elif c in cons:
countC += 1
print("The no of Vowels are",countV)
print("The no of Consonants are",countC)
I B.SC CS

Assignment-Cum-Tutorial Questions
A. Objective Questions
1. Identify The right way to close a file [ ]
a)File.close() b)close(file) c)close(“file”) d)File.closed
2. is an example of volatile memory
3. A file is stored in memory [ ]
a)primary b)secondary c)cache d)volatile
4. What will happen when a file is opened in write mode and then immediately
closed. [ ]
a) Filecontentsaredeleted
b) Nothing Happens
c) A Blank Line is written to the file
d)an error occurs
5. The default access mode of the file is
6. If a file opened in „w‟ mode does not exist, then [ ]
a) nothing will happen
b) File will be created
c) Data will be written to a afile that has a name similar to the specified name
d) Error will be generated
7. Identify the delimiter in the Solaris file system [ ]
a)/ b)\ c): d)|
8. By default a new file is created in which directory [ ]
a)root b)current working c)Python directory d)D Drive
9. which method is used to read a single line from the file [ ]
a)read() b)readline() c)readlines() d)reads()
10. When you open a file for appending that does not exist, then a new file is
created [True/False]
11. Identify the correct way to write “Welcome to Python” in a file [ ]
a)write(file,”Welcome to python”)
b)write(“Welcome to Python”,file)
c)file.write(“Welcome to Python”)
I B.SC CS

d)”Welcome to Python”.write(file)
12. If the file.txt has 10 lines written in it,what will the result? [ ]
len(open(„file.txt‟).readlines())
a)1 b)0 c)10 d)2
13. Identify the sub folder in the path [ ]
C:\Students\UnderGraduates\B.Tech_CS.docx
a)C: b) Students c)B.Tech_CS.docx d) UnderGraduates
14. Which method returns a string that includes everything specified in the
path? [ ]
a)os.path.dirname(path)
b)os.path.basename(path)
c)os.path.relpath()
d)os.path.abs()
15. if count is missing or has a negative value in the read() method then, no
contents are read from the file. [True/False]
16. os.path.abs() method accepts a file path as an argument and returns True if
the path is an absolute path and False otherwise
[True/False]
17. How many characters would be printed by this code (One character is one
byte)
file=open(“file.txt”,”r”)
for i in range(100):
print(file.read(10))
file.close()
18. Fill in the blank to open a file,read its content and prints its length
file= (“file.txt”,”r”)
text=file. ()
print( (text))
file.close()
19. Predict the output of the following program [ ]f
= None
I B.SC CS

for i in range (5):


with open("data.txt", "w") as f:
if i > 2
break
print(f.closed)
a)True b) False c) None d) Error
20. Predict the output of the following program [ ]
with open("hello.txt", "w") as f:
f.write("Hello World how are you today")
with open('hello.txt', 'r') as f:
data = f.readlines()
for line in data:
words = line.split()
print (words)
f.close()
a. Runtime Error
b. Hello World how are you today
c. [„Hello‟, „World‟, „how‟, „are‟, „you‟, „today‟]
d. Hello
B. Descriptive Questions
1. Define file. Explain about the importance of files in Python.
2. Define path. Distinguish between absolute and relative path with an example.
3. Discuss briefly about various types of file.
4. Write in detail about various modes of file.
5. Give an overview of File positions.
6. Explain different file operations with suitable programming examples.
7. What is the purpose of opening a file using with keyword.
8. Write a Python program to count number of vowels and consonants in a given
text file
I B.SC CS

9. Write a Python program that reads data from a file and Calculates the
percentage of vowels and consonants in the file
10. Write a Python program that copies one file to another in such away that all
comment lines are skipped and not copied in the destination file
11. Write a python program to find no of lines, words and characters in a given
text file
12. Write a Python program to combine each line from first file with the
corresponding line in second file.
13. Write a program that accepts file name as an input from the user. Open the
file and count number of times a character appears in the file.
14. Write a program that tells and sets the position of the file pointer.
-----------OOO-----------

You might also like