Python Notes
Python Notes
CLASS: I BCA
SUBJECT: PYHON PROGRAMMING SUBJECT CODE: 23UCA01
UNIT-I
BASICS OF PYTHON PROGRAMMING
Explain about basics of python programming. (5m)
Python is an exciting and powerful language.
It is a high-level, interpreted, interactive, object-oriented, and a reliable language that is very simple and
uses English-like words.
It has a vast library of modules to support integration of complex solutions from pre-built components.
Python is an open-source project, supported by many individuals.
It is a platform-independent, scripted language, with complete access to operating system APIs.
This allows users to create high-powered, highly-focused applications.
HISTORY OF PYTHON
Write about history of python. (5m)
Python was 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. While version 2.0 included list comprehensions
and was released in 2000 by the BeOpen Python Labs team. Python 2.7 which is still used today will be
supported until 2020. But there will be no 2.8, instead, support team will continue to support version 2.7
and concentrate further development of Python 3. Currently, Python 3.6.4 is already available. The
newer versions have better features like flexible string representation, etc.
Although Python is copyrighted, its source code is available under the GNU General Public
License(GPL) like that of 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 a very powerful and popular
language. It would be surprising to know that Python is actually older than Java, R, and JavaScript.
Why is it called 'Python'?
Python language was released by its designer, Guido Van Rossum, in February 1991 while working for
CWI (also known as Stichting Mathematisch Centrum).
At the time he began implementing this language, he was also reading the published scripts from Monty
Python's Flying Circus (a BBC comedy series from the 70's).
Rossum wanted a name that was short, unique, and slightly mysterious. Since, he was a fan of the show
he thought Python would be the perfect name for the new language.
FEATURES OF PYTHON
1. DISCUSS ABOUT FEATURES OF PYTHON.[PART-C]
Python is a complete programming language with the following features.
Simple:
Python is a simple and a small language.
Reading a program written in Python feels almost like reading English.
Python allows programmers to concentrate on the solution to the problem rather the language itself.
Easy to Learn:
Python program is clearly defined and easily readable. The structure of the program is very simple.
It uses few keywords and a clearly defined syntax.
Versatile:
Python supports development of a wide range of applications ranging from simple text processing to
WWW browsers to games.
Free and Open Source:
Python is an example of open source software.
Anyone can freely distribute it, read the source code, edit it, and even use the code to write new programs
1
High-level Language:
Python the programmers don’t worry about low-level details like managing memory used by the program,
etc. Concentrate on writing solutions of the current problem at hand.
Interactive:
Programs use interactive mode which allows interactive testing and debugging of pieces of code.
Programmers can interact with interpreter directly at the python prompt to write their programs.
Portable:
It is a portable language and hence the programs behave the same on a wide variety of hardware platforms
and have the same interface on all platforms.
The programs work on any of the operating systems like Linux, Windows, FreeBSD, Macintosh, Solaris,
OS/2, Amiga, AROS, AS/400, BeOS, OS/390, 2/OS, Palm OS and even Pocket PC without requiring any
changes.
Object Oriented:
Python supports object-oriented as well as procedure-oriented style of programming.
Encapsulates data and functionalities within objects, procedure-oriented technique, on the other hand,
builds the program around procedures or functions which are nothing but reusable pieces of programs.
Python is powerful yet a simple language for implementing OOP concepts, especially when compared to
languages likes C++ or Java.
Interpreted:
Python is processed at run-time by the interpreter.
No need to compile a program before executing it. We can simply run the program.
Python converts source code into an intermediate form called bytecode, which is then translated into the
native language of our computer so that it can be executed.
Bytecodes makes Python code portable since users can copy the code and run it without worrying about
compiling, linking, and loading processes
Dynamic:
Python executes dynamically.
Programs written in Python can be copied and used for flexible development of applications.
If there is any error, it is reported at run-time to allow interactive program development.
Extensible:
Python is 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.
Moreover, if you want a piece of code not to be accessible for everyone, then you can even code that part
of your program in C or C++ and then use them from your Python program
Embeddable:
Programmers can embed Python within their C, C++, COM, ActiveX, CORBA, and Java programs to
give 'scripting capabilities for users
Extensive Libraries:
Python has a huge library that is easily portable across different platforms.
These library functions are compatible on UNIX, Windows, Macintosh, etc. and allows programmers to
perform a wide range of applications varying from text processing, maintaining databases, to GUI
programming
Easy Maintenance:
Code written in Python is easy to maintain.
Secure:
Python language environment is secure from tampering.
Modules can be distributed to prevent altering the source code.
Additional 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 things make the language robust.
Multi-threaded:
Python supports multi-threading that is executing more than one process of a program simultaneously.
2
It also allows programmers to perform process management tasks.
Garbage Collection:
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.
An object that is no longer used or has gone out of scope are eligible for garbage collection.
LITERAL
Explain about literals. (5m)
The word "literal" has been derived from literally.
The value of a literal constant can be used directly in programs.
There are mainly five types of literals used in PYTHON:
String Literals
Numeric Literals
Boolean Literals
Special Literals
Literal Collections
Numbers
Numeric Literals are digits. Python supports four different numerical types −
int (signed integers) − They are often called just integers or ints, are positive or negative whole
numbers with no decimal point.
long (long integers ) − Also called longs, they are integers of unlimited size, written like integers
and followed by an uppercase or lowercase L.
float (floating point real values) − Also called floats, they represent real numbers and are written
with a decimal point dividing the integer and fractional parts.
complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents
the square root of -1 (which is an imaginary number). The real part of the number is a, and the
imaginary part is b.
Example:
val1 = 25 # int Literal Output:
print(val1)
val2 = 11.89 # float Literal 25
print(val2) 11.89
val3 = 6+2.9j # complex Literal
print(val3) (6+2.9j)
val4 = 0x12d # hexadecimal Literal
print(val4) 301
val5 = 0o021 # octal literal 17
print(val5)
Strings
We can easily create a string literal simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
There are two types of Strings supported in Python:
Single-line String- Strings that are terminated within a single-line are known as Single line
Strings.
Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.
Example: Output:
str1 = "Natarajan"
print(str1) Natarajan
str2 = """ This,
This,
is it!
""" is it!
print(str2)
What is Unicode Strings?(5 Marks)
Unicode Strings
3
Unicode is a standard way of writing international text. That is, if we want to write some text in our
native language like Hindi, then we need to have a Unicode-enabled text editor. Python allows you to
specify Unicode text by prefixing the string with a u or U. For example,
u"Sample Unicode string."
The 'U' prefix specifies that the file contains text written in language other than English.
There is no char data type in Python.
Escape Sequences
Some characters (like", \) cannot be directly included in a string. Such characters must be escaped by
placing a backslash before them.
>>>print('What's your name?')
SyntaxError: invalid syntax
Reason for error: Python got confused as to where the string starts and ends. So, we need to clearly
specify that this single quote does not indicate the end of the string. This indication can be given with the
help of an escape sequence. We specify the single quote as \' (single quote preceded by a backslash).
>>>print('What\'s your name?')
What's your name?
An escape sequence is a combination of characters that is translated into another character or a
sequence of characters that may be difficult or impossible to represent directly.
Similarly, to print double quotes in a string enclosed within double quotes, we need to precede the
double quotes with a backslash as given below.
>>>print("The boy replies, \"My name is Aaditya.\"")
The boy replies, "My name is Aaditya."
To print a multi-line string, we use triple quotes.
We can use an escape sequence for the newline character (\n). Characters following the
\n are moved to the next line. Observe the output of the following command.
>>>print("Today is 15th August. \n India became independent on this day.")
Today is 15th August.
India became independent on this day.
Programming Tip: When a string is printed, the quotes around it are not displayed.
Another useful escape sequence is \t which inserts tab in a string. Consider the command given below to
show how the string gets displayed on the screen.
>>>print("Hello All. \t Welcome to the world of Python.")
Hello All. Welcome to the world of Python.
Note that when specifying a string, if a single backslash (\) at the end of the line is added, then it indicates
that the string is continued in the next line, but no new line is added otherwise.
Escape Sequence Purpose Example Output
\\ Prints Backslash print("\\") \
\’ Printssingle-quote print("\'") ‘
\” Prints double-quote print("\"") “
\a Rings bell print("\a") Bell rings
\f Prints form feed character print("Hello\fworld") Hello world
\n Prints newline character print("Hello\nWorld")Hello
world
\t Prints a tab print("Hello\tworld") Hello world
\o Prints octal value print("\056") .
\x Prints hex value print("\x87") +
Explain Raw Strings and String Formatting. (5 Marks)
Raw Strings
To specify a string that should not handle any escape sequences and want to display exactly as
specified, then we need to specify that string as a raw string.
A raw string is specified by prefixing r or R to the string. Consider the code below that prints the string
as it is.
>>> print (R "What\'s your name?")
What\'s your name?
String Formatting
4
format() function can be used to format floating point numbers. The same function can also be used to
control the display of strings. The syntax of format() function is given as,
format (value, format specifier)
where, value is the value or the string to be displayed, and format specifier can contain a combination of
formatting options.
Example Commands to display 'Hello' left-justified, right-justified, and center-aligned in a field width of
30 characters.
Example
>>>format('Hello', '<30')
‘ Hello’
>>> format (‘Hello’,’>30')
‘ Hello’
>>> format ('Hello', '^30')
'Hello
Here, the '<' symbol means to left justify. Similarly, to right justify the string use the ">"symbol and
the ‘^’ symbol to centrally align the string.
format () function uses blank spaces to fill the specified width. But we can also use the format ()
function to fill the width in the formatted string using any other character as shown below.
>>>print('Hello', format ('-','-<10'), 'World')
('Hello',’----------', 'World')
Boolean Literals
Boolean has two values i.e. True and False. True is for 1 and False 0. Output:
Example
a = (1 == True) True
b = (1 == False) False
print(a)
print(b)
Special literals:
None is a special literal defined in Python to specify the end of a list or to represent a NULL value.
Example:
val1=None Output:
val2= “Natarajan” None
print(val1) Natarajan
print(val2)
Literal Collections
There are four different literal collections List literals, Tuple literals, Dictionary literals, and Set literals.
Example:
# list literal Output:
fruits = ["apple", "mango", "orange"]
print(fruits) ['apple', 'mango', 'orange']
# tuple literal
numbers = (1, 2, 3) (1, 2, 3)
print(numbers)
# dictionary literal
{'a': 'apple', 'b': 'ball', 'c':
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'}
print(alphabets) 'cat'}
# set literal
vowels = {'a', 'e', 'i' , 'o', 'u'} {'e', 'a', 'o', 'i', 'u'}
print(vowels)
VARIABLES – IDENTIFIERS
Elaborate identifiers. (5 Marks)
Variables play a very important role in most programming languages, and Python is no exception.
Variable, in simple language, means its value can vary. We can store any piece of information in a
variable. Variables are nothing but just parts of our computer's memory where information is stored.
To be identified easily, each variable is given an appropriate name.
5
Every variable is assigned a name which can be used to refer to the value later in the program.
Variables are reserved memory locations that stores values.
Variables are examples of identifiers. Identifiers as the name suggests, 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 that we must follow.
These rules are:
1. The first character of an identifier must be an underscore(‘_’) or a letter(upper or lowercase).
2. The rest of the identifier name can be underscore(‘_’), letters(upper or lowercase), or digit (0-9).
3. Identifier names are case-sensitive. For example, myvar and myVar are not the same.
4. 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.
Python is a case-sensitive language.
Variable names can contain only letters, numbers, and underscores.
KEYWORDS
In every programming language there are certain words which have a pre-defined meaning. These words
which are also known as reserved words or keywords cannot be used for naming identifiers.
Table below shows a list of Python keywords.
Table: Reserved Words
and assert break class continue def del elif else except
exec finally for from global if import in is lambda
not or pass print raise return try while with yield
Note All the Python keywords contain lowercase letters only.
BUILT-IN DATA TYPES
Write about data types in python. (5 Marks)
Variables can hold values of different types called data types.
Thus, we need different data types to store different types of values in the variables.
For example, a person's age is stored is a number, his name is made of only characters, and his address is
a mixture of numbers and characters.
Python has various standard data types that are used to define the operations possible on them and the
storage method for each of them.
Based on the data type of a variable, the interpreter reserves memory for it and also determines the type
of data that can be stored in the reserved memory. The basic types are numbers and strings. We can
even create our own data types in Python (like classes). The five standard data types supported by
Python includes numbers, string, list, tuple, and dictionary.
Note: Python is a purely object-oriented language. It refers to everything as an object including numbers
and strings.
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
num = 7
amt = 123.45
code = 'A'
pi =3.1415926536
population_of_India = 10000000000
msg= "Hi"
print("NUM "+str(num))
print("\n AMT = "+ str(amt))
print("\n CODE = "+ str(code))
print("\n POPULATION OF INDIA =" + str(population_of_India))
print("\n MESSAGE = "+msg)
OUTPUT
6
NUM = 7
AMT = 123.45
CODE = A
POPULATION OF INDIA = 10000000000
MESSAGE = Hi
In Python, we can reassign variables as many times as we want to change the value stored in them.
We may even store value of one data type in a statement and then a value of another data in a subsequent
statement.
This is possible because Python variables do not have specific types, so we can assign an integer to a
variable, and later assign a string to the same variable.
Example Program to reassign values to a variable
val ='Hello' OUTPUT
print (val) Hello
val= 100 100
print (val) 12.34
val= 12.34
print(val)
For example, type the following command lines in the IDLE and observe the output.
>>>x = 5
>>> y = 10
>>>print('Hello')
Hello
>>> print (x+y)
15
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also known as
multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple variables
or assigning multiple values to multiple variables.
Example: Output:
x=y=z=50 50
print(x) 50
print(y) 50
print(z)
Multiple Statements on a Single Line
There are two types of lines in a program code-the physical line and the logical line.
While, physical line is what we see while writing the program, logical line, on the other hand, is what
Python sees as a single statement.
For example, print("Hello") is a logical line. If this is the only statement present in a line, it also
corresponds to physical line. Python assumes that each physical line corresponds to a logical line. So, it
is a good programming habit to specify a single statement on a line. This also makes the code readable
and easily understandable.
However, if we want to specify more than one statement in a single line, then we should use a semi-
colon (;) to separate the two statements.
Boolean
Data type with one of the two built-in values, True or False.
But non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false.
It is denoted by the class bool.
Example: Output:
print(type(True)) <class 'bool'>
print(type(False)) <class 'bool'>
OUTPUT STATEMENTS
Explain about output statement in python. (5, 10 Marks)
7
Explain print() function with all if its options.(5 Marks)
The print() function prints the specified message to the screen, or other standard output device.
The message can be a string, or any other object, the object will be converted into a string before written
to the screen.
The print() statement
The Python print() function is often used to output variables.
Syntax of print()
print function accepts 5 parameters.
print(object= separator= end= file= flush=)
Here,
object - value(s) to be printed
sep (optional) - allows us to separate multiple objects inside print().
end (optional) - allows us to add add specific values like new line "\n", tab "\t"
file (optional) - where the values are printed. It's default value is sys.stdout (screen)
flush (optional) - boolean specifying if the output is flushed or buffered. Default: False
Python print() with end Parameter
# print with end whitespace
print('Good Morning!', end= ' ')
print('It is rainy today')
Output
Good Morning! It is rainy today
Python print() with sep parameter
print('New Year', 2023, 'See you soon!', sep= '. ')
Output
New Year. 2023. See you soon!
In the above example, the print() statement includes multiple items separated by a comma. Notice that
we have used the optional parameter sep= ". " inside the print() statement. Hence, the output includes
items separated by . not comma.
The print(“string”) statement Example
We can pass the string in the print( ) method. # Python program to demonstrate
Example # print() method
x = "Python is awesome" print("ABC")
print(x) # code for disabling the soft space feature
OUTPUT: print('A', 'B', 'C')
Python is awesome Output
In the above example, we can see that in the case of the 2nd ABC
print statement there is a space between every letter and the A B C
print statement always add a new line character at the end of
the string. This is because after every character the sep parameter is printed and at the end of the string
the end parameter is printed.
The print(“variable list”) statement
We can also use the print() function to print Python variables. For example,
Example: Output
x = 97 Example: 2
number = -10.6 5
print(x) name = "Programming"
# print literals -10.6
print(5)
# print variables Programming
print(number)
print(name)
9
:= Places the sign to the left most position
:+ Use a plus sign to indicate if the result is positive or negative
:- Use a minus sign for negative values only
: Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers)
:, Use a comma as a thousand separator
:_ Use a underscore as a thousand separator
:b Binary format
:c Converts the value into the corresponding unicode character
:d Decimal format
:e Scientific format, with a lower case e
:E Scientific format, with an upper case E
:f Fix point number format
:F Fix point number format, in uppercase format (show inf and nan as INF and NAN)
:g General format
:G General format (using a upper case E for scientific notations)
:o Octal format
:x Hex format, lower case
:X Hex format, upper case
:n Number format
:% Percentage format
INPUT STATEMENTS
Python input() function is used to get input from the user.
It prompts for the user input and reads a line. After reading data, it converts it into a string and returns
that.
Syntax: input ([prompt]) Output:
prompt: It is a string message which prompts for the user input. Enter a value: 56
Example 1: You entered: 56
val = input("Enter a value: ")
print("You entered:",val)
Example 2: Output:
val = int(val) Enter an integer: 3
sqr = (val*val) Square of the value: 9
print("Square of the value:",sqr)
COMMENTS
Write note on comments. (5m)
Comments are the non executable statements in a program.
They are added to describe the statements in Python code. It can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Hash sign (#) is not inside a string literal begins a comment. All characters following the # and up to end
of the line are part of the comment.
Example:
#This is a comment
Output:
print("Hello, World!")
Hello, World!"
#This is a comment
Hello, World!"
#written in
Hello, World!"
#more than just one line
print("Hello, World!")
"""
This is a comment
written in
more than just one line"""
print("Hello, World!")
INDENTATION
What is intentation? (5m)
Output:
Indentation refers to the white spaces at the beginning of a code line.
Welcome to Python
10 Thank you
End the program
Where in other programming languages the indentation in code is for readability only, the indentation in
Python is very important.
Python uses indentation to indicate a block of code.
Example:
name = 'Python'
if name == 'Python':
print('Welcome to Python')
print('Thank you')
else:
print('Not Python ')
print('Exit')
print('End the program')
OPERATORS
Explain in detail about operators (5m)
Operators are used to perform operations on variables and values.
In a particular programming language, operators serve as the foundation upon which logic is
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Unary Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Python arithmetic operators are used to perform mathematical operations on numerical values.
These operations are Addition, Subtraction, Multiplication, Division, Modulus, Exponents and Floor
Division.
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
Example: Output:
a = 21
b = 10 a + b : 31
print ("a + b : ", a + b) a - b : 11
print ("a - b : ", a - b) a * b : 210
print ("a * b : ", a * b) a / b : 2.1
print ("a / b : ", a / b) a%b: 1
print ("a % b : ", a % b) a ** b : 16679880978201
print ("a ** b : ", a ** b) a // b : 2
print ("a // b : ", a // b)
Comparison operators
11
Python comparison operators compare the values on either sides of them and decide the relation among
them. They are also called relational operators.
These operators are equal, not equal, greater than, less than, greater than or equal to and less than or equal
to.
= Assignment Operator a = 10
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
There are following Bitwise operators supported by Python language
Operator Name Example
<< Binary Left Shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off
>> Binary Right Shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
Example
Following is an example which shows all the above bitwise operations:
a = 60 # 60 = 0011 1100 Output:
b = 13 # 13 = 0000 1101
c=a&b # 12 = 0000 1100 a & b : 12
print ("a & b : ", c)
a | b : 61
c=a|b # 61 = 0011 1101
print ("a | b : ", c) a ^ b : 49
c=a^b # 49 = 0011 0001
print ("a ^ b : ", c) ~a : -61
c = ~a; # -61 = 1100 0011
a >> 2 : 240
print ("~a : ", c)
c = a << 2; # 240 = 1111 0000 a >> 2 : 15
print ("a << 2 : ", c)
c = a >> 2; # 15 = 0000 1111
print ("a >> 2 : ", c)
Logical Operators
There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
13
Operator Description Example
and Logical AND If both the operands are true then condition (a and b) is true.
becomes true.
not Logical NOT Used to reverse the logical state of its Not(a and b) is false.
operand.
Example: Output:
price = 9.99 True
print(price > 9 and price < 10) True
print(price > 9 or price < 5) True
print(not price > 10)
Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
Operator Description Example
not in Evaluates to true if it does not finds a variable x not in y, here not in results in a 1
in the specified sequence and false otherwise. if x is not a member of sequence y.
Example:
x = 'Hello world' Output:
y = {1:'a', 2:'b'} True
True
print('H' in x) # prints True
True
print('hello' not in x) # prints True
False
print(1 in y) # prints True
print('a' in y) # prints False
Identity Operators
Identity operators compare the memory locations of two objects.
Operator Description Example
14
print(x3 is y3) # prints False
Operator Precedence and Associativity
The order in which the operators are examined is crucial to understand since it tells us which operator
needs to be considered first. Below is a list of the Python operators' precedence tables.
Operator Description
* / % // the division of the floor, the modules, the division, and the multiplication.
<= < > >= Comparison operators (less than, less than equal to, g8456
reater than, greater then equal to).
EXPRESSIONS
Write note on expression and their types. (5m)
In any programming language, an expression is any legal combination of symbols (like variables,
constants and operators) that represents a value.
Every language has its own set of rules that define whether an expression is valid or invalid in that
language.
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.
These operators use constants and variables to form an expression AB+C-5 is an example of an
expression, where,+, and are operators; A, B, and C are variables; and 5 is a constant.
Some valid expressions in Python are: a x = a/b, y=a*b, z = a^ b, x=a>b, etc.
When an expression has more than one operator, then the expression is evaluated using the operator
precedence chart.
An example of an illegal expression can be a+, -b, or, <y++.
When the program is compiled, it also checks the validity of all expressions.
If an illegal expression is encountered, an error message displayed
Types of Expressions
Python supports different types of expressions that can be classified as follows:
Based on the position of operators in an expression: These type of expressions include:
15
Infix Expression: It is the most common used type of expression in which the operator is placed
in between the operands. Example a=b-c
Prefix Expression: In this type of expression, the operator is placed before the operands.
Example: a=-bc.
Postfix Expression: In this type of expression, the operator is placed after the operands. Example:
a=bc-
Based on the data type of the result obtained on evaluating an expression: These type of expressions
include:
Costant Expression: One that involves only constants Example: 8+9-2
Integral Expression: One that produces an integer result after evaluating the expression.
Example:
a = 10
b=5
c=a*b
Floating Point Expression: One that produces floating point results. Example: a* b / 2
Relational Expressions: One that returns either True or False value Example: c = a>b
Logical Expression: One that combines two or more relational expressions and returns a value as
True or False. Example: a>b && y!= 0
Bitwise Expression: One that manipulates data at bit level. Example: x&z
Assignment Expressions: One that assigns a value to a variable Example c=a+b or c = 10
Example:
a = 15 + 1.3
print('Value of constant expression:',a)
x = 40
y = 12
add = x + y
print('Value of arithmetic expression:',add) Output:
z = 12.0 Value of constant expression: 16.3
b = x + int(z) Value of arithmetic expression: 52
print('Value of integer expression:',b) Value of integer expression: 52
c=x/y Value of floating point expression:
print('Value of floating point expression:', c) 3.3333333333333335
d = (x + y) >= (y - z) Value of relational expression: True
print('Value of relational expression:',d) Value of logical expression: False
P = (10 == 9) Value of bitwise expression: 10
Q = (7 > 5)
R = P and Q
print('Value of logical expression:',R)
e = x >> 2
print('Value of bitwise expression:',e)
TYPE CONVERSIONS
What is type conversion? (5m)
Python defines type conversion functions to directly convert one data type to another type.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion: By the Python program automatically.
2. Explicit Type Conversion: The programmer must perform this task manually
Implicit Type Conversion:
The Python interpreter automatically converts one data type to another without any user involvement.
Example: Output:
x = 10 x is of type: <class 'int'>
print("x is of type:",type(x)) y is of type: <class 'float'>
y = 10.6 20.6
print("y is of type:",type(y)) z is of type: <class 'float'>
z=x+y
16
print(z)
print("z is of type:",type(z))
Explicit Type Conversion:
In Explicit Type Conversion in Python, the data type is manually changed by the user as per their
requirement.
With explicit type conversion, there is a risk of data loss since we are forcing an expression to be changed
in some specific data type. Various forms of explicit type conversion are:
int(a, base): This function converts any data type to integer.
float(): This function is used to convert any data type to a floating-point number.
ord() : This function is used to convert a character to integer.
hex() : This function is to convert integer to hexadecimal string.
oct() : This function is to convert integer to octal string.
tuple() : This function is used to convert to a tuple.
set() : This function returns the type after converting to set.
list() : This function is used to convert any data type to a list type.
dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
str() : Used to convert integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag) number.
chr(number): This function converts number to its corresponding ASCII character.
Example:
x = 15 Output:
y = 2.8 Value of int to float: 15.0
z = 1j Value of float to int: 2
print('Value of int to float:',float(x)) Value of int to complex: (15+0j)
print('Value of float to int:',int(y)) Value of char to int: 65
print('Value of int to complex:',complex(x)) value of int to hexadecimal: 0xf
s = 'A' value of int to oct: 0o17
Value of string to tuple ('A',)
print ('Value of char to int:',ord(s))
value of string to set {'A'}
print('value of int to hexadecimal:',hex(x))
value of string to set ['A']
print('value of int to oct:',oct(x))
s1 = 'python'
print ('Value of string to tuple',tuple(s))
print ('value of string to set',set(s))
print ('value of string to set',list(s))
PYTHON ARRAYS
Write note on python arrays. (5m)
An array is a collection of items stored at contiguous memory locations.
The idea is to store multiple items of the same type together.
This makes it easier to calculate the position of each element by simply adding an offset to a base value,
i.e., the memory location of the first element of the array
Element - Each item stored in an array is called an element.
Index - The location of an element in an array has a numerical index, which is used to identify the
position of the element.
1. As per example, Index starts with 0. Array length is 10, which means it can store 10 elements.
2. Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.
DEFINING AND PROCESSING ARRAYS
Array in Python can be created by importing array module.
Syntax: from array import *
arrayName = array(data_type, value_list])
17
This is used to create an array with data type and value list specified in its arguments.
We can access each element of an array using the index of the element.
Example:
import array as arr Output:
a = arr.array('i', [2, 4, 6, 8]) First element: 2
print("First element:", a[0]) Second element: 4
print("Second element:", a[1]) Second last element: 8
print("Second last element:", a[-1])
Some of the data type used for creating array
Some of the data type used for creating array
ARRAY METHODS
Explain array methods. (5m)
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable ), to the end of the current list
index() Returns the index of the first element with the specified value
18
pop() Removes the element at the specified position
TEXT BOOKS:
ReemaThareja, ―Python Programming using problem solving approach‖, First Edition, 2017, Oxford
University Press.
Dr. R. NageswaraRao, ―Core Python Programming‖, First Edition, 2017, Dream tech Publishers.
https://www.guru99.com/python-tutorials.html
https://www.w3schools.com/python/python_intro.asp
https://www.programiz.com/python-programming
19
POSSIBLE QUESTIONS
ONE MARK
1. Who developed Python Programming Language?
a) Wick van Rossum b) Rasmus Lerdorf c) Guido van Rossum d) Niene Stom
2. Which type of Programming does Python support?
a) object-oriented programming b) structured programming
c) functional programming d) all of the mentioned
3. Is Python case sensitive when dealing with identifiers?
a) no b) yes c) machine dependent d) none of the mentioned
4. Which of the following is the correct extension of the Python file?
a) .python b) .pl c) .py d) .p
5. Is Python code compiled or interpreted?
a) Python code is both compiled and interpreted b) Python code is neither compiled nor interpreted
c) Python code is only compiled d) Python code is only interpreted
6. All keywords in Python are in _________
a) Capitalized b) lower case c) UPPER CASE d) None of the mentioned
7. Which of the following character is used to give single-line comments in Python?
a) // b) # c) ! d) /*
8. What is the maximum possible length of an identifier?
a) 31 characters b) 63 characters c) 79 characters d) none of the mentioned
9. Which of the following is invalid?
a) _a = 1 b) __a = 1 c) __str__ = 1 d) none of the mentioned
10. Which of the following is an invalid variable?
a) my_string_1 b) 1st_string c) foo d) _
11. Which is the correct operator for power(xy)?
a) X^y b) X**y c) X^^y d) None of the mentioned
12. Which one of these is floor division?
a) / b) // c) % d) None of the mentioned
13. What is the answer to this expression, 22 % 3 is?
a) 7 b) 1 c) 0 d) 5
14. Identify the words which best describes Python
a) Interpreted b) reliable c) simple d) All of these
15. Select the integer literal
a) 10.345 b) 9 c) '9' d) "9"
16. Which of these will not be stored as a float?
a)23.0 b) 1/ 3 c) 15 d) ABC
17. Which operator gives the remainder after the division?
a) / b) // c) % d) *
20
18. Python allows you to specify Unicode text by prefixing the string with which character?
a) U b) R c) S d) A
19. Identify the correct variable name
a) this_is_a_variable b) 123abc - 10.22 c) ThisBook - "Python" d) Sname!
20. A variable can be removed using which --------- keyword?
a) remove b) clear c) del d) delete
21. To specify more than one statements in a single line, use a ------- to separate the statements.
a) , b) ; c) : d) /
22. Comments start with which symbol?
a) " b)# c) // d) *
21
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-8.
STAFFCODE: SCS117 CLASS: I CS ‘B’
SUBJECT: PYHON PROGRAMMING SUB.CODE: 23UCSCC01
UNIT-II
CONTROL STATEMENTS
Explain about control statement. (10m)
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.
A control statement can either comprise of one or more instructions.
The three fundamental methods of control flow in a programming language are
1. sequential,
2. selection and
3. iterative control.
Each statement is executed one by one in order from top to bottom. That is, the second statement is
executed after the first, the third statement is executed after the second, so on and so forth. This method
is known as sequential control flow.
However, in some cases it may be necessary to either execute only a selected set of statements (i.e.,
selection control) or execute a set of statements repeatedly (i.e., iterative control). Thus, the decision
control statements can alter the flow of a sequence of instructions. Such type of conditional processing
provided by the decision control statements extends the usefulness of programs.
It allows the programmers to build a program that determine which statements of the code should be
executed and which should be ignored.
The categorization of decision control statements.
1. Sequential control statements
statement 1
statement 2
…….
…….
statement n
2. Selection control statements
statement 1
test condition
true false
…… ……
If statement
Explain about if statement with example (5m)
If statement checks the condition, if the condition is true executes the certain statements which is
specified in true part. If the condition is false skips the statements.
Note:
(i) : must be specified after the condition, it separates the header of the statement from body.
(ii) The line after: must be indentation i.e., 4 spaces for indentation.
(iii) All the lines intended with same amount after: will be the block of statements which belong to that
if statement.
Syntax:
if condition:
Statement_1
Statement_2
Statement_3
.....
Statement_n
Example:
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number
If …else statement:
Explain about if …else statement with example
(5m)
If the condition is true, true part statements of if
statements are executed. If the condition is false,
false part statements of if statement are executed.
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Example:
age = int (input("Enter your age: "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
23
Output:
Enter your age: 90
You are eligible to vote !!
Nested if statement:
Explain about nested if statement with example (5m)
Nested if statement is used to check multiple conditions. It checks the first condition if it true check
the second condition if it is true check the third condition and so on. If all the conditions become true,
then true part statements are executed.
Syntax:
# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)
Example:
number = -5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')
# inner else statement
else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')
Output:
Number is negative
If…. elif else statement:
Explain about if…. elif else statement with example (5m)
If the condition is true, true part statements are executed. If the condition is false, check another
condition.
if it is true that true part is executed. If all the conditions are false, else part statements are
executed.
Syntax:
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example:
number = int(input("Enter the number?"))
if number==10:
print("The given number is equals to 10")
elif number==50:
print("The given number is equal to 50");
elif number==100:
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");
24
Output:
Enter the number?30
The given number is not equal to 10, 50 or 100
ITERATIVE STATEMENTS
Python supports basic loop structures through iterative statements. Iterative statements are decision
control statements that are used to repeat the execution of a list of statements.
Python language supports two types of iterative statements
1. while loop
2. for loop.
While Loop
Explain about while loop with example. (5m)
While loop executes the block of statements until the condition is true (i.e., ) if the condition becomes
false terminate the loop. In while loop programmer has to initialize the loop variable at the beginning
(i.e., ) before the loop and update loop variable inside the loop according to condition.
Syntax:
Initialvalue
while condition:
# body of while loop
Example:
i=1
while i<=10:
print(i, end=' ')
i+=1
Output:
1 2 3 4 5 6 7 8 9 10
For Loop
Explain about for loop with example. (5m)
A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, etc.) and execute a
block of code for each element in the sequence.
Python for loop can be used in two ways.
1. Using Sequence
2. Using range() function
Using Sequence
1. The sequence is referred to as list, set, string, tuple, and
dictionary in Python. We can extract the elements of the
sequence using for loop. Below is the syntax for loop.
Syntax:
for element in sequence:
# Code to be executed for each element
Example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
Output:
1
2
3
4
5
Using range() function
The range function() generates the sequence of the numbers. For example, if we execute the range(5) and it
will generate the 0 to 4.
Syntax:
range(start, stop, step-size)
25
It accepts the three arguments.
The start represents the beginning of the iteration.
The stop indicates the end of for loop. It will iterate till stop-1.
The step size skips the specific number of iteration. By default, the step size is 1.
Example
values = range(4)
for i in values:
print(i)
Output:
0
1
2
27
for loop
while loop
for letter in "HELLO":
i=1
print(letter, end=" ")
while(i<0):
else:
print(i)
print("\nDone")
i=i-1
OUTPUT
else:
HELLO
print(i,"is not negative so loop did not execute")
Done
OUTPUT
Nested Loop
1 is not negative so loop did not execute
Python allows its users to have nested
loops, that is, loops that can be placed inside other loops.
A for loop can be used to control the number of times a particular set of statements will be executed.
Another outer loop could be used to control the number of times that a whole loop is repeated.
Loops can be nested to any desired level. However, the loops should be properly indented to identify
which statements are contained within each for statement. 1
Write a program to print the following pattern.
*
** for i in range(1,6):
*** print()
**** for j in range(i):
***** print("*",end=' ')
TEXT BOOKS:
ReemaThareja, ―Python Programming using problem solving approach‖, First Edition, 2017, Oxford
University Press.
Dr. R. NageswaraRao, ―Core Python Programming‖, First Edition, 2017, Dream tech Publishers.
https://www.guru99.com/python-tutorials.html
https://www.w3schools.com/python/python_intro.asp
https://www.programiz.com/python-programming
POSSIBLE QUESTIONS
ONE MARK
1. Which part of if statement should be indented?
b) The first statement
c) All the statement
d) None of these
e) Statements within the if block
2. How many numbers will be printed?
i=5
while i>=0:
print(i)
i = i -1
a) 5 b) 6 c) 4 d) 0
3. How many numbers will be printed?
i = 10
while True:
print(i)
i = i -1
if i<=7:
break
29
a) 1 b) 3 c) 2 d) 4
4. Which statement ends the current iteration of the loop and continues with the next one?
a) break b) skip c) continue d) pass
5. Which of the following in placed after the if condition?
a) : b) ; c) . d) ,
6. Which statement is used to terminate the execution of the nearest enclosing loop in which it appears?
a) break b) pass c) continue d) jump
7. Which statement indicates a NOP?
a) break b) continue c) pass d) jump
8. What would happen if we replace the break statement in the code with a 'continue'?
a) It will stop executing
b) It would run foreven
c) You will have to press Ctrl + C
d) There would be no change
9. How many lines will be printed by this code?
a) 1 b) 0 c) 10 d) countless
10. What keyword would you use to add an alternative condition to an if statement?
a) else if b) elif c) elseif d) None of these
11. What will be the output of given Python code?
str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print(c)
a) 2 b) 3 c) 4 d) 0
12. Which of the following sequences would be generated bt the given line of code?
range (5, 0, -2)
a) 5 4 3 2 1 0 -1 b) 5 4 3 2 1 0 c) 5 3 1 d) None of the above
5 Marks
1. Write about if-else statement with an example.
2. Write about nested if with an example.
3. Write a Program to test whether a number entered by the user is negative, positive, or equal to zero.
4. Explain the While statement.
5. Explain in detail about nested loop.
10 Marks
1. Explain in detail about control statement.
2. Write a program to
a) Find whether the given number is an Amstrong number or not.
b) Enter a number and then calculate the sum of its digits.
3. Explain in detail about for loop with suitable example.
4. Write about jump statement with suitable example.
30
31
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-8.
STAFFCODE: SCS117 CLASS: I CS ‘B’
SUBJECT: PYHON PROGRAMMING SUB.CODE: 23UCSCC01
UNIT-III
FUNCTIONS – Introduction
Write short notes on Functions. (5 Marks)
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.
……….. def Fun1( ):
Fun1( ) ………..
……… …………
When the function 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.
Suppose if func1() calls function named func2(). Therefore, func1() is known as the calling function
and func2() is known as the called function.
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
Need for Functions
Explain the purpose of functions. (5 Marks/10 Marks)
1. Dividing the program into separate well defined functions facilitates each function to be written and
tested separately. This simplifies the process of program development.
2. Understanding, coding, and testing multiple separate functions are far easier than doing the same for
one huge function.
3. If a big program has to be developed without the use of any function, then there will be large number of
lines in the code and maintaining that program will be a big mess. Also, the large size of the program is a
serious issue in micro-computers where memory space is limited.
4. 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 speeds up program
development by allowing the programmer to concentrate only on the code that has to be written from
scratch (i.e, they are not available in the libraries).
5. 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.
6. 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.
Code reuse is one of the most prominent reason to use functions . Large programs usually follow the
DRY principle, that is, Don't Repeat Yourself principle. Once a function is written, it can be called
multiple times within the same or by a different program wherever its functionality is required.
Functions provide better modularity for our application and a high degree of code reuse.
FUNCTION DEFINITION
Discuss Function definition. (5 Marks)
Any function can be compared to a black box (that is used for an entity having unknown
implementation) that takes in input, processes it and then produces out the result.
However, we may also have a function that does not take any inputs at all, or that does not return
anything at all.
Terminology:
32
A function, f that uses another function g, is known as the calling function and g is known as the called
function.
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. Users can also write their own functions.
Such functions are called user defined functions.
There are two basic types of functions, built-in functions and user defined ones.
The built-in functions comes as a part of the Python language.
For examples, dir(), len(), or abs ().
The user defined functions are functions created by users in their programs using the def keyword.
Function naming follows the same rules of writing identifiers in Python.
Key points:
1. Function blocks starts with the keyword def.
2. The keyword is followed by the function name and parentheses ( ). The function name is used to
uniquely identify the function.
3. After the parentheses a colon (:) is placed.
4. Parameters or arguments that the function accepts are placed within parentheses. Through these
parameters values are passed to the function. They are optional. In case no values are to be passed,
nothing is placed within the parenthesis.
5. The first statement of a function can be an optional statement the documentation string of the function or
docstring describe what the function does.
6. The code block within the function is properly indented to form the block code.
7. A function may have a return[expression] statement That is, the return statement is optional. If it exist,
it passes back an expression to the caller. A return statement with no arguments is the same as return
None.
8. We can assign the function name to a variable. Doing this will allow you to call the same function using
the name of that variable.
Example
def diff(x,y):
return(x-y)
a = 20
b = 10
operation = diff # function name assigned to a variable
print (operation(a,b)) # function called using variable name
OUTPUT
10
The words before parentheses specify the function name, and the comma-separated values inside the
parentheses are function arguments.
When a function is defined, space is allocated for that function in the memory. A function definition
comprises of two parts:
1. Function header
2. Function body
The syntax of a function definition can be given as:
def function name (variable1, variable2,..): Function Header
documentation string
statement block Function Body
return [expression]
Write a function that displays a string repeatedly
def func():
for 1 in range(4):
33
print("Hello World")
func()
OUTPUT
Hello world
Hello world
Hello World
Hello World
The indented statements form body of the function.
The parameter list in the function definition as well as function declaration must match with each other.
FUNCTION CALL
Explain Function call in detail. (5 Marks)
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.
The syntax of calling a function that does not accept parameters is simply the name of the function
followed by parenthesis, which is given as,
function_name()
Function call statement has the following syntax when it accepts parameters.
function_name (variablel, variable2,-)
When the function is called, the interpreter checks that the correct number and type of arguments are
used in the function call. It also checks the type of the returned value (if it returns a value to the
calling function).
List of variables used in function call is known as the actual parameter list. The actual parameter list
may be variable names, expressions, or constants.
Function Parameters
Discuss Function Parameters. (5 Marks)
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.
Parameters are specified within the pair of parentheses in the function definition and are separated by
commas.
Key points to remember while calling the function
The function name and the number of arguments in the function call must be same as that given in the
function definition. Otherwise, an error will be returned.
Names of variables in function call and header of function definition may vary.
If the data type of the argument passed does not match with that expected in the function, then an error is
generated.
VARIABLE SCOPE AND ITS LIFE TIME
Explain the scope and lifetime of variable. (5 Marks)
List out the differences between the local and global variables. (5 Marks)
Scope of the variable - Part of the program in which a variable is accessible is called its scope.
Lifetime of the variable - Duration for which the variable exists is called its lifetime .
Local and Global Variables
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 golden rule, use only those variables or objects that are meant to be used globally, like functions
and classes, should be put in the global section of the program (i.e., above any other function or line of
code).
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 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 (provided a variable with the
same name is not defined in the local scope).
34
Example: Program to understand the difference between local and global variables
num1 = 10
#global variable
print("Global variable num1: ", num1)
def func(num2):
#num2 is function parameter
print("In Function Local Variable num2", num2)
num3 = 38
#num3 is a local variable
print("In Function Local Variable num3",num3)
func(28) #28 is passed as an argument to the function
print("num1 again", num1)
#global variable is being accessed
#Error- local variable can't be used outside the function in which it is defined
print("num3 outside function = ", num3)
OUTPUT
Global variable num1 - 10
In Function Local Variable num2 28
In Function Local Variable num3 = 38
num1 again - 10
num3 outside function -
Traceback (most recent call last):
File "C:\Python34\Try.py", line 12, in <module>
print("num3 outside function = ", num3)
NameError: name "num3' is not defined
Programming Tip: Trying to access local variable outside the function produces an error. Variables can
only be used after the point of their declaration
The following Table lists the differences between global and local variables.
Global Variables Local Variables
1. They are defined in the main body of the 1. They are defined within a function and is local to that
program file. function.
2. They can be accessed throughout the 2. They can be accessed from the point of its definition until
program file. the end of the block in which it is defined.
3. Global variables are accessible to all 3. They are not related in any way to other variables with
functions in the program. the same names used outside the function
Using the Global Statement
Explain Global statement in detail. (5 Marks)
Write a Python program to illustrate the concept of “global” keyword. (5 Marks)
To define a variable defined inside a function as global, we must use the global statement.
This declares the local or the inner variable of the function to have module scope.
Example Program to demonstrate the use of global statement
var= "Good"
def show():
global var1
varl= "Morning"
print("In Function var is ", var)
show()
print("Outside function varl is ", var1)
print("var is ", var)
OUTPUT
In Function var is Good
Outside function, varl is Morning
var is Good
Programming Tip: All variables have the scope of the block.
Key points to remember
35
We 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. For
example, Program to demonstrate name clash of local and global variable
var="Good"
def show():
var = "Morning"
print("In Function var is ",var)
show()
print("outside function, var is ",var)
OUTPUT
In Function var is Morning
outside function, var is Good
If we have a global variable and then create another global variable using the global statement,
then changes made in the variable will be reflected everywhere in the program.
Example Program to demonstrate modifying a global variable
var= "Good"
print("Initially var is ",var)
def show():
global var
var = "Morning"
print("In Function var is ",var)
show()
print("Outside function, var is", var)
var = "Fantastic"
print("Outside function, after modification, var is ",var)
OUTPUT
Initially var is Good
In Function var is Morning
Outside function, var is Morning
Outside function, after modification, var is Fantastic
In case of nested functions (function inside another function), the inner function can access
variables defined in both outer as well as inner function, but the outer function can access
variables defined only in the outer function.
Example Program to demonstrate access of variables in inner and outer functions
def outer_fun():
outer_var=10
def inner_func():
inner_var=20
print("Outer variable = ",outer_var)
print("Inner variable = ",inner_var)
inner_func()
print("Outer variable = ",outer_var)
print("Inner variable = ",inner_var)
outer_fun()
OUTPUT
Outer variable = 10
Inner variable = 20
Outer variable = 10
Traceback (most recent call last):
File "Z:/innerouter.py", line 10, in <module>
outer_fun()
File "Z:/innerouter.py", line 9, in outer_fun
print("Inner variable = ",inner_var)
NameError: name 'inner_var' is not defined
36
Programming Tips Arguments specified within parentheses. If there is more than one argument, then
they are separated using comma.
If a variable in the inner function is defined with the same name as that of a variable defined in the
outer function, then a new variable is created in the inner function.
Example Program to demonstrate name clash variables in case of nested functions
def outer_func():
var = 10
def inner func():
var = 20
print("Inner Variable= ”, var)
inner_func()
print("Outer Variable= ", var)
outer_func()
OUTPUT
Inner Variable = 20
Outer Variable= 10
Note - In the above program, even if we use global statement we would get the same result as global
statement is applicable for the entire program and not just for outer function.
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.
Programming Tip: Try to avoid the use of global variables and global statement.
def f( ):
global str
print (str)
str = "Hello World!
print(str)
str = "Welcome to Python Programming!”
f()
OUTPUT
Welcome to Python Programming!
37
Hello World!
Return STATEMENT
Explain the concept of “return” statement. (5 Marks)
A Python function may or may not return a value. If we want our function to return some value to a
function call, we use the return statement. For example,
def add_numbers():
...
return sum
Here, we are returning the variable sum to the function call.
Note: The return statement also denotes that the function has ended. Any code after return is not executed.
Example 2: Function return Type
# function definition
def find_square(num):
result = num * num
return result
function call
square = find_square(3)
print('Square:',square)
# Output: Square: 9
FUNCTION ARGUMENTS
Write short notes on Function Arguments with its types. (5 Marks/10 Marks)
1. Required arguments
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.
KEYWORD ARGUMENTS
When we call a function with some values, the values are assigned to the arguments based on their
position.
Python also allows 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 when used in function calls, helps the function to identify the arguments by the
parameter name. This is especially beneficial in two cases.
First, if you skip arguments.
Second, if in the function call you change the order of parameters. That is, in any order different from that
specified in the function definition.
Example Program to demonstrate keyword arguments
def display (str, int_x, float_y):
print("The string is ",str)
print("The integer value is ",int_x)
print("The floating point value is ", float_y)
display (float_y=6789.845, str="Hello", int_x = 1234)
OUTPUT
The string is Hello
The integer value is 1234
The floating point value is 6789.845
Example:
def display(name, age, salary):
print("Name : ", name)
print("Age : ", age)
38
print("Salary: ", salary)
n="RAM"
a=29
s=500000
display(salary=s,name=n,age=a)
OUTPUT
Name : RAM
Age : 29
Salary: 500000
Key points to remember
All the keyword arguments passed should match one of the arguments accepted by the function.
The order of keyword arguments is not important.
In no case an argument should receive a value more than once.
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. 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 value for one or more arguments.
Note - A default argument assumes a default value if a value is not provided in the function call for that
argument.
VARIABLE-LENGTH ARGUMENTS
39
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 uses an
asterisk (*) before the parameter name.
Syntax for a function using variable arguments can be given as
def functionname([arg1, arg2, .....] *var_args tuple):
function statements
return [expression]
Example Program to demonstrate the use of variable-length arguments
def func(name, *fav_subjects):
print("\n",name,"likes to read")
for subject in fav_subjects:
print(subject)
func("Goransh", "Mathematics", "Android Programming")
func("Richa", "C", "Data Structures", "Design and Analysis of Algorithms")
func("Krish")
OUTPUT
Goransh likes to read Mathematics Android Programming
Richa likes to read C Data Structures Design and Analysis of Algorithms
Krish likes to read
In the above program, in the function definition, we have two parameters - one is name and the other is
variable-length parameter fav_subjects.
The function is called three times with 3, 4, and 1 parameter(s) respectively.
The first value is assigned to name and the other values are assigned to parameter fav_subjects.
Key points to remember
The arbitrary number of arguments passed to the function basically forms a tuple before being passed
into the function.
Inside the called function, for loop is used to access the arguments.
The variable-length arguments if present in the function definition should be the last in the list of formal
parameters.
RECURSION
Explain Recursion in detail. (5 Marks)
Write a Python program to calculate factorial of a number using recursion. (5 Marks)
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:
1. base case, in which the problem is simple enough to be solved directly without making any further
calls to the same function.
2. recursive case, in which first the problem at hand is divided into simpler sub-parts. Second, the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
Recursion utilized divide and conquer technique of problem solving.
Divide and conquer technique is a method of solving a given problem by dividing it into two or more
smaller instances.
Each of these smaller instances is recursively solved, and the solutions are combined to produce a
solution for original problem. Therefore, recursion is used for defining large and complex problems in
terms of a smaller and more easily solvable problem.
Every recursive function must have least one base case. Otherwise, the recursive function will generate an
infinite sequence of calls thereby resulting in an error condition known as an infinite stack.
5! = 5 X 4 X 3 X 2 X 1
= 120
This can be written as
5! = 5 X 4!, where
4! = 4 X 3!
40
Therefore,
5! = 5 X 4 X 3!
Similarly, we can also write,
5! = 5 X 4 X 3 X 2!
Expanding further
5! = 5 X 4 X 3 X 2 X 1!
We can write a recursive function to calculate the factorial of a number. Note that we have said every
recursive function must have a base case and a recursive case. For the factorial function,
1. Base case is when n=1, because if n=1, the result is known to be 1 as 1!= 1.
2. Recursive case of the factorial function will call itself but with a smaller value of n, this case can
be given as factorial(n) = n* factorial (n-1)
Example Program to calculate the factorial of a number recursively
def fact(n):
if(n==1 or n==0):
return 1
else:
return n*fact(n-1)
n=int(input("Enter the N value: "))
print("The factorial of ",n,"is",fact(n))
OUTPUT
Enter the N value: 5
The factorial of 5 is 120
Basic steps of a recursive program.
Step 1: Specify the base case which will stop the function from making a call to itself.
Step 2: Check to see whether the current value being processed matches with the value of the base case. If
yes, process and return the value.
Step 3: Divide the problem into a smaller or simpler sub-problem.
Step 4: Call the function on the sub-problem.
Step 5: Combine the results of the sub-problems.
Step 6: Return the result of the entire problem.
Note The base case of a recursive function acts as the terminating condition. So, in the absence of an
explicitly defined base case, a recursive function would call itself indefinitely.
42
Whenever a recursive function is called, some amount of overhead in the form of a run-time stack is
always involved. Before jumping to the function with a smaller parameter, the original parameters, the
local variables and the return address of the calling function are all stored on the system stack. Therefore,
while using recursion a lot of time is needed to first push all the information on the stack when function
is called and then time is again involved in retrieving the information stored on the stack once the control
passes back to the calling function.
To conclude, the pros and cons of recursion.
Pros - The benefits of using a recursive program are:
1. Recursive solution often tend to be shorter and simpler than non-recursive ones.
2. Code is clearer and easier to use.
3. Recursion uses the original formula to solve a problem.
4. It follows a divide and conquer technique to solve problems.
5. In some instances, recursion may be more efficient.
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. Whitespace
character, exclamation mark and any other symbol(?,<,>,*,@,#,$,&,%,etc.) that forms a part of the string
would be assigned its own index number.
Traversing a String: A string can be traversed by accessing character(s) from one index to another.
Example Program to demonstrate string traversal using indexing
message ="Hello!"
index=0
for i in message:
print("message[", index, "] = ", i)
index += 1
OUTPUT
message[0] = H
message[1] = e
message[2] = l
message[3] = l
message[4] = o
message[5] = !
43
STRING OPERATIONS
Explain String Operations with neat examples. (5,10 Marks)
Concatenating, Appending, And Multiplying Strings
The word concatenate means to join together. Python allows you to concatenate two strings using the
‘+’ operator as shown in the following example.
Example Program to concatenate two strings using + operator
strl = "Hello "
str2 = "World"
str3= strl + str2
print("The concatenated string is : ", str3)
OUTPUT
The concatenated string is: Hello World
Append mean to add something at the end . In Python, We can add one string at the end of another
string using the + operator.
Example Program to append a string using + operator
str = "Hello, "
name=input("\n Enter your name: ")
str+= name
str+= ".Welcome to Python Programming."
print (str)
OUTPUT
Enter your name : Mano
Hello, Mano. Welcome to Python Programming.
We can use the operator '*' to repeat a string n number of times.
Example Program to repeat a string using operator
str = "Hello"
print (str*3)
OUTPUT
HelloHelloHello
The str() function is used to convert values of any other type into string type. This helps the
programmer to concatenate a string with any other data which is otherwise not allowed.
str1= "Hello"
var = 7
str2 = strl + str(var)
print(str2)
OUTPUT
Hello7
The print statement prints one or more literals or values in new lines. If we don't want to print on a new
line then, add end statement with a separator like whitespace, comma, etc.
print("Hello", end=' ')
print("world")
OUTPUT
Hello World
A raw string literal which is prefixed by an 'r' passes all the characters as it is. They are not processed in
any special way, not even the escape sequences. Example Program to print a raw string
print("\n Hello")
print(r"\nworld")
OUTPUT
Hello
\nworld
Note The 'u' prefix is used to write Unicode string literals.
IMMUTABLE STRINGS
Explain Immutable strings. (5 Marks)
Python strings are immutable which means that once created they cannot be changed . Whenever we
try to modify an existing string variable, a new string is created.
44
Every object in Python is stored in memory. We can find out whether two variables are referring to the
same object or not by using the id(). The id() returns the memory address of that object. As both str1
and str2 points to same memory location, they both point to the same object.
Example Program to demonstrate string references using the id() function
str1 = "Hello"
print("Str1 is : ", str1)
print("ID of str1 is: ", id(str1))
str2 = "World"
print("Str2 is: ", str2)
print("ID of str1 is: ", id(str2))
str1 += str2
print("str1 after concatenation is : ", str1)
print("ID of str1 is: “, id(str1))
str3= str1
print("str3= ", str3)
print("ID of str3 is: “, id(str3))
OUTPUT
Str1 is : Hello
ID of str1 is: 45093344
Str2 is: World
ID of str1 is : 45093312
Str1 after concatenation is : Helloworld
ID of str1 is : 43861792
str3 = Helloworld
ID of str3 is: 43861792
BUILT-IN STRING METHODS AND FUNCTIONS
Explain String handling functions with neat examples. (10 Marks)
Strings are an example of Python objects. An object is an entity that contains both data (the actual string
itself) as well as functions to manipulate that data. These functions are available to any instance
(variable) of the object.
Python supports many built-in methods to manipulate strings.
A method is just like a function. The only difference between a function and method is that a method is
invoked or called on an object. For example, if the variable str is a string, then we can call the upper()
method as str.upper() to convert all the characters of str in uppercase.
Table - Commonly Used String Methods
FUNCTION USAGE EXAMPLE
capitalize() This function is used to str ="hello"
capitalize first letter of the print(str.capitalize())
string. OUTPUT Hello
center (width,fillchar) Returns a string with the str = "hello"
original string centered to a print(str.center (10, ‘*’)
total of width columns OUTPUT
andfilled with fillchar in **hello***
columns that do not have
characters.
count(str, beg, end) Counts number of times str str = "he"
occurs in a string. We can message = "helloworldhellohello”
specify beg as 0 and end as print (message. count (str,0, len(message)))
the length of the message to OUTPUT
search 3
the entire string or use any
other value to just search a
part of the string
endswith(suffix, beg, Checks if string ends with message ="She is my best friend
end) suffix; returns True if so and print(message.endswith("end",0, len(message)))
45
False otherwise. We can OUTPUT
either set beg=0 and end equal True
to the length of the message to
search entire string or use any
other value to search a part of
it.
startswith (prefix,beg, end) Checks if string starts with str = "The world is beautiful"
prefix; if so, it returns True print(str.startswith("Th",0,len(str)))
and False otherwise. We can OUTPUT
either set beg=0 and end True
equal to the length of the
message to search entire string
or use any other value to
search a part of it.
find(str, beg,end) Checks if str is present in message= "She is my best friend"
string. If found it returns the print (message. find("my",0, len(message)))
position at which str occurs OUTPUT
in string, otherwise returns -1. 7
We can either set beg=0 and
end equal to the length of the
message to search entire string
or use any other value to
search a part of it.
index(str, beg, end) Same as find but raises an message = "She is my best friend”
exception if str is not found. print (message. index("mine", 0,len (message)))
OUTPUT
valueError: substring not found
rfind(str, beg, end) Same as find but starts str = "Is this your bag?"
searching from the end. print (str.rfind("is", 0, len(str)))
OUTPUT
5
rindex(str, beg, end) Same as rindex but start str = "Is this your bag?"
searching from the end and print(str.rindex("you", 0, len(str)))
raises an exception if str is not OUTPUT
found. 8
isalnum( ) Returns True if string has at message = "JamesBond007"
least 1 character and every print(message.isalnum())
character is either a number or OUTPUT
an alphabet and False True
otherwise.
isalpha( ) Returns True if string has at message ="JamesBond007"
least 1 character and every print(message.isalpha())
character is an alphabet and OUTPUT
False otherwise. False
isdigit( ) Returns True if string contains message="007"
only digits and False print(message.isdigit())
otherwise. OUTPUT
True
islower( ) Returns True if string has at message = "Hello"
least 1 character and every print(message.islower())
character is a lowercase OUTPUT
alphabet and False otherwise. False
isspace( ) Returns True if string contains message = “ “
only whitespace characters print(message.isspace())
and False otherwise. OUTPUT
46
True
isupper( ) Returns True if string has at message ="HELLO"
least 1 character and every print (message.isupper())
character is an upper case OUTPUT
alphabet and False otherwise. True
splitlines([keepends]) The splitlines( ) returns a list print('Sun and \n\n Stars, Planets \r and Moon\r\
of the lines in the string. This n'.splitlines())
method uses the newline OUTPUT
characters like \r or \n to split ['Sun and ', '', ' Stars, Planets ', ' and Moon']
lines. Line breaks are not
included in the resulting list
unless keepends is given as
48
True.
50
THE PYTHON MODULE
Explain Python Module. (5 Marks)
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.
Name of Module
Every module has a name. We can find the name of a module by using the __name__ attribute of the
module.
Example Program to print the name of the module in which our statements is written
print("Hello")
print("Name of this module is : ", __name__)
OUTPUT
Hello
Name of this module is: __main__
Observe the output and always remember that the for every standalone program written by the user the
name of the module is __main__
dir( ) function
dir() is a built-in function that lists the identifiers defined in a module. These identifiers may include
functions, classes, and variables. The dir() works as given in the following example.
Example Program to demonstrate the use of dir() function
def print_var(x):
print(x)
x=10
print_var(x)
print(dir())
OUTPUT
10
[‘_builtins_’,’_doc_’,’_file_’,’_name_’,’_package_’,’print_var’,’x’]
If no name is specified, the dir() will returns the list of names defined in the current module. If we
mention the module name in the dir() function, it will return the list of the names defined in that module.
For example,
>>>dir(MyModule)
[‘_builtins_’,’_doc_’,’_file_’,’_name_’,’_package_’,’display’,’str’]
MODULES AND NAMESPACE
Explain Modules and Namespace. (5, 10 Marks)
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.
In Python, each module has its own namespace. This namespace includes the names of all items
(functions and variables) defined in the module. Therefore, two instances of repeat_x(), each defined in
their own module, are distinguished by being fully qualified with the name of the module in which each
is defined as,
module1.repeat_x and module2.repeat_x. This is illustrated as follows:
import modulel
import module2
result1= module1.repeat_x(10)
result2= module2.repeat_x(10)
Local, Global, and Built-in Namespaces
51
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 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 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 the same name are
defined in more than one of these namespaces, it becomes masked, as shown in the following example,
Example Program to demonstrate name clashes in different namespaces
def max(numbers): #global namespace
print("USER DEFINED FUNCTION MAX.....")
large = -1 #local namespace
for i in numbers:
if i>large:
large = i
return large
numbers =[9,-1,4,2,7]
print(max(numbers))
print("Sum of these numbers= ", sum(numbers)) #built-in namespace
OUTPUT
USER DEFINED FUNCTION MAX.....
9
Sum of these numbers = 21
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 we want some variables or functions in a module
to be privately used within the module, but not to be accessed from outside it, then we 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 * from module name, 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 Module
1. Python modules provide all the benefits of modular software design. These modules provide services
and functionality that can be reused in other programs.
2. 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/
Key points to remember
1. A modules can import other modules
2. It is customary but not mandatory to place all import statements at the beginning of a module.
3. A module is loaded only once, irrespective of the number of times it is imported.
DEFINING OUR OWN MODULES
How modules are created. (5 Marks)
Every Python program is a module, that is, every file that the user save as .py extension is a module.
First write these lines in a file and save the file as MyModule.py
def display( ): #function definition
print("Hello")
print(“Name of called module is: “,__name__)
52
MyModule.display() #using function defined in MyModule
print("Name of calling module is : “,__name__)
OUTPUT
MyModule str = Welcome to the world of Python!!!
Hello
Name of called module is : MyModule
Name of calling module is: __main__
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.
Dot operator can be used to access members (variables or functions) of the module.
# Code in MyModule
def large(a,b):
if a>b:
return a
else:
return b
# Code in Find.py
import MyModule
print("Large (50, 100) = “, MyModule.large(50, 100))
print("Large('B', 'c') = ", MyModule.large('B’, 'c'))
print("Large('HI', 'BI') = ", MyModule.large(‘HI', 'BI'))
OUTPUT
Large (50, 100) = 100
Large('B', 'c') = c
Large('HI', 'BI') - HI
POSSIBLE QUESTIONS
1 MARK
1. Which keyword is used for function?
a) Fun b) Define c) def d) Function
2. Python function always returns a value
a) True b) false c)none d)both a and b
3. What will be the output of the following Python code?
1. def sayHello():
2. print('Hello World!')
3. sayHello()
4. sayHello()
a)Hello World! b)'Hello World!' C)Hello d)nono
Hello World! 'Hello World!' Hello
53
4. What will be the output of the following Python code?
1. def printMax(a, b):
2. if a > b:
3. print(a, 'is maximum')
4. elif a == b:
5. print(a, 'is equal to', b)
6. else:
7. print(b, 'is maximum')
8. printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned
5. Choose the correct function declaration of fun1() so that we can execute the following function call
successfully
1. def fun1(*data):
2. print(*data)
3. fun1(25, 75, 55)
4. fun1(10, 20)
a) def fun1(**kwargs) b) No, it is not possible in Python c) def fun1(args*) d)def fun1(*data)
6. What is the output of the following display() function call
1. def display(**kwargs):
2. for i in kwargs:
3. print(i)
4. display(emp="Kelly", salary=9000)
a)TypeError b)Kelly c)(’emp’, ‘Kelly’) d)emp
9000 (‘salary’, 9000) salary
7. Which of the following items are present in the function header?
a) function name b) parameter list c) return value d) Both A and B
8. What is a recursive function?
a) A function that calls other function. b) A function which calls itself.
c) Both A and B d) None of the above
9. What is a variable defined outside a function referred to as?
a) local variable b) global variable c) static Variable d) automatic variable
10. A return statement with _____ arguments.
a) No b) 1 c) 2 d) Any
11. ___________ are the arguments passed to a function in correct positional order.
a) Required arguments b) Keyword arguments
c) Default arguments d) Variable-length arguments
12. Select the correct output of the following String operations
str = "natarajan";
print (str.capitalize())
a)NATARAJAN b)Natarajan c)Error d) unsupported operand
13. What will be printed when the following executes?
str = "This is fun"
str = str[5]
print(str)
a) i b) ' ' c) is fun d)This is fun
14. What is the value of s1 after the following code executes?
s1 = "heY"
s1 = s1.capitalize()
s1.lower()
a) heY b) hey c) HEY d) Hey
15. What is printed by the following statements?
animal = "dog"
print("animal " + "animal")
a) animal animal b) animalanimal c) animal dog d) animaldog
16. What will be the output of above Python code?
54
str1="6/4"
print("str1")
a) 1 b) 6/4 c) 1.5 d) str1
17. Which of the following is False?
a) String is immutable.
b) capitalize() function in string is used to return a string by converting the whole given string into
uppercase.
c) lower() function in string is used to return a string by converting the whole given string into lowercase.
d) None of these.
18. What will be the output of below Python code?
str1="Information"
print(str1[2:8])
a) format b) formatio c) orma d) ormat
19. What will be the output of below Python code?
str1="Aplication"
str2=str1.replace('a','A')
print(str2)
a) application b) Application c) ApplicAtion d)application
20.Which of the following functions is a built-in function in python? *
a) array() b) sqrt() c) factorial() d) print()
21. To use a module in another module, you must import it using an ________ statement *
a) import b) include c) both A and B d) none of the above
22. DRY principle makes the code
f) Reusable b) Loop forever c) Bad and repetitive d)
Complex
23. How many times will the display( ) 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
24. How would you refer to the sqrt function if it was imported by writing like this---?
from math import sqrt as square_root
math.--------
a) square b) square_root c) sqrt d) math.sqrt
25. The code will print how many numbers?
def display(x):
for i in range(x):
print(i)
return
display(10)
a) 0 b) 1 c) 10 d) 9
26. Which statement invokes the function?
a) function call: b) function definition c) function header d) __doc___
27. If number of arguments in function definition and function call does not match, then which type of error
is returned?
a) TypeError b) NameError c) ImportError d) NumberError
28. Modules are files saved with ---------- extension
a) mod b) mdl c) .py d) imp
29. Identify the correct way of calling a function named display() that prints Hello on the screen.
a) displayHello
b) result=display( )
c) print(display)
55
d) displayHello( )
30. The index of the first character in the string is -------
a) 1 b) 0 c) n d) n - 1
31. You can delete the entire string using which keyword?
a) erase b) del c) remove d) delete
32 In splitlines( ), splits lines in strings on which characters?
a) whitespace b) newline c) comma d) colon
33. When using find( ), if str is not present in the string then what is returned?
a) 0 b) n-1 c) -1 d) valueError
5 Marks
6. Write short notes on Functions. [Refer Page No.: 1]
7. Explain Function call in detail. [Refer Page No.: 3]
8. Explain the concept of “return” statement. [Refer Page No.: 7]
9. Explain Recursion in detail. [Refer Page No.: 10]
10. Explain String Comparison using relational operators. [Refer Page No.: 19]
11. Explain Python Module. [Refer Page No.: 21]
10 Marks
5. Write short notes on Function Arguments with its types. [Refer Page No.: 8]
6. Explain String Operations with neat examples. [Refer Page No.: 13]
7. Explain String handling functions with neat examples. [Refer Page No.: 15]
8. Explain Modules in detail. [Refer Page No.: 19]
9. Explain Modules and Namespace. [Refer Page No.: 21]
UNIT-IV
LIST: CREATING A LIST
Explain in detail about list with suitable example. (10 Marks)
A data structure is a group of data elements that are put together under
one name. Data structure defines a particular way of storing and
organizing data in a computer so that it can be used efficiently.
Sequence is the most basic data structure in Python . In the sequence data
structure, each element has a specific index. The index value starts from zero and is automatically
incremented for the next element in the sequence.
Python has some basic built-in functions that help programmers to manipulate elements that form a part
of a sequence.
List is a versatile data type in Python. It is a sequence in which elements
are written as a list of comma-separated values (items) between square
brackets.
A list is similar to an array that consists of a group of elements or items. The difference between array
and list is array can store only one type of elements whereas a list can store different types of elements.
The key feature of a list is that it can have elements that belong to the different data types.
The syntax of defining a list can be given as,
List_variable = [val1, val2, …]
List is mutable which means that value of its elements can be changed.
>>> list_A = [1,2,3,4,5] >>> list_B = ['A', 'b', 'C', 'd', 'E']
56
>>> print(list_A) >>>print(list_B)
[1, 2, 3, 4, 5] ['A', 'b', 'C', 'd', 'E']
>>> list_C = ["Good", "Going"] >>> list_D = [1, 'a', "bcd"]
>>> print(list_C) >>>print(list_D)
['Good', 'Going’] [1, 'a', 'bcd']
ACCESS VALUES IN LISTS
How to access values in list? (5 Marks)
Lists can also be sliced and concatenated.
To access values in lists, square brackets are used to slice along with the
index or indices to get value stored at that index.
The syntax for the slice operation is given as,
seq = 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
Program to demonstrate the slice operations used to access the elements of the list
num_list = [1,2,3,4,5,6,7,8,9,10]
print(“num_list is: “, num_list)
print(“First element 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 element 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 LISTS
How to update values in list? (5 Marks)
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.
We can also append new values in the list and remove existing value(s)
from the list using the append() method and del statement respectively.
Example Program to illustrate updating values in a list
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]
If we know exactly which element(s) to delete, use the del statement,
otherwise use the remove() method to delete the unknown elements. The
append() and insert() methods are list methods. They cannot be called on
other values such as strings or integers
Example Programs to illustrate deletion of numbers from a list using del statements
num_list = [1,2,3,4,5,6,7,8,9,10] # a list is defined
del num_list[2:4] # deletes numbers at index 2 and 3
57
print (num_list)
OUTPUT
[1, 2, 5, 6, 7, 8, 9, 10]
58
concatenation Joins two lists. [1,2,3,4,5] + [6,7,8,9,10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
repetition Repeats elements in the list. "Hello", "World"*2 ['Hello', 'World',
'Hello', 'World']
in Checks if the value is present 'a' in ['a', 'e', 'i', 'o', 'u'] True
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 in >>> num_list=[6,3,7,0,1,2,4,9] 9
the list. >>> print (max(num_list))
min Returns minimum value in >>>num_list = [6,3,7,0,1,2,4,9] 0
the list. >>> print (min(num_list))
x.insert(0,9)
print('x after inserting 9 at 0th position: ',x)
y=x.copy()
print('Newly created list y: ',y)
y.extend(x)
OUTPUT
print('y after appending x: ',y)
How many element: 5
Enter element: 12
print('Content of list-x: ',x)
Enter element: 9
n=x.count(9)
Enter element: 7
print('Number of times 9 found in the list
Enter element: 23
x: ',n)
Enter element: 5
x.remove(23)
The list is: [12, 9, 7, 23, 5]
print('x after removing 23: ',x)
Number of elements: 5
x after append 23: [12, 9, 7, 23, 5, 23]
x.pop()
x after inserting 9 at 0th position: [9, 12, 9, 7, 23, 5, 23]
print('x after removing ending element:
Newly created list y: [9, 12, 9, 7, 23, 5, 23]
',x)
y after appending x: [9, 12, 9, 7, 23, 5, 23, 9, 12, 9, 7, 23, 5, 23]
Content of list-x: [9, 12, 9, 7, 23, 5, 23]
x.sort()
Number of times 9 found in the list x: 2
print('x after sorting: ',x)
x after removing 23: [9, 12, 9, 7, 5, 23]
x after removing ending element: [9, 12, 9, 7, 5]
x after sorting:
60 [5, 7, 9, 9, 12]
x after reversing: [12, 9, 9, 7, 5]
x after removing all elements: []
x.reverse()
print('x after reversing: ',x)
x.clear()
print('x after removing all elements: ',x)
Example To print the return values
>>> num_1ist [100, 200, 300, 400]
>>> print (num_1ist.insert(2, 250))
OUTPUT
None
TUPLES
Explain about tuple data structure in detail. (5, 10 Marks)
A tuple is an ordered, immutable, and iterable collection of elements. Tuples are similar to lists, but
unlike lists, once you create a tuple, We cannot change its contents (immutable).
CREATING ELEMENTS IN A TUPLE
How to creating an elements in a tuple? (5 Marks)
We can create a tuple by enclosing elements within parentheses () or by simply separating them with
commas without parentheses.
Example:
my_tuple = (1, 2, 3)
another_tuple = 4, 5, 6 # Creating a tuple without parentheses
Other Examples:
Tup1=( ) # empty tuple
Tup1=(5) # create with a single element
Tup1=(1,2,3,4,5) #create a tuple of integer
Tup1=(‘a’,’b’,’c’) #create a tuple of character
Tup1=(“abc”,”def”) #create a tuple of String
Tup1=(“abc”,”a”,1,1.5) #create a tuple of Mixed vaules
ACCESSING ELEMENTS IN A TUPLE
How to access an element in a tuple? Explain in detail. (5 Marks)
We can access elements in a tuple using indexing,
first_element = Tup1[0]
Negative indexing works the same way as with lists.
first_element = Tup1[-4]
Example Program to illustrate the use of slice operation to retrieve value(s) stored in a tuple
Tup1 =(1,2,3,4,5,6,7,8,9,10)
print("Tup[3:6] = ", Tup1[3:6])
print("Tup[:4] = ", Tup1[:4])
print("Tup[4:] = ", Tup1[4:])
print("Tup[:] = “, Tup1[:])
OUTPUT
Tup[3:6] = (4, 5, 6)
Tup[:4] = (1, 2, 3, 4)
Tup[4:] = (5, 6, 7, 8, 9, 10)
Tup[:] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
UPDATING ELEMENTS IN A TUPLE
How to update an element in a tuple? (5 Marks)
Tuple is immutable and so, the value(s) in the tuple cannot be changed you can only extract the values
from the tuples
Example:
Tupl = (1,2,3,4,5)
Tup2 = (6,7,8,9,10)
Tup3 = Tupl+Tup2
print(Tup3)
61
Output:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
DELETING ELEMENTS IN A TUPLE
How will you delete an item in a tuple? (5 Marks)
Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course , you can create
a new tuple that has all elements in your tuple except the ones you don't want (those you wanted to be
deleted
Example:
Tupl = (1,2,3,4,5)
del Tupl[3]
print(Tup1)
Output:
TypeError: 'tuple' object doesn't support item deletion
BASIC TUPLE OPERATIONS:
OPERATION EXAMPLE OUTPUT
len len((l,2,3,4,5,6,7,8,9,10)) 10
concatenation (1,2,3,4,5) + (6,7,8,9,10) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Repetition ('nat','raj')*2 ('nat', 'raj', 'nat', 'raj')
membership 'a' in ('n','a','t') True
Iteration for i in (1,2,3,4,5,6,7,8,9,10): 1 2 3 4 5 6 7 8 9 10
print(i, end=' ')
max num_list = (6,3,7,0,1,2,4,9) 9
print(max(num_list))
min num_list = (6,3,7,0,1,2,4,9) 0
print(min(num_list))
Comparsion Tup1=(1,2,3) False
use<,>,== Tup2=(4,5,6)
print(Tup1>Tup2)
Convert to tuple print(tuple("Welcome")) ('W', 'e', 'l', 'c', 'o', 'm', 'e')
print(tuple([1,2,3,4,5])) (1, 2, 3, 4, 5)
NESTED TUPLE
Explain in detail about nested tuple. (5 Marks)
Python allows you to define a tuple inside another tuple. This is called a nested tuple. Nested tuples
allow you to create multi-dimensional data structures.
Example:
nested_tuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
DIFFERENCE BETWEEN LIST AND TUPLE
Mention the difference between list and tuples. (5 Marks)
List Tuple
Lists are mutable. Tuples are immutable.
Iteration in lists is time consuming. Iteration in tuples is faster
Lists are better for insertion and deletion operations Tuples are appropriate for accessing the elements
Lists consume more memory Tuples consume lesser memory
Lists have several built-in methods Tuples have comparatively lesser built-in methods.
Lists are more prone to unexpected errors Tuples operations are safe and chances of error are
very less
Creating a list is slower because two memory blocks Creating a tuple is faster than creating a list.
need to be accessed.
Lists are initialized using square brackets []. Tuples are initialized using parentheses ().
List objects cannot be used as keys for dictionaries Tuple objects can be used as keys for dictionaries
because keys should be hashable and immutable. because keys should be hashable and mutable.
List have order. Tuple have structure.
DICTIONARIES
Explain in detail about dictionary data structure. (5, 10 Marks)
62
Dictionary is a data structure in which we store values as a pair of key and value. Each key is separated
from its value by a colon (:), and consecutive items are separated by commas. The entire items in a
dictionary are enclosed in curly brackets ({}).
CREATING A DICTIONARY
How to create a dictionary? Explain it. (5 Marks)
The syntax to create an empty dictionary can be given as,
dictionary_variable = [ ]
The syntax for defining a dictionary is
dictionary_name = {key_l: value_l, key_2: value_2, key_3: value_3}
(or)
dictionary_name =
{
key_l: value_l,
key_2: value_2,
key_3: value_3,
}
While, keys in the dictionary must be unique and be of any immutable data type, the value of a key can
be of any type. Remember that dictionaries are not sequences, rather they are mappings. Mappings arc
collections of objects that store objects by key instead of by relative position.
Note: Dictionary keys are case- sensitive. Two keys with the same name but in different case are not the
same in Python.
Example:
Class ={'Roll No':'2K23CS017','Name':'Natarajan','Course':'BSc [CS]'}
print(Class)
Output: {'Roll No': '2K23CS017', 'Name': 'Natarajan', 'Course': 'BSc [CS]'}
ACCESSING VALUES IN A DICTIONARY
How to accessing values in a dictionary? (5 Marks)
To access values in a dictionary, square brackets are used along with the key to obtain its value.
Example:
Class ={
"Roll No": "2K23CS017",
"Name": "VIGNESH",
"Course": "BSC [CS]"
}
print(Class["Roll No"])
print(Class["Name"])
Output:
2K23CS017
VIGNESH
UPDATING ELEMENTS IN A DICTIONARY
How to update an element in a dictionary. (5 Marks)
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.
The syntax to add an item in a dictionary is given as,
dictionary_variable[key] = val
EXAMPLE:
Class ={"Roll No": "2K23CS017", "Name": "NATARAJAN", "Course": "BSC [CS]"}
Class['Grade']='a' #INSERT AN ELEMENT
print(Class)
OUTPUT:
{'Roll No': '2K23CS017', 'Name': 'NATARAJAN', 'Course': 'BSC [CS]', 'Grade': 'a'}
MODIFYING AN ENTRY:
To modify an entry, just overwrite the existing value (ie) dictionaries are mutable (changeable). We can
change the value of a dictionary element by referring to its key.
EXAMPLE:
63
Class ={"Roll No": "2K23CS017", "Name": "NATARAJAN", "Course": "BSC [CS]"}
Class['Course']='BCA' #MODIFY
print(Class)
OUTPUT:
{'Roll No': '2K23CS017', 'Name': 'NATARAJAN', 'Course': 'BCA'
DELETING ELEMENTS IN A DICTIONARY
How will you delete an element in a dictionary? (5 Marks)
We 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
again use the del statement as del Dict_name. The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:
Class ={"Roll No": "2K23CS017", "Name": "NATARAJAN", "Course": "BSC [CS]"}
del Class["Course"] #delete one value in Dictionary
print(Class)
Class.clear() #clear the dictionary values that makes dictionary empty.
print(Class)
del Class #delete dictionary value
print(Class)
Output:
{'Roll No': '2K23CS017', 'Name': 'NATARAJAN'}
{}
Traceback (most recent call last):
File "C:/Users/Natz/AppData/Local/Programs/Python/Python38/t.py", line 7, in <module>
print(Class)
NameError: name 'Class' is not defined
We can also use the pop() method to delete a particular key from the dictionary. The syntax of the pop()
method is given as,
dict.pop(key [default])
As the name suggests, the pop() method removes an item from the dictionary and returns its value. If the
specified key is not present in the dictionary, then the default value is returned.
Since default is optional, if you do not specify the default value and the key is also not present in the
dictionary, then a Key Error is generated. Another method diet. popitem() randomly pops and returns an
item from the dictionary. The use of these methods
DICTIONARY FUNCTIONS AND METHODS
Explain in detail about dictionary methods with suitable example. (5, 10 Marks)
Some methods and functions that can be used on dictionaries in Python.
OPERATION DESCRIPTION EXAMPLE OUTPUT
len(Dict) Returns the length of Dict1={'Roll No' :’16/001', 3
dictionary. That is, number of 'Name': 'Arav', 'Course':
items (key- value pairs) 'BTech'}
print(len(Dict1))
str(Dict) Returns a string Dictl={('Roll No’ : {‘Name’: 'Arav','Roll
representation of the ’16/001', 'Name': No’:'16/001','Course':
dictionary 'Arav','Course': 'BTech'} 'BTech'}
print (str (Dict1))
Dict.clear() Deletes all entries in the Dictl={'Roll No’ : '16/001', {}
dictionary 'Name’ : 'Arav' ,
’Course': 'BTech'}
Dict1.clear()
print (Dict1)
Dict.copy() Returns a shallow copy of the Dictl={'Roll No’ : Dict2:{'Course':'BTech',
dictionary, i.e., the dictionary ‘16/001', 'Name" : 'Arav', 'Name':'Arav', 'Roll No' :
returned will not have a 'Course': 'BTech’} '16/001'}
duplicate copy of Dict but Dict2 = Dict1.copy() Dict1 after modification:
64
will have the same reference print("Dict2:", Dict2) {'Course': 'BTech',
Dict2['Name'] ='Saesha' ‘Name’:’Arav’, ‘Roll
print("Dicti after No’: ‘16/001’}
modification : ",Dict1) Dict2 after modification:
print(“Dict2 after {‘Course’: ‘BTech’,
modification: “, Dict2) ‘Name’:’Saesha’,’Roll
No’:’16/001’}
Dict.fromkeys(seq[,val]) Create a new dictionary with Subjects = {‘python’:-1,
keys from seq and values set [‘python’,’cryptography, ‘cryptography’:-1,
to val. If no val is specified ’pst’] ‘pst’:-1}
then, None is assigned as Marks=dict.fromkeys
default value (Subjects, -1)
print(Marks)
Dict.get(key) Returns the value for the key Dict = {'Roll No':'16/001', Arav
passed as argument. If the 'Name': 'Arav', 'Course':
key is not present in 'BTech'}
dictionary, it will return the print(Dict1.get(‘Name’))
default value. If no default
value is specified then it will
return None
Dict.has_key(key) Returns True if the key is Dict = {'Roll No':'16/001', False
present in the dictionary and 'Name': 'Arav', 'Course':
False otherwise 'BTech'}
print( ‘Marks’ in Dict1)
Dict.items() Returns a list of tuples(key- Dict = {'Roll No':'16/001', [(‘Course’, ‘Btech’),
value pair) 'Name': 'Arav', 'Course': (‘Name’, ’Arav’), (Roll
'BTech'} No’, ‘16/001’)]
print( Dict1.items())
Dict.keys() Returns a list of keys in the Dict = {'Roll No':'16/001', [‘Course’,’Name’,’Roll
dictionary 'Name': 'Arav', 'Course': No’]
'BTech'}
print( Dict1.keys())
Dict.setdefault(key, Sets a default value for a key Dict = {'Roll No':'16/001', Arav has got marks = 0
value) that is not present in the 'Name': 'Arav', 'Course':
dictionary 'BTech'}
Dict1.setdefault(‘Marks’,0)
print(Dict1[‘Name’], “has
got marks = ”,
Dict1.get(‘Marks’))
Dict1.update (Dict2) Adds the key-value pairs of Dictl={'Roll No’ : {'Grade':'0',
Dict2 to the key-value pairs '16/001', 'Name': 'Arav', 'Course':'BTech',
of Dict1 'Course': 'BTech'} 'Name':'Arav',
Dict2={'Marks’: 90, 'Roll No’:'16/001',
'Grade’: '0'} 'Marks': 90}
Dict1. update(Dict2)
print (Dict1)
Dict.values() Returns a list of values in Dictl={'Roll No' : ['BTech', 'Arav',
dictionary '16/001', 'Name': 'Arav', '16/001']
'Course': 'BTech’}
print(Dict1.values())
Dict. iteritems() Used to iterate through items Dict={'Roll No : Course BTech
in the dictionary '16/001', 'Name': 'Arav', Name Arav
'Course': 'BTech'} Roll No 16/001
for i,j in Dict.iteritems():
print(i, j)
65
in and not in Checks whether a given key Dict={'Roll No' : True
is present in dictionary or not '16/001', 'Name': 'Arav', False
'Course': 'BTech"}
print('Name' in Dict)
print ("Marks' in Dict)
DIFFERENCE BETWEEN LISTS AND DICTIONARIES
Mention the difference between list and dictionary. (5 Marks)
List Dictionary
The list is a collection of index value pairs like The dictionary is a hashed structure of the key and
that of the array in C++. value
pairs.
The list is created by placing elements in [ ] The dictionary is created by placing elements in { }
separated by commas “,” as “key”:”value”, each key-value pair is separated by
commas “, “
The indices of the list are integers starting from 0. The keys of the dictionary can be of any data type.
The elements are accessed via indices. The elements are accessed via key-value pairs.
The order of the elements entered is maintained. There is no guarantee for maintaining order.
Lists are orders, mutable, and can contain Dictionaries are unordered and mutable but they
duplicate values. cannot contain duplicate keys.
*****UNIT IV COMPLETED*****
POSSIBLE QUESTIONS
1 Mark
5 Marks
1. How to update values in list? [Refer Page No.: 01]
2. Discuss about nested list. [Refer Page No.: 03]
3. Explain in detail about list operations with suitable example. [Refer Page No.: 03]
4. How to access an element in a tuple? Explain in detail. [Refer Page No.: 05]
5. Mention the difference between list and tuples. [Refer Page No.: 07]
6. How to updating values in a dictionary? [Refer Page No.: 08]
7. Mention the difference between list and dictionary. [Refer Page No.: 10]
10 Marks
1. Explain in detail about list with suitable example. [Refer Page No.: 01]
2. Explain about list methods with suitable example. [Refer Page No.: 03]
3. Explain about tuple data structure in detail. [Refer Page No.: 05]
67
4. Explain in detail about dictionary data structure. [Refer Page No.: 07]
5. Explain in detail about dictionary methods with suitable example. [Refer Page No.: 08]
UNIT-V
PYTHON FILE HANDLING
Explain in detail about file handling in python. (5,10 Marks)
A file is a collection of data stored on a secondary storage device like hard
disk.
Till now, we had been processing data that was entered through the computer's keyboard using the input
(). But this task can become very tedious especially when there is a huge amount of data to be processed.
68
A better solution is to combine all the input data into a file and then design a Python program to read this
data from the file whenever required.
When a program is being executed, its data is stored in random access memory (RAM). Though RAM
can be accessed faster by the CPU, it is also volatile, which means that when the program ends, or the
computer shuts down, all the data is lost. If we want to use the data in future, then you need to store this
data on a permanent or non-volatile storage media such as the hard disk, USB drive, DVD, etc.
Data on non-volatile storage media is stored in named locations on the media called files. We first open a
file, read or write to it, and then finally close it.
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 major problems:
1. It becomes cumbersome and time consuming to handle huge amount of data through terminals.
2. 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.
File Path
A file path can be either relative or absolute.
An absolute path always contains the root and the complete directory list
to specify the exact location the file. For example, C:\Users\Desktop\ODD 23-24\
PYTHON\PYTHON_PROGRAMMING_V.docx
Relative pathnames starts with respect to the current working directory.
For example, PYTHON_PROGRAMMING_V.docx. Relative path is joined with the current directory to
create an absolute file path.
TYPES OF FILES IN PYTHON
Explain in detail about types of files in python. (5 Marks)
Python supports two types of files.
1. Text files
2. Binary files
ASCII Text Files
A text file is a stream of characters that can be sequentially processed by
a computer in forward direction.
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.
In a text file, each line contains zero or more characters and ends with one or more characters that
specify the end of line. Each line in a text file can have maximum of 255 characters.
When data is written to a text file, each newline character is converted to a carriage return/line feed
character.
Similarly, when data is read from a text file, each carriage return/line feed character is converted to
newline character.
When a text file is used, there are actually two representations of data internal or external.
In a text file, each line of data ends with a newline character. Each file
ends with a special character called the end-of-file (EOF) marker.
Binary Files
Discuss about binary files. (5 Marks)
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.
1. 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.
2. 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 can be either processed sequentially or
randomly depending on the needs of the application. In Python, to process a file randomly, the
69
programmer must move the current file position to an appropriate place in the file before reading or
writing data.
For example, if a file is used to store records (using structures) of students, then to update a particular
record, the programmer must first locate the appropriate record, read the record into memory, update it,
and finally write the record back to disk at its appropriate location in the file.
The contents of a binary file are not human readable. If we want that data
stored in the file must be human-readable, then store the data in a text
file.
Binary files store data in the internal representation format. Like text file, binary file also ends with an
EOF marker.
In a text file, an integer value 123 will be stored as a sequence of three characters--1, 2, and 3. As each
character takes 1 byte, therefore, to store the integer value 123, we need 3 bytes. However, in a binary
file, the integer value 123 will be stored in 2 bytes in the binary form. This clearly indicates that binary
files takes less space to store the same piece of data and eliminates conversion between internal and
external representations and are thus more efficient than the text files.
Text files contain only basic characters and do not store any information about the color, font, and size of
the text. These files can be opened with Windows Notepad. These files can be easily read and the
contents of the file are treated as an ordinary string value. Binary files cannot be read by text editors like
Notepad. If we open a binary file in Notepad, we will see some scrambles, and absurd data.
Binary files are mainly used to store data beyond text such as images, executables, etc.
OPENING AND CLOSING FILES
How to open a file in python? Explain with suitable example. (5, 10 Marks)
Write a short note on access modes in python. (5 Marks)
Python has many in-built functions and methods to manipulate files. These functions and methods
basically
work on a file object.
The open() Function
Before reading from or writing to a file, we 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])
Here, file name is a string value that specifies name of the file that we want to access.
access_mode indicates the mode in which the file has to be opened, i.e., read, write, append, etc.
The open() function returns a file object. This file object will be used to read, write, or perform any other
operation on the file. It works like a file handle.
We can also print the details of file object as shown in the code given below.
file.open("Filel.txt", "rb") OUTPUT
print (file) <open file 'File1.txt', mode 'rb' at 0x02A85000>
Access mode is an optional parameter and the
default file access mode is read (r).
A file handle is different from a file. Use the remote control to switch channels, change the volume, etc.
But whatever changes we try to do using remote control are actually applied on the TV. So our file
handle or the file object acts as a remote control of our file (TV). Whatever changes we want to perform
on the file is actually carried out through the file object.
Table : Access Modes
Mode Purpose
r This is the default mode of opening a file which opens the file for reading only. The file pointer is
placed at the beginning of the file.
rb This mode opens a file for reading only in binary format. The file pointer is placed at the beginning
of the file.
r+ This mode opens a file for both reading and writing. The file pointer is placed at the beginning of
the file.
rb+ This mode opens the file for both reading and writing in binary format. The file pointer is placed at
the beginning of the file.
w This mode opens the file for writing only. When a file is opened in w mode, two things can happen.
If the file does not exist, a new file is created for writing. If the file already exists and has some data
70
stored in it, the contents are overwritten.
wb Opens a file in binary format for writing only. When a file is opened in this mode, two things can
happen. If the file does not exist, a new file is created for writing. If the file already exists and has
some data stored in it, the contents are overwritten.
w+ Opens a file for both writing and reading. When a file is opened in this mode, two things can
happen. If the file does not exist, a new file is created for reading as well as writing. If the file
already exists and has some data stored in it, the contents are overwritten.
wb+ Opens a file in binary format for both reading and writing. When a file is opened in this mode, two
things can happen. If the file does not exist, a new file is created for reading as well as writing. If the
file already exists and has some data stored in it, the contents are overwritten.
a Opens a file for appending. The file pointer is placed at the end of the file if the file exists. If the file
does not exist, it creates a new file for writing.
ab Opens a file in binary format for appending. The file pointer is at the end of the file if the file exists.
If the file does not exist, it creates a new file for writing.
a+ Opens a file for both reading and appending. The file pointer is placed at the end of the file if the
file exists. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file in binary format for both reading and appending. The file pointer is placed at the end of
the file if the file exists. If the file does not exist, a new file is created for reading and writing.
72
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)
Example Program to print the first 10 characters of the file File1.txt
file = open("Filel.txt", "r") OUTPUT
print(file.read(10)) Hello All,
file.close()
If we try to open a file for reading that does not exist, then we will get an error, as shown below.
file1= open("file2.txt","r")
print(file2.read()) OUTPUT
read() method returns newline as "\n". Traceback (most recent call last):
The readline () method is used to read a single line File "C:\Python34\Try.py", line 1, in <module>
from the file. The method returns an empty string filel= open("file2.txt","r")
when the end of the file has been reached. Note IOError: (Errno 2] No such file or directory: ‘file2.txt'
that a blank line is represented by \n and the readline() method returns a string containing only a single
newline character when a blank line is encountered in the file.
Example: Consider adding a few more lines in the file File1.txt and read its contents using the readline
() method. The following are the contents of # Filel.txt
the file. Hello All,
file = open("Filel.txt", "r") Hope you are enjoying learning Python
print("First Line : ", file.readline()) We have tried to cover every point in detail to avoid confusion
print("Second Line : ", file.readline()) Happy Reading
print("Third Line : ", file.readline())
file.close() OUTPUT
After reading a line from the file using the First Line: Hello All,
readline () method, the control automatically Second Line :
passes to the next line. That is why, when we Third Line : Hope you are enjoying learning Python
call the readline () again, the next line in the file
is returned.
Binary files are more efficient than text files so we have opened the files using rb and wb access modes.
We could have also opened using r or w access mode to work with text files.
The readlines () method is used to read all the lines in the file. The code for doing so is given below.
Example Program to demonstrate readlines () function
file = open("File1.txt", "r") OUTPUT
print (file.readlines()) 'Hello All, \r\n', ‘\r\n', 'Hope you are enjoying
file.close() learning Python\r\n', '\r\n', 'We have tried to cover
The list() method is also used to display every point in detail to avoid confusion\r\n',
entire contents of the file. We just need '\r\n', 'Happy Reading\r\n']
to pass the file object argument to the
list() method.
Example Program to display the OUTPUT
contents of the file File1.txt using the ["Hello All, \r\n', '\r\n', 'Hope you are enjoying learning Python\r\n', '\r\n',
list () method. We have tried to cover every point in detail to avoid confusion\r\n', '\r\n',
file = open("Filel.txt", "r") 'Happy Reading\r\n']
print (list(file))
file.close()
A very fast, simple, and efficient way to display a file is to loop over the file object to print every line in
it.
Example Program to display the contents of a file
file = open("Filel.txt", "r")
All reading methods return an empty string when end-of-file (EOF) is reached.
for line in file:
That is, if we have to read the entire file and then again call readline(), an
print (line)
empty string would be returned
file.close()
73
Opening Files using with Keyword
How to open a file using with keyword. (5 Marks)
“with” keyword is used 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
Hello World
or write operation or even when we forget to explicitly
Welcome to the world of Python Programming.
close the file. This difference is clearly evident from the
code given as follows using the contents of filel.txt.
The file contents are, OUTPUT
with open("file1.txt", "rb") as file: Hello world
for line in file: Welcome to the world of Python Programming.
print(line) Let's check if the file is closed: True
print("Let's check if the file is closed", file.close())
file = open("file1.txt", "rb")
for line in file: OUTPUT
print(line) Hello World
print("Let's check if the file is closed : ", file.close()) Welcome to the world of Python Programming.
In the first code, the file is opened using the with Let's check if the file is closed: False
keyword. After the file is used in the for loop, it is
automatically closed as soon as the block of code comprising of the for loop is over.
But when the file is opened without the with keyword, it is not closed automatically. We need to
explicitly close the file after using it.
Calling close() on a file object that is already closed does not raise any error but fails silently as shown
below,
with open("file1.txt","r") as file:
print (file.read()) OUTPUT
file.close() Hello World
When we open a file for reading, or writing, the file is Welcome to the world of Python Programming
searched in the current working directory. If the file exists somewhere else then we need to specify the
path of the file.
SPLITTING WORDS
Discuss about split keyword. (5 Marks)
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 we can even specify any other character to split words in the string.
Example Program to perform split operation whenever a comma is encountered
with open("filel.txt", "r") as file:
OUTPUT
line = file.readline()
[‘Hello World', 'Welcome to the world of Python Programming\n']
words = line.split(',')
print (words)
FILE METHODS
Explain about file methods in detail. (5, 10 Marks)
Method Description Example
fileno() Returns the file number of the file (which is an integer file = open("File1.txt", "w")
descriptor) print(file. fileno())
OUTPUT 3
flush() Flushes the write buffer of the file stream file = open("Filel.txt", "w")
file. flush()
isatty() Returns True if the file stream is interactive and False file = open("Filel.txt", "w")
otherwise file.write("Hello")
print (file.isatty())
OUTPUT False
readline(n) Reads and returns one line from file. n is optional. If n is file = open("Try.py", "r")
specified then at most n bytes are read print (file.readline(10))
OUTPUT file = ope
truncate(n) Resizes the file to n bytes file =open("File.txt", "w")
file.write("Welcome to the World of
74
programming....")
file.truncate (5)
file = open("File.txt", "r")
print(file.read())
OUTPUT Welco
rstrip() Strips off whitespaces including newline characters from file = open("File.txt") OUTPUT
the right side of the string read from the file line = file.readline()
print(line.rstrip()) Greetings to
FILE POSITIONS
Write about file positions. (5 Marks)
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.
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 we just open a file for reading, the file pointers is positioned at location 0, which is the beginning
of the file.
The seek (offset[, from]) method is used to set the position of the file pointer or in simpler terms, move
the file pointer to a new location. 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.
Table specifies the value of from argument and its corresponding interpretation.
From Reference Position
0 From the beginning of the file
1 From the current position of the file
2 From the end of the file
From value 2 is especially important when working with MP3 files that stores tags at the end of the file,
so we directly issue a command to move the file pointer to a position 128 bytes from the end of the files.
Example Program that tells and sets the position of the file pointer
file = open("File1.txt","rb")
OUTPUT
print("Position of file pointer before reading is : ",file.tell())
Position of file pointer before reading is : 0
print(file.read(10))
'Hello All,'
print("Position of file pointer after reading is : ",file.tell())
Position of file pointer after reading is : 10
print("Setting 3 bytes from the current position of file pointer")
Setting 3 bytes from the current position of file
file.seek(3,1)
pointer
print(file.read())
'ope
file.close()
you are enjoying learning Python\r\nWe have
In Python, we don't need to import any library to read and
tried to cover every point in detail to avoid
write files.
confusion\r\nHappy Reading'
Just create a file object and call the open function to
read/write to the file.
Example Program - Write a program that accepts file name as an input from the user. Open the file
and count the number of times a character appears in the file.
filename = input("Enter the filename: ") Content of File1.txt
with open(filename) as file: Hello All,
text=file.read() Hope you are enjoying learning Python
letter=input("Enter the character to be searched: ") We have tried to cover every point in detail to
count=0 avoid confusion
for char in text: Happy Reading
if char == letter:
count+=1
OUTPUT
print(letter,"appears ",count," times in file")
Enter the filename: File1.txt
Enter the character to be searched: a
a appears 7 times in file
75
RENAMING AND DELETING FILES
Write about remove() method with a suitable example. (5 Marks)
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, we should first import it in our program and then call any
related functions.
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 file object provides functions to manipulate files.
Example Program to rename file "File1.txt" to "Students.txt"
import os OUTPUT
os.rename("File1.txt","Students.txt") File Renamed
print("File Renamed")
We can check whether the above code renamed the right file by checking in the C:\Python34 directory.
Now, there is no file named File1.txt but it does have a file named Students.txt.
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 delete a file named "Students.txt"
import os OUTPUT
os.remove("Students.txt") File Deleted
print("File Deleted")
*************UNIT V COMPLETED*************
POSSIBLE QUESTIONS
1 Mark
1. ----------- pathnames starts with respect to the current working directory.
a) Absolute b) Relative c) Both a) and b) d) None of these
2. Each file ends with a special character called the ----------.
a) \n b) EOF marker c) BOF marker d) \r
3. A file is stored in ----------- memory.
a) secondary b) primary c) cache d) volatile
4. Identify the right way to close a file.
a) File.close() b) close(File) c) close(“File”) d) File.closed
5. If a file opened in ‘w’ mode does not exist, then ----------
a) nothing will happen b) data will be written to a file that has a name a similar to the specified
name
c) file will be created d) error will be generated
6. The default access mode is
a) w b) r c) wb d) rb
7. By default, a new file is created in which directory
a) root directory b) current directory c) python directory d) D drive
8. Which method is used to read a single line from the file?
a) read() b) readline() c) readlines() d) reads()
9. open() function returns a -----------
a) file content b) file object c) \n d) None of the above
5 Marks
12. Explain in detail about types of files in python. [Refer Page No.: 1]
13. Write a short note on access modes in python. [Refer Page No.: 2]
14. Write about close() and append() method. [Refer Page No.: 3
15. Explain about file methods in detail. [Refer Page No.:6]
10 Marks
76
10. Explain in detail about file handling in python. [Refer Page No.: 1]
11. Explain about write() and writelines() methods in detail. [Refer Page No.: 4]
12. Explain about read() and readline() method with an example. [Refer Page No.: 4]
77