0% found this document useful (0 votes)
42 views203 pages

Python Unit 1 to 5- Final

Uploaded by

Gopi Pugal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
42 views203 pages

Python Unit 1 to 5- Final

Uploaded by

Gopi Pugal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 203

PYTHON PROGRAMMING III-BSC[CS]

MORAPPUR KONGU COLLEGE OF ARTS AND SCIENCE


STAFF: V.SARASU, M.Sc., B.Ed., M.Phil.,
SUBJECT:PROGRAMMING IN PYTHON
UNIT-I
PYTHON INTRODUCTION
Explain the python and where we used in python programming languages ?(5
marks)

What is Python?
 Python is a popular programming language. It was created by Guido van Rossum, and

 released in 1991.
 Python language is being used by almost all tech-giant companies like – Google, Amazon,

Facebook, Instagram, Dropbox, Uber… etc.


 he biggest strength of Python is huge collection of standard library which can be used for

the following:

 Machine Learning
 GUI Applications (like Kivy, Tkinter, PyQt etc. )
 Web frameworks like Django (used by YouTube, Instagram, Dropbox)
 Image processing (like OpenCV, Pillow)
 Web scraping (like Scrapy, BeautifulSoup, Selenium)
 Test frameworks
 Multimedia
 Scientific computing
 Text processing and many more..

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

1
PYTHON PROGRAMMING III-BSC[CS]
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.

Example

print("Hello, World!")

Python can be used on a server to create web applications.


Python is a high-level, interpreted programming language known for its simplicity and
readability. Here are some key points about Python:

1. General-Purpose: Python is a versatile, general-purpose programming language,


meaning it can be used for a wide range of applications, including web development, data
analysis, artificial intelligence, machine learning, automation, and more.
2. Readability: Python code is designed to be easy to read and write, emphasizing a clean
and expressive syntax. This makes it an excellent language for beginners and also
contributes to the maintainability of code.
3. Interpreted and Interactive: Python is an interpreted language, which means that you
can run your code line by line, making it easy to test and debug. It also supports an
interactive mode, where you can enter commands directly into the interpreter and see the
2
PYTHON PROGRAMMING III-BSC[CS]
results immediately.
4. Object-Oriented: Python is an object-oriented programming (OOP) language, which
means it supports the creation and use of objects, encapsulation, and inheritance to
structure code in a modular way.
5. Extensive Libraries: Python has a rich ecosystem of libraries and frameworks that
provide pre-built functionality for various tasks. This includes NumPy and Pandas for
data manipulation, TensorFlow and PyTorch for machine learning, Flask and Django for
web development, and many more.
6. Community and Documentation: Python has a large and active community of
developers. This results in a wealth of online resources, tutorials, and documentation,
making it easier for developers to find help and share knowledge.
7. Cross-Platform: Python is cross-platform, meaning you can run Python code on various
operating systems, including Windows, macOS, and Linux.

Python's origins:

EXPLAIN THE PYTHON ORGINS BRIEFLY(5 MARKS)

Python's origins trace back to the late 1980s. Here's a more detailed account:

1. Early Development (Late 1980s): Guido van Rossum started working on Python in
December 1989 while at the Centrum Wiskunde & Informatica (CWI) in the Netherlands.
The project was motivated by his desire to create a language that was easy to read, write,
and maintain. Van Rossum had previously worked on a language called ABC at CWI,
and Python was conceived as its successor.
2. First Release (February 1991): The first official Python release, Python 0.9.0, occurred
in February 1991. The name "Python" was inspired by the British comedy group Monty
Python, whose work Guido van Rossum enjoyed. The language was designed with a
focus on code readability, and its syntax aimed to allow programmers to express concepts
in fewer lines of code than languages like C++ or Java.
3. Python 1.0 (January 1994): Python 1.0 was released in January 1994. This version
included new features such as lambda, map, filter, and reduce functions.
4. Python 2.0 (October 2000): Python 2.0, released in October 2000, introduced list
comprehensions, garbage collection, and Unicode support. Python 2 became widely used
and saw various updates over the years.
5. Python 3.0 (December 2008): Python 3.0, also known as "Python 3000" or "Py3k," was
3
PYTHON PROGRAMMING III-BSC[CS]
a significant milestone. It was designed to rectify inconsistencies and improve the
language. While it introduced some backward-incompatible changes, the Python
community recognized the need for a cleaner and more modern language.
6. Python Software Foundation (PSF): The Python Software Foundation, a non-profit
organization, was established in 2001 to promote, protect, and advance Python
programming language. The PSF plays a key role in managing the intellectual property
rights and overall development of Python.
7. Guido van Rossum's Leadership: Guido van Rossum played a crucial role in guiding
Python's development. He served as the "Benevolent Dictator For Life" (BDFL), a term
he coined to reflect his position as the ultimate decision-maker in the Python community.
However, in July 2018, he stepped down from his role as the leader, signaling a shift in
governance to a more collaborative model.

Python has since continued to evolve, with regular releases and a vibrant community
contributing to its growth and widespread adoption in various domains. The language's
simplicity, readability, and versatility have made it one of the most popular programming
languages globally.

EXPLAIN FEATURES OF PYTHONS (5 MARKS)


Python is a versatile programming language with numerous features that make it popular among
developers. Here are some key features of Python:

1. Readability and Simplicity: Python's syntax is designed to be clean and readable,


emphasizing code readability and allowing developers to express concepts in fewer lines
of code compared to languages like C++ or Java.
2. High-Level Language: Python is a high-level language, meaning it abstracts low-level
details like memory management, allowing developers to focus on problem-solving
rather than dealing with complex system details.
3. Interpreted and Interactive: Python is an interpreted language, which means that the
code is executed line by line. This makes it easy to test and debug code. Python also
supports an interactive mode, allowing developers to experiment with code snippets in
real-time.
4. Object-Oriented: Python supports object-oriented programming (OOP) principles,
facilitating the creation and use of classes and objects, encapsulation, and inheritance.
5. Extensive Standard Library: Python comes with a comprehensive standard library that
provides modules and packages for a wide range of tasks, from working with files and
4
PYTHON PROGRAMMING III-BSC[CS]
data to handling networking and web development.
6. Dynamic Typing: Python is dynamically typed, meaning that you don't need to specify
the data type of a variable when declaring it. The interpreter automatically determines the
type during runtime.
7. Cross-Platform: Python is a cross-platform language, allowing developers to write code
that runs on various operating systems, including Windows, macOS, and Linux.
8. Community and Ecosystem: Python has a large and active community of developers.
This community contributes to a vast ecosystem of third-party libraries and frameworks
that extend Python's capabilities in areas like web development (Django, Flask), data
science (NumPy, Pandas), machine learning (TensorFlow, PyTorch), and more.
9. Open Source: Python is an open-source language, meaning that its source code is freely
available and can be modified and redistributed. This contributes to its widespread use
and continuous improvement.
10. Versatility: Python is a general-purpose programming language, suitable for a wide
range of applications, including web development, data analysis, artificial intelligence,
machine learning, automation, scientific computing, and more.
11. Integration Capabilities: Python can easily be integrated with other languages and
technologies, allowing developers to leverage existing code and infrastructure.
12. Support for Multiple Programming Paradigms: While Python is primarily an object-
oriented language, it also supports procedural and functional programming paradigms,
providing flexibility to developers.

These features contribute to Python's popularity and make it a go-to language for a broad
spectrum of applications and industries.

How to run a python program using different ways?


Introduction

what is the most important step after writing any code? Yes, obviously to compile, execute and
test the code! It is the only way to be sure if our code works at all, and whether we get the
desired output.But since Python is an interpreted language, we can skip the compilation part
and run the python script/file directly.

Script:

 It is a plain text file containing Python code.


5
PYTHON PROGRAMMING III-BSC[CS]
 It has the extension .py or .pyw
 It can be executed directly.
 Python interpreter is responsible for executing the Python scripts.

So, what is an Interpreter?

Interpreter:

 It is a program which is needed to run Python Script or code.


 It is mandatory for the Python Interpreter to be installed into one's system to run the code.
 It can run a Python code in two ways:
1. As a Script or Module
2. As a piece of code written in an interactive session
What are the Different Ways to Run Python Program(5 marks)
There are various ways to run a Python Program, let us see them -
1. The Python Interactive Mode

This is the most frequently used way to run a Python code. Here basically we do the following:

1. Open command prompt / terminal in your system


2. Enter the command - python or python3 (based on python version installed in your
system)
3. If we see these : >>> then, we are into our python prompt. It will look something like
this:
1. C:\Users\Deepa>python

2. Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit


(AMD64)] on win32

3. Type "help", "copyright", "credits" or "license" for more information.

5. >>> print("Hello World!")

Hello World!

2. Using the Python Command Line

Follow the below steps to run a Python Code through command line -
1. Write your Python code into any text editor.
2. Save it with the extension .py into a suitable directory

# Save it with any suitable file name(suppose hello.py)

print("Hello World!!")
6
PYTHON PROGRAMMING III-BSC[CS]
3. Open the terminal or command prompt.
4. Type python/python3 (based on installation) followed by the file name.py --

python YourFileName.py
3. Run Python on Text Editor

If you want to run your Python code into a text editor -- suppose VS Code, then follow the below
steps:

1. From extensions section, find and install 'Python' extension.


2. Restart your VS code to make sure the extension is installed properly
3. Create a new file, type your Python code and save it.
4. Run it using the VS code's terminal by typing the command "py hello.py"
5. Or, Right Click -> Run Python file in terminal

4. Run Python on IDLE

Python installation comes with an Integrated Development and Learning Environment,


which is popularly known as IDLE. Though Python IDLE are by-default included with Python
installations on Windows and Mac, if you’re a Linux user, then you can easily download Python
IDLE using your package manager.

Steps to run a python program on IDLE:

1. Open the Python IDLE(navigate to the path where Python is installed, open IDLE(python
version))
2. The shell is the default mode of operation for Python IDLE. So, the first thing you will
see is the Python Shell –
3. You can write any code here and press enter to execute
4. To run a Python script you can go to File -> New File
5. Now, write your code and save the file –
6. Once saved, you can run your code from Run -> Run Module Or simply by pressing F5

How to declare a variables in pythons?(5 marks)

 In Python, a variable is a symbolic name that represents or refers to a value.


 Variables are containers for storing data values.
 Variables are used to store and manipulate data within a program.
 Unlike some other programming languages, in Python, you don't need to explicitly
declare the type of a variable. The interpreter dynamically determines the type based on
the value assigned to it.
Creating Variables
 Python has no command for declaring a variable.
7
PYTHON PROGRAMMING III-BSC[CS]
 A variable is created the moment you first assign a value to it.

EXAMPLE :
x=5
y = "John"
print(x)
print(y)

OUTPUT:
5
John

Here's a simple example of variable usage in Python:

python
# Assigning values to variables
name = "Alice"
age = 30
height = 5.8

# Printing the values


print(name)
print(age)
print(height)

In this example:
 name, age, and height are variables.
 The = operator is used for assignment.
 "Alice", 30, and 5.8 are values assigned to the variables.

Python is dynamically typed, meaning that you can reassign variables to different types:

python
x = 10 # x is an integer
print(x)

x = "hello" # x is now a string


print(x)

Variables do not need to be declared with any particular type, and can even change type after they have
been set.

Variable names should follow certain rules:

 Variable names can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
 Variable names cannot start with a number.
 Python keywords (reserved words) cannot be used as variable names.
8
PYTHON PROGRAMMING III-BSC[CS]
 Variable names are case-sensitive.

Here's an example illustrating these rules:

python
my_variable = 42
My_Variable = "Hello"
MY_VARIABLE = 3.14

# These are different variables due to case sensitivity


print(my_variable)
print(My_Variable)
print(MY_VARIABLE)

Understanding how to use variables is fundamental to writing effective Python code. They are
used to store and manipulate data, making your programs flexible and dynamic.

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
OUTPUT:

Orange
Banana
Cherry
Output Variables

The Python print() function is often used to output variables.

x = "Python is awesome"
print(x)
OUTPUT:
Python is awesome

In the print() function, you output multiple variables, separated by a comma:

x = "Python"
y = "is"
z = "awesome"

9
PYTHON PROGRAMMING III-BSC[CS]
print(x, y, z)

OUTPUT:

Python is awesome

You can also use the + operator to output multiple variables:

x = "Python "
y = "is "

z = "awesome"

print(x + y + z)

OUTPUT

Python is awesome

Casting

If you want to specify the data type of a variable, this can be done with casting.
x = str(3)
y = int(3)

z = float(3)
print(x)
print(y)
print(z)
O/P:

3
3
3.0

Get the Type


You can get the data type of a variable with the type() function

x=5

y = "John"
print(type(x))
print(type(y))
OUTPUT:

<class 'int'>
<class 'str'>
10
PYTHON PROGRAMMING III-BSC[CS]

Single or Double Quotes?

String variables can be declared either by using single or double quotes:


x = "John"
print(x)

#double quotes are the same as single quotes:


x = 'John'
print(x)
OUTPUT:
John
John

Case-Sensitive

Variable names are case-sensitive.


a=4
A = "Sally"
print(a)
print(A)
OUTPUT:

4
Sally

Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.

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


x, y, z = fruits
print(x)
print(y)
print(z)

output:

apple
banana
cherry

Global Variables
11
PYTHON PROGRAMMING III-BSC[CS]

 Variables that are created outside of a function (as in all of the examples above) are
known as global variables.
 Global variables can be used by everyone, both inside of functions and outside.

Example

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()
o/p:

Python is awesome

How to assign the values to a variable in python give some example(5 marks)
 Assignment is the process of associating a value with a variable. You use the = operator
for assignment.
 Unlike other languages, in Python this is very simple. We don't need to declare a variable, all we
need to do is give it a name, put the equal sign ( = ) and then the value that we want to assign.
That's it.
 When programming, it is useful to be able to store information in variables. A variable is a string
of characters and numbers associated with a piece of information.
 The assignment operator, denoted by the “=” symbol, is the operator that is used to assign
values to variables in Python.
 The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”.
After executing this line, this number will be stored into this variable. Until the value is changed
or the variable deleted, the character x behaves like the value 1.

Example:

Variable Type Data/Info

x int 1

12
PYTHON PROGRAMMING III-BSC[CS]
y int 2

python
# Assigning values to variables
a = 10
b = 3.14
c = "Python"

# Reassigning variables
a = 20
b = "Hello"

Variable Naming Rules:

 Variable names can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
 They cannot start with a number.
 Python keywords (reserved words) cannot be used as variable names.
 Variable names are case-sensitive (count and Count are different variables).

Example:

python
my_variable = 42
another_variable = "Python"

Multiple Assignment:

 You can assign multiple variables in a single line.

Example:

python
x, y, z = 10, 20, 30

Now, x is 10, y is 20, and z is 30.

Assigning Values to Variables in Python


Below are the steps and methods by which we can assign values to variables in Python and other
languages:
 Direct Initialization Method
 Using Conditional Operator
Assign Values to Variables Direct Initialisation Method

13
PYTHON PROGRAMMING III-BSC[CS]
In this method, we will directly assign the value in Python but in other programming languages
like C, and C++, we have to first initialize the data type of the variable. So, In Python, there is no
need for explicit declaration in variables as compared to using some other programming
languages. We can start using the variable right away.

#include <bits/stdc++.h>
using namespace std;

int main()
{
// initialising variables directly
int a = 5;

// printing value of a
cout << "The value of a is: " << a;
}
The value of a is: 5

Assign Values to Variables Using Conditional Operator

This method is also called Ternary operators. So Basic Syntax of a Conditional Operator is:-

condition? True_value : False_Value

Using Conditional Operator, we can write one line code in python. The conditional operator
works in such a way that first evaluates the condition, if the condition is true, the first
expression( True_value) will print else evaluates the second expression(False_Value).

Below is the syntax in other popular languages.

#include <bits/stdc++.h>
using namespace std;

int main()
{
// initialising variables using Conditional Operator
int a = 20 > 10 ? 1 : 0;

// printing value of a
cout << "The value of a is: " << a;
}
Output
The value of a is: 1

Python One liner Conditional Statement Assigning

14
PYTHON PROGRAMMING III-BSC[CS]
In the another example, we have used one liner if-else conditional statement in Python.

#one liner if-else


a = 1 if 20 > 10 else 0
# printing value of a

print ("The value of a is: " + str(a))

Output

The value of a is: 1

Explain the basics of Python or fundamental of python (5 marks)


Let's ,see some of the basics of Python:

1. Variables and Data Types:

 Variables are used to store data values.


 Common data types include integers (int), floating-point numbers (float), strings (str),
booleans (bool), and more.

go
```python
makefile
# Example of variables and data types
x = 5 # int
y = 3.14 # float
name = "John" # str
is_true = True # bool
```
2. Basic Operations:

 Python supports standard arithmetic operations: addition (+), subtraction (-),


multiplication (*), division (/), and exponentiation (**).
go
```python
makefile
# Basic operations
result = 10 + 5 # 15
product = 3 * 4 # 12
quotient = 20 / 2 # 10.0
```
3. Conditional Statements:
 if, elif (else if), and else are used for conditional branching.

15
PYTHON PROGRAMMING III-BSC[CS]
go
```python
bash
# Example of a conditional statement
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
```
4. Loops:
 for and while loops are used for iteration.

go
```python
perl
# Example of a for loop
for i in range(5):
print(i) # Prints numbers 0 to 4

# Example of a while loop


count = 0
while count < 5:
print(count)
count += 1
```
5. Functions:

 Functions allow you to group code into reusable blocks.


go
```python
python
# Example of a function
def greet(name):
print("Hello, " + name + "!")

greet("Alice") # Outputs: Hello, Alice!


```
6. Lists:

 Lists are used to store multiple items in a single variable.

go
16
PYTHON PROGRAMMING III-BSC[CS]
```python
perl
# Example of a list
fruits = ["apple", "orange", "banana"]
print(fruits[0]) # Outputs: apple
```
7. Dictionaries:
 Dictionaries store key-value pairs.

go
```python
perl
# Example of a dictionary
person = {"name": "John", "age": 25, "city": "New York"}
print(person["age"]) # Outputs: 25
```
8. Input and Output:
 input() is used to take user input, and print() is used to display output.

go
```python
lua
# Input and output
name = input("Enter your name: ")
print("Hello, " + name + "!")
```
These are some of the fundamental concepts in Python.
9. Whitespace and indentation

If you’ve been working in other programming languages such as Java, C#, or C/C++, you know
that these languages use semicolons (;) to separate the statements.

However, Python uses whitespace and indentation to construct the code structure.

The following shows a snippet of Python code:

# define main function to print out something


def main():
i = 1
max = 10
while (i < max):
print(i)
i = i + 1

17
PYTHON PROGRAMMING III-BSC[CS]
# call function main
main()

10. Comments
The comments are as important as the code because they describe why a piece of code was
written.

When the Python interpreter executes the code, it ignores the comments.

In Python, a single-line comment begins with a hash (#) symbol followed by the comment. For
example:

# This is a single line comment in PythonCode language: Python (python)

And Python also supports other kinds of comments.

11. Continuation of statements


Python uses a newline character to separate statements. It places each statement on one line.

However, a long statement can span multiple lines by using the backslash (\) character.

The following example illustrates how to use the backslash (\) character to continue a statement
in the second line:

if (a == True) and (b == False) and \


(c == True):
print("Continuation of stat

12. Identifiers
Identifiers are names that identify variables, functions, modules, classes, and other objects in
Python.

The name of an identifier needs to begin with a letter or underscore ( _). The following characters
can be alphanumeric or underscore.

Python identifiers are case-sensitive. For example, the counter and Counter are different
identifiers.
In addition, you cannot use Python keywords for naming identifiers.
13. Keywords
Some words have special meanings in Python. They are called keywords.

18
PYTHON PROGRAMMING III-BSC[CS]
The following shows the list of keywords in Python:

False class finally is return


None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raiseCode language: Python (python)

Python is a growing and evolving language. So its keywords will keep increasing and changing.

Python provides a special module for listing its keywords called keyword.

To find the current keyword list, you use the following code:

import keyword

print(keyword.kwlist)

14. String literals

Python uses single quotes ('), double quotes ("), triple single quotes (''') and triple-double
quotes (""") to denote a string literal.

The string literal need to be surrounded with the same type of quotes. For example, if you use a
single quote to start a string literal, you need to use the same single quote to end it.

The following shows some examples of string literals:

s = 'This is a string'
print(s)
s = "Another string using double quotes"
print(s)
s = ''' string can span
multiple line '''

print(s)
Explain the basic style to make a python code?(5 marks)

 Coding guidelines help engineering teams to write consistent code which is easy to read
and understand for all team members.
19
PYTHON PROGRAMMING III-BSC[CS]
 Python has an excellent style guide called PEP8. It covers most of the situations you will
step into while writing Python.
 We like PEP8, believe there has been much effort and thinking put into it.
 On the other hand, PEP8 can be considered a generic Python guideline rather than strict
rules as it allows different approaches to achieve similar goals.
 And that may be a problem for teams with different skill levels that using methodologies
where the team members are equal and there is always a place to argue.
 It is way easier to write the code or do a code review by a strictly defined practical style
guide. Establishing such guidelines can be problematic but it will be very beneficial for
the whole team if it is done the right way
 The final goal of this guide is to have code that is clean, consistent, and efficient.
Remember — сode is read more often than it is written
 and only incidentally for machines to execute. Some parts of the guide are opinionated
and meant to be strictly followed to preserve consistency when writing new code..

Code Layout

 Use 4 spaces instead of tabs


 Maximum line length is 120 symbols
 2 blank lines between classes and functions
 1 blank line within class between class methods
 No blank line following a def line.
 No whitespace inside parentheses, brackets, or braces.
 Surround operators with single whitespace on either side.
 Never use whitespaces around = when passing keyword arguments or defining a default
parameter value,
 Use blank lines for logic separation of functionality within functions/methods wherever it
is justified.
 Move function arguments to a new line with an indentation, if they do not fit into the
specified line length
 Move the logical conditions to the new line if the line does not fit the maximum line size.
This will help you understand the condition by looking from top to bottom. Poor
formatting makes it difficult to read and understand complex predicates.
 Use multiline strings, not \\ since it gets much more readable.
 Place a class' init at the beginning of each class
 Use named arguments to improve readability and avoid dummy mistakes in the future
 Never end your lines with a semicolon, and do not use a semicolon to put two
statements on the same line.
 Chaining methods should be broken up on multiple lines for better readability
20
PYTHON PROGRAMMING III-BSC[CS]

Explain the Python object with give some examples ?Or how to creating a
python object ?(5 marks)

 An Object is an instance of a Class. A class is like a blueprint while an instance is a copy


of the class with actual values.
 Python is an object-oriented programming language that stresses objects i.e. it mainly
emphasizes functions.
 Python Objects are basically an encapsulation of data variables and methods acting on
that data into a single entity.

Understanding of Python Object

 understanding of the concept of objects in Python.


 Let’s consider an example, many of you have played CLASH OF CLANS, So let’s
assume base layout as the class which contains all the buildings, defenses, resources, etc.
 Based on these descriptions we make a village, here the village is the object in Python.

Syntax:

obj = MyClass()
print(obj.x)
 Instance defining represent memory allocation necessary for storing the actual data of
variables.
 Each time when you create an object of class a copy of each data variable defined in that
class is created.
 In simple language, we can state that each object of a class has its own copy of data
members defined in that class.

How to Creating a Python Object


Working of the Program: Audi = Cars()

 A block of memory is allocated on the heap. The size of memory allocated is decided by
the attributes and methods available in that class(Cars).
 After the memory block is allocated, the special method init () is called internally.
Initial data is stored in the variables through this method.
21
PYTHON PROGRAMMING III-BSC[CS]
 The location of the allocated memory address of the instance is returned to the
object(Cars).
 The memory location is passed to self.

class Cars:
def init (self, m, p):
self.model = m
self.price = p

Audi = Cars("R8", 100000)

print(Audi.model)
print(Audi.price)

Output:

R8
100000

How to Accessing Class Member Using Object:

Variables and methods of a class are accessible by using class objects or instances in Python.
Syntax:

obj_name.var_name
Audi.model

obj_name.method_name()
Audi.ShowModel();

obj_name.method_name(parameter_list)
Audi.ShowModel(100);

Example 1:

# Python program to create instance


# variables inside methods

class Car:

# Class Variable
vehicle = 'car'

# The init method or constructor


22
PYTHON PROGRAMMING III-BSC[CS]
def init (self, model):

# Instance Variable
self.model = model

# Adds an instance variable


def setprice(self, price):
self.price = price

# Retrieves instance variable


def getprice(self):
return self.price

# Driver Code
Audi = Car("R8")
Audi.setprice(1000000)
print(Audi.getprice())

Output:

1000000

Explain the internal types in python ?(5 marks )


 Python is a high-level programming language, and it abstracts away many of the low-
level details of computer architecture.
 As a result, Python doesn't expose the internal details of data types in the same way that
lower-level languages might.

However, I can provide a brief overview of how certain common data types are typically
implemented:

1. int:
o Internally, integers are usually implemented using the native integer types
provided by the hardware. For example, in a 64-bit system, Python's int would
typically map to a 64-bit integer.
2. float:
o Python uses the native floating-point types provided by the hardware. On most
systems, this is the IEEE 754 double-precision floating-point format.
3. str:
o Strings in Python are sequences of Unicode characters. Internally, Python might use a variety of
representations for strings, and the actual implementation detailscan be complex due to the need to
23
PYTHON PROGRAMMING III-BSC[CS]
Unicode, variable-length
characters, and various optimizations.
4. list:
o Lists in Python are implemented as dynamic arrays. The list object contains
pointers to the elements, and the underlying array is resized as needed.
5. tuple:
o Tuples are similar to lists but are immutable. Internally, they may use a similar
representation to lists, but the immutability allows for certain optimizations.
6. dict:

24
PYTHON PROGRAMMING III-BSC[CS]
o Dictionaries in Python are implemented as hash tables. The keys are hashed, and
the values are stored at the corresponding hash indices.

7. set:
o Sets are also implemented using a hash table. They store unique elements, and the
hash table allows for efficient membership tests.

25
PYTHON PROGRAMMING III-BSC[CS]
python
8. bool:
o Booleans represent the truth values True and False. Internally, these are often
implemented as integers, where True is 1 and False is 0.
9. NoneType:
o The None type is a singleton object representing the absence of a value. It is often
used to signify that a variable or function returns nothing.

While understanding these internal details can be interesting, it's not typically necessary for
everyday programming in Python. The beauty of Python lies in its simplicity and abstraction,
allowing developers to focus on solving problems rather than dealing with low-level details.
What are the various operator in python (or) discuss about standard type
operators (5 marks)

Python supports a variety of operators for performing operations on different types of data. Here
are some of the standard operators in Python:

1. Arithmetic Operators:
python
# Addition
result = 5 + 3 # Result: 8

# Subtraction
result = 7 - 2 # Result: 5

# Multiplication
result = 4 * 6 #
Result: 24

# Division
result = 10 / 2 # Result: 5.0 (floating-point division)
2. Floor Division and Modulus:
python
# Floor Division (returns the quotient)
result = 10 // 3 # Result: 3

# Modulus (returns the remainder)


result = 10 % 3 # Result: 1

3. Exponentiation:
python
result = 2 ** 3 # Result: 8 (2 raised to the power of 3)

4. Comparison Operators:
python

26
PYTHON PROGRAMMING III-BSC[CS]
python
# Equal to
result = 5 == 5 # Result: True

# Not equal to
result = 5 != 3 # Result: True

# Greater than
result = 7 > 4 # Result: True

# Less than
result = 6 < 10 # Result: True

# Greater than or equal to


result = 8 >= 8 # Result: True

# Less than or equal to


result = 3 <= 2 # Result: False

Logical Operators:
python
# Logical AND
result = True and False # Result: False

# Logical OR
result = True or False # Result: True

# Logical NOT
result = not True # Result: False

Membership Operators:
python
# in (checks if a value is present in a sequence)
result = 3 in [1, 2, 3] # Result: True

# not in (checks if a value is not present in a sequence)


result = 5 not in [1, 2, 3] # Result: True

Identity Operators:
python
# is (checks if two variables reference the same object)
result = "hello" is "hello" # Result: True

# is not (checks if two variables do not reference the same object)


result = "hello" is not "world" # Result: True

27
PYTHON PROGRAMMING III-BSC[CS]
python
These are some of the standard operators in Python. They are used for various operations on
different data types. Keep in mind that some operators might behave differently for different
types (e.g., + for concatenation of strings, lists, etc.).

Explain the built in data types(10 marks)

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

1. Numeric Types:
 int: Integer data type.
 float: Floating-point or decimal numbers.
 complex: Complex numbers.

x = 5 # int
y = 3.14 # float
z = 2 + 3j # complex
```
2. Sequence Types:
 str: String data type.
 list: List is an ordered collection of items.
 tuple: Similar to a list but immutable (cannot be modified after creation).

```python
makefile
text = "Hello, Python!" # str
numbers = [1, 2, 3, 4, 5] # list
coordinates = (10, 20) # tuple
28
PYTHON PROGRAMMING III-BSC[CS]
python
```

3. Set Types:
 set: Unordered collection of unique items.

```python
makefile
my_set = {1, 2, 3, 4, 5} # set
```
4. Mapping Type:
 dict: Dictionary is a collection of key-value pairs.

go
```python
makefile
person = {"name": "John", "age": 25, "city": "New York"} # dict
```

5. Boolean Type:
 bool: Represents boolean values (True or False).

go
```python
graphql
is_true = True # bool
is_false = False # bool
```

6. None Type:
 NoneType: Represents the absence of a value or a null value.

go
```python
makefile
no_value = None # NoneType
```

7. Binary Types:
 bytes: Immutable sequence of bytes.
 bytearray: Mutable sequence of bytes.

go
```python
perl
binary_data = b'hello' # bytes
mutable_binary_data = bytearray(b'hello') # bytearray
```

29
PYTHON PROGRAMMING III-BSC[CS]
python

8. Other Built-in Types:


 range: Represents a sequence of numbers.
 complex: Represents complex numbers.

go
```python
go
numbers_range = range(1, 6) # range
```These are the fundamental built-in data types in Python. Each data type has its own set of
operations and methods that can be applied.
How to Getting the Data Type
You can get the data type of any object by using the type() function:
x=5
print(type(x))
o/P:<class 'int'>
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:

Example Data Type


x = "Hello World" str
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set


x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneT

Setting the Specific Data Type


If you want to specify the data type, you can use the following constructor functions:
30
PYTHON PROGRAMMING III-BSC[CS]
python

x = int(20)
int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

What are the standard built-in functions in Python (or) Describe about built
in functions with give some examples(10 marks)

Python provides a variety of built-in functions that you can use to perform common operations on
different types of data. Here are some of the standard built-in functions in Python:
1.Type Conversion Functions
2.Mathematical Functions
3.String Functions
3. String Functions
4. Other Common Functions

1.Type Conversion Functions

1. int(x): Converts x to an integer.

python
num_str = "42"
num_int = int(num_str) # Result: 42

2. float(x): Converts x to a floating-point number.

31
PYTHON PROGRAMMING III-BSC[CS]
python
python
 num_int = 42
num_float = float(num_int) # Result: 42.0

3. str(x): Converts x to a string.


python
num = 42
num_str = str(num) # Result: '42'

2.Mathematical Functions:

1. abs(x): Returns the absolute value of x.

python
result = abs(-5) # Result: 5

2. round(x, n): Rounds x to n decimal places.result = round(3.14159, 2) # Result: 3.14

3. max(iterable) and min(iterable): Returns the maximum or minimum value in an iterable.

python
numbers = [1, 5, 3, 7, 2]
max_value = max(numbers) # Result: 7

3.String Functions:

1. len(s): Returns the length of a string, list, or other iterable.

python
text = "Hello, Python!"
length = len(text) # Result: 14

2. str.upper() and str.lower(): Converts all characters in a string to uppercase or lowercase.

python
text = "Hello, Python!"
upper_case = text.upper() # Result: 'HELLO, PYTHON!'

3. String Functions:

1. len(lst): Returns the number of items in a list.

python
numbers = [1, 2, 3, 4, 5]
length = len(numbers) # Result: 5

2. list.append(x): Adds an element to the end of a list.

python
numbers = [1, 2, 3]
numbers.append(4) # numbers is now [1, 2, 3, 4]
32
PYTHON PROGRAMMING III-BSC[CS]
python

Other Common Functions:

 input(prompt): Reads a line from input and returns it as a string.name = input("Enter your name: ")

 print(x): Prints the specified value.

python
 print("Hello, Python!")

 type(x): Returns the type of an object.

python
num = 42
data_type = type(num) # Result: <class 'int'>

These are just a few examples of the many built-in functions available in Python.

Each function serves a specific purpose and can be useful in different scenarios.

QUESTION BANK

UNIT - I

1. Explain The Python And Where We Used In Python Programming Languages ?(5 Marks)
2. Explain the python orgins briefly(5 marks)
3. Explain features of pythons (5 marks)
4. What Are The Different Ways To Run Python Program(5 Marks)
5. Explain The Internal Types In Python ?(5 Marks )
6. What Are The Various Operator In Python (Or) Discuss About Standard Type Operators
(5 Marks)
7. What Are The Various Operator In Python (Or) Discuss About Standard Type Operators
(5 Marks)
8. How To Assign The Values To A Variable In Python Give Some Example(5 Marks)
9. Explain The Basics Of Python Or Fundamental Of Python (5 Marks)
10. How To Declare A String In Various Method Used In Python ?(5 Marks)
11. Explain The Basic Style To Make A Python Code?(5 Marks)
12. Explain The Python Object With Give Some Examples ?Or How To Creating A Python
Object ?(10 Marks)

33
PYTHON PROGRAMMING III-BSC[CS]
13. What Are The Standard Built-In Functions In Python (Or) Describe About Built In
Functions With Give Some Examples(10 Marks)
14. Explain The Built-In Data Types(10 Marks)

1. Who created python?

a.Van dar dusa b.Mike turgo


c.Guido van Rossum d.None of these
Answer: c

2. In which year python was created?

a.1992 b.2002 c.1999 d.1980 Answer: d

3. By which program python was interpreted?

a.Python compiler b.Python Interpreter

c.Python CLI d.None of these Answer: b


4. What will be the output of the following code?
4+3%5
a.5 b.4 c.6 d.7 Answer: d

5. Which of the following keyword is used for function in python?

a.Def b.function c.func d.None of these Answer: a


6. Which of the following brackets are used in python to create a list?

a.( ) b.[ ] c.{ } d.None of these Answer - 2. [ ]


7. Which of the following is the correct extension of a python file?
a).py b).pl c).ty d.None of these Answer - 1. .py
8. In which language python is written?
a.Java b.C# c.C d.Perl Answer - 3. C

9. Which of the following is invalid variable?


a.string_123 b._hello c.12_hello d.None of these Answer - 3. 12_hello

10. Is python identifiers case sensitive?


a.False b.True c.Depends on program d.Depends on computer

Correct Answer - 2. True


11. Which of the following is not the part of python programming?
a.Pointers b.Loops c.Dynamic typing d.None of these

Correct Answer - 1. Pointers


12. What is the output of the following code?
print(0.3 + 0.5 == 0.8)

34
PYTHON PROGRAMMING III-BSC[CS]

a.True b.False c.Error d.Machine dependent

Correct Answer - 1. True


13. Which function is used to get the version of python?

a.system.getversion b.sys.version(1)
c.system.get d.None of the above

Correct Answer - 2. sys.version(1)


14. What will be the output of the following code?
print(1**(30**2))
a.60 b.3 c.1 d.0 Answer - 3. 1
15. Which of the following is the built in function in python?
a.dvd() b.ntr() c.sqrt() d.print() Answer - 4. print()
16. What is the output of the following code?
print(min(max(False,-30,-4), 12,7))
a.Error b.True c.False d.None of these Answer - 3. False
17. What is the correct extension of python file?
a).python b).pyt c).py d).None of these Answer - 3. .py
18. What will be the output of the following?
4+7%5
a.7 b.6 c.5 d.3 Answer - 2. 6
19. What will be the output of the following code?
4-6*2%3

a.4 b.3 c.2 d.1 Answer - 1. 4


20. What will be the output of the following code?
2**3**2
a.214 b.456 c.567 d.512 Answer - 4. 512

21. Which of the following operator is used for truncation division?

a.? b.% c./ d.// Answer - 4. //


22. Which of the following is NOT a data type in python?

a.list b.tuple c.stringd.variable Answer - 4. variable


23. What is the output of the following code?
x=5
y = 20
print(x * y)

a.100 b.20 c.10 d.5 Answer - 1. 100


24. How will you get the second element in a list called "bus"?
35
PYTHON PROGRAMMING III-BSC[CS]

a.bus[3] b.bus[2] c.bus[0] d.bus[1] Answer - 4. bus[1]


25. What is the correct syntax to create a function in Python?

a.def myfunction() b.function myfunction


c.create myfunction d.None of these Answer - 1. def myfunction()
26. What is the use of the "for" loop ?

a.To repeat a block of code a given number of times b.To iterate over a sequence

c.To execute a block of code specified condition d.None of these Answer - 227.
27. What is the use of 'While' loop in Python?

a.Repeat a block of code b. Execute a block of code

c.Iterate a sequence of code d. None of these

Answer - 1. Repeat a block of code


28. Which is the data type of the following Python code?
x = [1 ,2 , 3]

a.List b.Integer c.Tuple d.Dictionary Answer - 1. List


29. What will be the output of the following Python code?
a=5
b=2
print(a%b)
a.2 b.1 c.3 d.0 Answer - 2. 1
30. Which of the following is a correct way to print the statement "Hello,
World!" in Python?
a.PRINT "Hello, World!" b.print("Hello, World!")
c.print "Hello, World!" d.System.out.println("Hello, World!")

Answer - 2. print("Hello, World!")


31. What is the output of the following code?
x = [1, 2, 3, 4, 5]
print(x[-3:])

a.[1,4,5] b.[2,3] c.[2,3,4] d.[1,2,3] Answer - 3. [2,3,4]


32. What this code of Python will return?
x = [1, 2, 3, 4, 5]
36
PYTHON PROGRAMMING III-BSC[CS]
y=x
y[0] = 100
print(x)

a.[1,2,3,4] b.[100,2,3,4]
c.[100,2] d.[100,2,3,4,5] Answer - 4.
33. What is the output of the following code?
i=1
while(i<=3):
print(i)
i=i+1

a. 123 b. 12 c. 1234 d. None of these Answer - 1


34. What is the data types of any variable which holds the value 'hello world' ?
a.int b.float c.string d.None of these Answer - 3. string
35. What is the output of the following code snippet?
print(10/3)
a. 3.0 b. 3 c. 1 d. 3.3333333333333 Answer - 4.
36. What is the output of the following code snippet?
mylist = [1,2,3,4,5]
print(mylist[2:4])

a.[2,3] b.[2,3,4] c.[3,4] d.None of these Answer - 3. [3,4]


37. What is the correct syntax for defining a function in Python?

a. define function(x) b. function x()


c. def x(): d. None of these Answer - 3. def x():
38. List in Python is ................in nature.

a. functionable b. mutable c. immutable d .None of these Answer - 2.


39. Which of the following statements is true regarding Python?
a.Python does not support object-oriented programming.
b.Python uses indentation to indicate block structure.
c.Python is a compiled language.
d.Python is a statically typed language. Answer - 2.
40. What is the output of the following Python code?
list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1)

37
PYTHON PROGRAMMING III-BSC[CS]

a.[1,2,3] b.[1,2,3,4] c.[2,3,4] d.[1,4,2,3] Answer - 2. [1,2,3,4]

41. Which of the following is data type is NOT Valid in Python?

a.Float b.Complex c.Tuple s.Array Answer - 4


42. What is the output of the following Python code?
x = 10
y= 5
print(x % y)
a.2 b.1 c.0 d.5 Answer - 2.
43. What does the following code do?
x = [1, 2, 3]
y = [4, 5, 6]
z= x+y
a.Multiplies the elements of x and y together b.Adds the elements of x and y together
c.Concatenates the elements of x and y together d.Subtract the elements of x and y together
Answer - 3.
44. What is the output of the following code?
x=5
y=2
if x > y:
print("x is greater than y")
else:
print("y is greater than x")

a. y is greater than x b.x is greater than y

c.x=y d.None of these Answer - 2.


45. Which of the following is NOT a comparison operator in Python?
a.== b.!= c.++ d.<= Answer - 3. ++
46. Which of the following is an arithmetic operator in Python?
a.>= b.== c.!= d.// Answer - 4. //
47. What is the output of the following code?
for i in range(5):
print(i)

a.0 1 2 3 4 5 b.1 2 3 4 c.0 1 2 3 4 d.1 2 3 4 Answer - 3. 0 1 2 3 4


48. What is the output of the following code?
x=5
y = "hello"

38
PYTHON PROGRAMMING III-BSC[CS]
print(x + y)

a.hello5 b.5hello c.hello+5 d.TypeError Answer - 4.


49. What will be output of the following Python code?
print(3+4*5)

a.27 b.23 c.35 d.30 Answer - 2. 23


50. Which of the following is NOT a valid Python tag?

a.<body> b.<title> c.<strong> d.<h1> Answer - 2. <title>


51. What is the purpose of the <head> tag in Python?

a.To define a section of a webpage that should be displayed as a heading

b.To define the main content of a webpage

c.To define a section of a webpage that contains metadata about the document

d.To define a line break in a text document Answer - 3.


52. What is the output of the following Python code?
import array
a = array.array('i', [1, 2, 3])
del a[1]
print(a)

a.array('i', [2, 3]) b.array('i', [1, 3]) c.[2, 3] d.[1, 3] Answer - 2.


43. Which of the following is NOT a valid typecode for Python array?

a.'i' b.'f' c.'d' d.'s' Answer - 4. 's'

39
PYTHON PROGRAMMING III-BSC[CS]
Unit-2

Introduction to numbers
How to declare a numbers in python language ?(5 marks)

 Python supports integers, floats, and complex numbers.

Integers
 The integers are numbers such as -1, 0, 1, 2, and 3, .. and they have type int.
 You can use Math operators like +, -, *, and / to form expressions that include integers.
For example:

>>> 20 + 10
30
>>> 20 - 10
10
>>> 20 * 10
200
>>> 20 / 10
2.0
Code language: Python (python)

To calculate exponents, you use two multiplication symbols (**). For example:

>>> 3**3
27Code language: Python (python)

To modify the order of operations, you use the parentheses (). For example:

>>> 20 / (10 + 10)


1.0 Code language: Python (python)
Floats
 Any number with a decimal point is a floating-point number. The term float means that
the decimal point can appear at any position in a number.

In general, you can use floats like integers. For example:

>>> 0.5 + 0.5


1.0
>>> 0.5 - 0.5
0.0
>>> 0.5 / 0.5

40
PYTHON PROGRAMMING III-BSC[CS]
1.0
>>> 0.5 * 0.5
0.25Code language: Python (python)

The division of two integers always returns a float:

>>> 20 / 10
2.0Code language: Python (python)

If you mix an integer and a float in any arithmetic operation, the result is a float:

>>> 1 + 2.0
3.0 Code language: Python (python)

Due to the internal representation of floats, Python will try to represent the result as precisely as
possible. However, you may get the result that you would not expect. For example:

>>> 0.1 + 0.2


0.30000000000000004Code language: Python (python)

Just keep this in mind when you perform calculations with floats. And you’ll learn how to handle
situations like this in later tutorials.

Double precision floating point numbers

 In computer programming, a double precision floating-point number is a data type that


represents a real number (i.e., a number that can have a fractional part) with double
precision.

41
PYTHON PROGRAMMING III-BSC[CS]
 "Double precision" means that the number is represented using 64 bits in memory,
providing greater precision compared to single-precision floating-point numbers, which
use 32 bits.

 In many programming languages, the keyword "double" is used to declare a variable as a


double-precision floating-point number.

 For example, in languages like C, C++, and Java, you might declare a double-precision in
python variable like this:

double myDouble = 3.14159 ;




 In Python, the float data type typically represents double-precision floating-point
numbers. For example:

my_double = 3.14159


 The double-precision format allows for a larger range of representable values and greater
precision in representing fractional parts of numbers compared to single precision.

 It's commonly used in applications where high precision is required, such as scientific
calculations, financial applications, and simulations.

Underscores in numbers
When a number is large, it’ll become difficult to read. For example:

count = 10000000000Code language: Python (python)

To make the long numbers more readable, you can group digits using underscores, like this:

count = 10_000_000_000Code language: Python (python)

When storing these values, Python just ignores the underscores. It does so when displaying the
numbers with underscores on the screen:
count = 10_000_000_000
print(count)Code language: Python (python)

Output:
10000000000Code language: Python (python)

The underscores also work for both integers and floats.


42
PYTHON PROGRAMMING III-BSC[CS]

Note that the underscores in numbers have been available since Python 3.6

Complex numbers

 In Python, complex numbers are represented using the data type.


complex
 A complex number consists of a real part and an imaginary part, both of which are floating-point
numbers.
 The imaginary part is specified using a "j" or "J" suffix. Here's an example:
 # Creating a complex number
 complex_num = 3 + 2j
# Printing the complex number

print("Complex Number:", complex_num)

# Accessing real and imaginary parts

real_part = complex_num.real

imaginary_part = complex_num.imag

print("Real Part:", real_part)

print("Imaginary Part:", imaginary_part)

In the above example, 3 is the real part, and 2j is the imaginary part. You can perform various
operations on complex numbers in Python, including addition, subtraction, multiplication, division,
and more.

Explain the operators in python (10 marks)

Defintion :
In programming,we want to compare a value with another value. To do that, you use comparison
operators.
Bascic Comparision Operators:

Python has six comparison operators, which are as follows:


 Less than ( < )
 Less than or equal to (<=)
 Greater than (>)
 Greater than or equal to (>=)
 Equal to ( == )
 Not equal to ( != )
43
PYTHON PROGRAMMING III-BSC[CS]

These comparison operators compare two values and return a boolean value, either True or
False.

You can use these comparison operators to compare both numbers and strings.

Less than operator (<)

The Less Than operator (<) compares two values and returns True if the value on the left is less
than the value on the right. Otherwise, it returns False:

left_value < right_valueCode language: Python (python)

The following example uses the Less Than (<) operator to compare two numbers:

>>> 10 < 20
True
>>> 30 < 20
FalseCode language: Python (python)

It’s quite obvious when you use the less-than operator with the numbers.

The following example uses the less than operator (<) to compare two strings:

>>> 'apple' < 'orange'


True
>>> 'banana' < 'apple'
FalseCode language: Python (python)

The expression 'apple' < 'orange' returns True because the letter a in apple is before the
letter o in orange.

Similarly, the 'banana' < 'apple' returns False because the letter 'b' is after the letter 'a'.

The following example shows how to use the less-than operator with variables:

>>> x = 10
>>> y = 20
>>> x < y
True
>>> y < x
FalseCode language: Python (python)

Less than or equal to operator (<=)


44
PYTHON PROGRAMMING III-BSC[CS]

The less than or equal to operator compares two values and returns True if the left value is less
than or equal to the right value. Otherwise, it returns False:

left_value <= right_valueCode language: Python (python)

The following example shows how to use the less than or equal to operator to compare two
numbers:

>>> 20 <= 20
True
>>> 10 <= 20
True
>>> 30 <= 30
TrueCode language: Python (python)

This example shows how to use the less than or equal to operator to compare the values of two
variables:

>>> x = 10
>>> y = 20
>>> x <= y
True
>>> y <= x
FalseCode language: Python (python)

Greater than operator (>)

The greater than the operator (>) compares two values and returns True if the left value is greater
than the right value. Otherwise, it returns False:

left_value > right_valueCode language: Python (python)

This example uses the greater than operator (>) to compare two numbers:

>>> 20 > 10
True
>>> 20 > 20
False
>>> 10 > 20
FalseCode language: Python (python)

The following example uses the greater than operator (>) to compare two strings:

>>> 'apple' > 'orange'


False
>>> 'orange' > 'apple'
45
PYTHON PROGRAMMING III-BSC[CS]
TrueCode language: Python (python)

Greater Than or Equal To operator (>=)


The greater than or equal to operator (>=) compares two values and returns True if the left value
is greater than or equal to the right value. Otherwise, it returns False:

left_value >= right_valueCode language: Python (python)

The following example uses the greater than or equal to an operator to compare two numbers:

>>> 20 >= 10
True
>>> 20 >= 20
True
>>> 10 >= 20
FalseCode language: Python (python)

The following example uses the greater than or equal to operator to compare two strings:

>>> 'apple' >= 'apple'


True
>>> 'apple' >= 'orange'
False
>>> 'orange' >= 'apple'
TrueCode language: Python (python)

Equal To operator (==)

The equal to operator (==) compares two values and returns True if the left value is equal to the
right value. Otherwise, it returns False :

left_value == right_valueCode language: Python (python)

The following example uses the equal to operator (==) to compare two numbers:

>>> 20 == 10
False
>>> 20 == 20
TrueCode language: Python (python)

And the following example uses the equal to operator (==) to compare two strings:

>>> 'apple' == 'apple'

46
PYTHON PROGRAMMING III-BSC[CS]
True
>>> 'apple' == 'orange'
FalseCode language: Python (python)

Not Equal To operator (!=)

The not equal to operator (!=) compares two values and returns True if the left value isn’t equal
to the right value. Otherwise, it returns False.

left_value != right_valueCode language: Python (python)

For example, the following uses the not equal to operator to compare two numbers:

>>> 20 != 20
False
>>> 20 != 10
TrueCode language: Python (python)

The following example uses the not equal to operator to compare two strings:

>>> 'apple' != 'apple'


False
>>> 'apple' != 'orange'
True

Explain the Python logical operators with give examples(5 marks)


Sometimes, you may want to check multiple conditions at the same time. To do so, you use
logical operators.

Python has three logical operators:

 and
 or
 not

The and operator


The and operator checks whether two conditions are both True simultaneously:
a and bCode language: Python (python)

It returns True if both conditions are True. And it returns False if either the condition a or b is
False.

The following example uses the and operator to combine two conditions that compare the price
with numbers:
47
PYTHON PROGRAMMING III-BSC[CS]

>>> price = 9.99


>>> price > 9 and price < 10
TrueCode language: Python (python)

The result is True because the price is greater than 9 and less than 10.

The following example returns False because the price isn’t greater than 10:

>>> price > 10 and price < 20


FalseCode language: Python (python)

In this example, the condition price > 10 returns False while the second condition price <
20 returns True.

The following table illustrates the result of the and operator when combining two conditions:

a B a and b
True True True
True False False
False False False
False True False

As you can see from the table, the condition a and b only returns True if both conditions
evaluate to True.

The or operator

Similar to the and operator, the or operator checks multiple conditions. But it returns True when
either or both individual conditions are True:
a or bCode language: Python (python)

The following table illustrates the result of the or operator when combining two conditions:

a b a or b
True True True
True False True
False True True
False False False

48
PYTHON PROGRAMMING III-BSC[CS]
The or operator returns False only when both conditions are False.

The following example shows how to use the or operator:

>>> price = 9.99


>>> price > 10 or price < 20
>>> TrueCode language: Python (python)

In this example, the price < 20 returns True, therefore, the whole expression returns True.

The following example returns False because both conditions evaluate to False:

>>> price = 9.99


>>> price > 10 or price < 5
FalseCode language: Python (python)

The not operator

The not operator applies to one condition. And it reverses the result of that condition, True
becomes False and False becomes True.

not aCode language: Python (python)

If the condition is True, the not operator returns False and vice versa.

The following table illustrates the result of the not operator:

a not a

True False
False True

The following example uses the not operator. Since the price > 10 returns False, the not
price > 10 returns True:

>>> price = 9.99


>>> not price > 10
TrueCode language: Python (python)

Here is another example that combines the not and the and operators:

>>> not (price > 5 and price < 10)


FalseCode language: Python (python)

In this example, Python evaluates the conditions based on the following order:

49
PYTHON PROGRAMMING III-BSC[CS]

 First, (price > 5 and price < 10) evaluates to True.


 Second, not True evaluates to False.

This leads to an important concept called precedence of logical operators.

Precedence of Logical Operators

When you mix the logical operators in an expression, Python will evaluate them in the order
which is called the operator precedence.

The following shows the precedence of the not, and, and or operators:

Operator Precedence
Not High
And Medium
Or Low

Based on these precedences, Python will group the operands for the operator with the highest
precedence first, then group the operands for the operator with the lower precedence, and so
on.In case an expression has several logical operators with the same precedence, Python will
evaluate them from the left to right:

a or b and c means a or (b and c)

a and b or c and d means (a and b) or (c and d)

a and b and c or d means ((a and b) and c) or d

not a and b or c means ((not a) and b) or c

Explain the simple Python if statement(5 marks)

 We use the if statement to execute a block of code based on a specified condition.

The syntax of the if statement is as follows:

if condition:
if-blockCode language: Python (python)

The if statement checks the condition first.

If the condition evaluates to True, it executes the statements in the if-block. Otherwise, it ignores
50
PYTHON PROGRAMMING III-BSC[CS]
the statements.

Note that the colon (:) that follows the condition is very important. If you forget it, you’ll get a
syntax error.

The following flowchart illustrates the if statement:

For example:

age = input('Enter your age:')


if int(age) >= 18:
print("You're eligible to vote.")Code language: Python (python)

This example prompts you to input your age.

If you enter a number that is greater than or equal to 18, it’ll show a message "You're
eligible to vote" on the screen. Otherwise, it does nothing.

The condition int(age) >= 18 converts the input string to an integer and compares it with 18.

Enter your age:18


You're eligible to vote.Code language: Python (python)

See the following example:

age = input('Enter your age:')


if int(age) >= 18:
print("You're eligible to vote.")
print("Let's go and vote.")Code language: Python (python)

51
PYTHON PROGRAMMING III-BSC[CS]
In this example, if you enter a number that is greater than or equal to 18,
In this example, indentation is very important. Any statement that follows the if statement needs
to have four spaces.

If you don’t use the indentation correctly, the program will work differently. For example:

age = input('Enter your age:')


if int(age) >= 18:
print("You're eligible to vote.")
print("Let's go and vote.")
Code language: Python (python)

In this example, the final statement always executes regardless of the condition in the if
statement. The reason is that it doesn’t belong to the if block:

Enter your age:11


Let's go and vote.Code language: Python (python)

Explain the Python if…else statement (5 marks)


We, want to perform an action when a condition is True and another action when the condition is
False.To do so, you use the if...else statement.The following shows the syntax of the

if...else statement:

if condition:
if-block;
else:
else-block;Code language: Python (python)

In this syntax, the if...else will execute the if-block if the condition evaluates to True.
Otherwise, it’ll execute the else-block.

The following flowchart illustrates the if..else statement:

52
PYTHON PROGRAMMING III-BSC[CS]

The following example illustrates you how to use the if...else statement:

age = input('Enter your age:')


if int(age) >= 18:
print("You're eligible to vote.")
else:
print("You're not eligible to vote.")Code language: Python (python)

In this example, if you enter your age with a number less than 18, you’ll see the message
"You're not eligible to vote." like this:

Enter your age:11


You're not eligible to vote.Code language: Python (python)

Explain the Python if…elif…else statement(5 marks)

If you want to check multiple conditions and perform an action accordingly, you can use the
if...elif...else statement. The elif stands for else if.

Here is the syntax if the if...elif...else statement:

if if-condition:
if-block
elif elif-condition1:
elif-block1
elif elif-condition2:
elif-block2
...
else:
else-blockCode language: Python (python)

The if...elif...else statement checks each condition (if-condition, elif-condition1,


elif-condition2, …) in the order that they appear in the statement until it finds the one that

evaluates to True.

When the if...elif...else statement finds one, it executes the statement that follows the
condition and skips testing the remaining conditions.

If no condition evaluates to True, the if...elif...else statement executes the statement in the
else branch.

Note that the else block is optional. If you omit it and no condition is True, the statement does
nothing.
53
PYTHON PROGRAMMING III-BSC[CS]

The following flowchart illustrates the if...elif...else statement:

The following example uses the if...elif..else statement to determine the ticket price based
on the age:

age = input('Enter your age:')

# convert the string to int


your_age = int(age)

# determine the ticket price


if your_age < 5:
ticket_price = 5
elif your_age < 16:
ticket_price = 10
else:
ticket_price = 18

# show the ticket price


print(f"You'll pay ${ticket_price} for the ticket")
Code language: Python (python)

In this example:

 If the input age is less than 5, the ticket price will be $5.
 If the input age is greater than or equal to 5 and less than 16, the ticket price is $10.
 Otherwise, the ticket price is $18.

Note :

 Use the if statement when you want to run a code block based on a condition.
54
PYTHON PROGRAMMING III-BSC[CS]
 Use the if...else statement when you want to run another code block if the condition is
not True.
 Use the if...elif...else statement when you want to check multiple conditions and
run the corresponding code block that follows the condition that evaluates to True.

Explain Python in Ternary Operator(5 marks)


Defintion:

Ternary operator is an operator that takes three arguments (or operands). The arguments and
result can be of different types. Many programming languages that use C-like syntax feature
a ternary operator, ?: , which defines a conditional expression.

Syntax:
[on_true] if [expression] else [on_false]

Simple Method to Use Ternary Operator


In this example, we are comparing and finding the minimum number by using the ternary
operator. The expression min is used to print a or b based on the given condition. For example, if
a is less than b then the output is a, if a is not less than b then the output is b.

# Program to demonstrate conditional operator


a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)
Output
10

Ternary Operator Examples

Here we will see the different example to use Python Ternary Operator:

 Ternary Operator in Python If-Else


 Python Ternary Operator using Tuples
 Python Ternary Operator using Dictionary
 Python Ternary Operator using Lambda
 Print in if Ternary Operator
 Limitations of Python Ternary Operator
 Ternary Operator in Python If-Else
 Example: Using Native way
55
PYTHON PROGRAMMING III-BSC[CS]

Python program to demonstrate nested ternary operator. In this example, we have used simple if-
else without using ternary operator.
a, b = 10, 20

if a != b:
if a > b:
print("a is greater than b")
else:
print("b is greater than a")
else:
print("Both a and b are equal")

Output
b is greater than a

Example: Using Ternary Operator

In this example, we are using a nested if-else to demonstrate ternary operator. If a and b are equal
then we will print a and b are equal and else if a>b then we will print a is greater than b
otherwise b is greater than a.
# Python program to demonstrate nested ternary operator
a, b = 10, 20

print ("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")

b is greater than a

Python Ternary Operator using Tuples

In this example, we are using tuples to demonstrate ternary operator. We are using tuple for
selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is
false it return 0, so element with 0 index will print.

# Python program to demonstrate ternary operator

a, b = 10, 20

print( (b, a) [a < b] )

Output:
10

56
PYTHON PROGRAMMING III-BSC[CS]
Python Ternary Operator using Dictionary

In this example, we are using Dictionary to demonstrate ternary operator. We are using tuple for
selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is
false it return 0, so element with 0 index will print.
# Python program to demonstrate ternary operator
a, b = 10, 20
print({True: a, False: b} [a < b])

10

Python Ternary Operator using Lambda

In this example, we are using Lambda to demonstrate ternary operator. We are using tuple for
selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is
false it return 0, so element with 0 index will print.

a, b = 10, 20
print((lambda: b, lambda: a)[a < b]())

Output
10

Print in if Ternary Operator

In this example, we are finding the larger number among two numbers using ternary operator in
python3.
a=5

b=7

# [statement_on_True] if [condition] else [statement_on_false]


print(a,"is greater") if (a>b) else print(b,"is Greater")

Output

7 is Greater

What are the Limitations of Python Ternary Operator(5 MARKS)

57
PYTHON PROGRAMMING III-BSC[CS]
 Python ternary is used to write concise conditional statements but it too have some
limitations.
 Readability: Ternary operator can make simple conditional expressions more concise, it
can also reduce the readability of your code, especially if the condition and the
expressions are complex.
 Potential for Error: Incorrect placement of parentheses, missing colons, or incorrect order
of expressions can lead to syntax errors that might be harder to spot.
 Debugging: When debugging, it might be harder to inspect the values of variables
involved in a complex ternary expression.
 Maintenance and Extensibility: Complex ternary expressions might become harder to
maintain and extend especially when the codebase grows.
 Can’t use assignment statements: Each operand of the Python ternary operator is an
expression, not a statement, that means we can’t use assignment statements inside any of
them. Otherwise, the program will throw an error.

Example:
3 if True else x=6
Output:
File "Solution.py", line 1
3 if True else x=6
^

SyntaxError: can't assign to conditional expression

The following program prompts you for your age and determines the ticket price based on it:

age = input('Enter your age:')


if int(age) >= 18:
ticket_price = 20
else:
ticket_price = 5

print(f"The ticket price is {ticket_price}")Code language: Python (python)

Here is the output when you enter 18:

Enter your age:18


The ticket price is $20Code language: Python (python)

In this example, the following if...else statement assigns 20 to the ticket_price if the age is
greater than or equal to 18. Otherwise, it assigns the ticket_price 5:

58
PYTHON PROGRAMMING III-BSC[CS]
if int(age) >= 18:
ticket_price = 20
else:
ticket_price = 5Code language: Python (python)

Describe the Numeric type Functions or Explain the concept of numberic type
functions(5 marks)

Numeric type functions typically refer to functions that operate on numeric data types,
such as integers and floating-point numbers.
These functions are commonly used in programming languages to perform mathematical
operations, conversions, and manipulations on numerical values.

The specific functions available may vary depending on the programming language, but
here are some common examples:

1. Mathematical Operations:

• Addition: a + b
• Subtraction: a - b
• Multiplication: a * b
• Division: a / b
• Modulus (remainder): a % b
• Exponentiation: a ** b or pow(a, b) (language-dependent)

2. Comparison Operations:

• Equal to: a == b
• Not equal to: a != b
• Greater than: a > b
• Less than: a < b
• Greater than or equal to: a >= b
• Less than or equal to: a <= b

3. Absolute Value:

• abs(x): Returns the absolute value of x.

4. Rounding:

59
PYTHON PROGRAMMING III-BSC[CS]
• round(x): Rounds x to the nearest integer.
• ceil(x): Rounds x up to the nearest integer.
• floor(x): Rounds x down to the nearest integer.

5. Conversion Functions:

• int(x): Converts x to an integer.


• float(x): Converts x to a floating-point number.

6. Trigonometric Functions (for angles in radians):

• sin(x), cos(x), tan(x): Sine, cosine, and tangent of x.

7. Logarithmic Functions:

• log(x): Natural logarithm of x.


• log10(x): Base-10 logarithm of x.

8. Random Number Generation:

• Language-dependent functions for generating random numbers.

9. Statistical Functions:

• Language-dependent functions for statistical calculations (mean, median, standard


deviation, etc.).

These are general examples, and the availability of these functions and their syntax may vary
between programming languages.

Always refer to the documentation of the specific programming language you are using for
accurate information.

STRINGS:
 In Python, a string is a sequence of characters. It is one of the built-in data types and is
used to represent text. Strings in Python are immutable, meaning that once a string is
created, it cannot be changed.
 Here are some basic operations and concepts related to strings in Python:
Creating Strings:
We can create a string by enclosing characters in either single quotes (') or double quotes ("). For
example:
Ex:
single_quoted_string = 'Hello, World!'
double_quoted_string = "Hello, World!"
String Concatenation:
We can concatenate (combine) strings using the + operator:
60
PYTHON PROGRAMMING III-BSC[CS]
str1 = "Hello"
str2 = "World"

result = str1 + ", " + str2


print(result)
This will output: Hello, World

String Indexing and Slicing:


Strings can be indexed and sliced. Indexing starts from 0, and you can use negative indices to
count from the end. Slicing allows you to extract a portion of a string:

my_string = "Python"

print(my_string[0]) # Output: 'P'

print(my_string[1:4]) # Output: 'yth'

String Methods:

Python provides a variety of built-in methods for working with strings. Some common methods
include len(), upper(), lower(), strip(), split(), replace(), and more:
my_string = " Hello, World! "

print(len(my_string)) # Output: 18

print(my_string.upper()) # Output: " HELLO, WORLD! "

print(my_string.strip()) # Output: "Hello, World!"

String Formatting:

You can format strings using the % operator or using the format() method. In Python 3.6 and
later, you can also use f-strings for string formatting:
name = "Alice"

age = 25

print("My name is %s and I am %d years old." % (name, age))

# Using format() method

61
PYTHON PROGRAMMING III-BSC[CS]
print("My name is {} and I am {} years old.".format(name, age))

# Using f-strings (Python 3.6+)

print(f"My name is {name} and I am {age} years old.")

Escape Characters:

You can use escape characters to include special characters in a string, such as newline (\n), tab
(\t), or a backslash (\\).

print("This is a line.\nThis is a new line.")

These are some fundamental aspects of working with strings in Python. Python's string handling
capabilities are extensive, and there are many more advanced features and methods available for
manipulating and formatting strings.

LIST IN PYTHONS
In Python, a list is a versatile and widely used data structure that allows you to store and
manipulate a collection of items. Lists are ordered, mutable (can be changed), and can contain
elements of different data types. Here's an overview of lists in Python:
Creating Lists:

 You can create a list by enclosing elements in square brackets []:

my_list = [1, 2, 3, "apple", "banana", True]

Accessing Elements:

 Elements in a list are accessed using indexing. Indexing starts from 0, and you can also
use negative indices to count from the end:
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: "apple"
print(my_list[-1]) # Output: True

Slicing:

 You can extract a portion of a list using slicing:

subset = my_list[1:4] # Output: [2, 3, "apple"]

62
PYTHON PROGRAMMING III-BSC[CS]
Modifying Lists:

Lists are mutable, meaning you can change their elements:

my_list[0] = 100

my_list.append("orange") # Adds "orange" to the end

my_list.extend([4, 5, 6]) # Extends the list with another list

my_list.insert(2, "pear") # Inserts "pear" at index 2

Removing Elements:

my_list.remove("banana") # Removes the first occurrence of "banana"

popped_item = my_list.pop(2) # Removes and returns the element at index 2

del my_list[1] # Removes the element at index 1

List Operations:

len(my_list) # Returns the number of elements in the list

"apple" in my_list # Returns True if "apple" is in the list, False otherwise


List Concatenation:

 You can concatenate lists using the + operator:


list1 = [1, 2, 3]
list2 = [4, 5, 6]

result = list1 + list2 # Output: [1, 2, 3, 4, 5, 6]

List Comprehensions:

 List comprehensions provide a concise way to create lists:

squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]

Nested Lists:

Lists can contain other lists:

63
PYTHON PROGRAMMING III-BSC[CS]
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(nested_list[1][2]) # Accessing an element inside a nested list

Lists are a fundamental and powerful data structure in Python, and understanding how to work
with them is essential for effective programming.

Tuples In Python

 In Python, a tuple is a collection of ordered and immutable elements. Tuples are similar
to lists, but the key difference is that once a tuple is created, you cannot modify its
elements - it is immutable. Tuples are defined using parentheses ().

Creating Tuples:

 You can create a tuple by enclosing elements in parentheses:

my_tuple = (1, 2, 3, "apple", "banana")

Accessing Elements:

Elements in a tuple are accessed using indexing, similar to lists:

print(my_tuple[0]) # Output: 1

print(my_tuple[3]) # Output: "apple"

Immutable Nature:

Unlike lists, tuples cannot be modified once they are created. The following code will raise an
error:

my_tuple[0] = 100 # This will raise an error

Tuple Unpacking:

You can use tuple unpacking to assign values from a tuple to variables:

a, b, c = my_tuple[:3]

print(a, b, c) # Output: 1 2 3
64
PYTHON PROGRAMMING III-BSC[CS]

Tuple Concatenation:

Tuples can be concatenated using the + operator:

tuple1 = (1, 2, 3)

tuple2 = ("apple", "banana")

result = tuple1 + tuple2 # Output: (1, 2, 3, "apple", "banana")

Tuple Methods:
Tuples have limited methods compared to lists due to their immutability. Some common
methods include count() and index():

my_tuple.count("apple") # Returns the number of occurrences of "apple"

my_tuple.index(3) # Returns the index of the first occurrence of 3

Use Cases:

Tuples are often used in situations where the data should not be changed, such as representing
coordinates, RGB color values, or elements of a mathematical vector.
coordinates = (3, 4)

rgb_color = (255, 0, 0)

vector = (1, 2, 3)

When to Use Tuples vs Lists:

Use tuples when the data should not be modified.

Use lists when you need a collection that can be modified, such as adding or removing elements.

Understanding when to use tuples or lists depends on the specific requirements of your program
or application. Tuples are generally preferred for read-only data or fixed collections.

65
PYTHON PROGRAMMING III-BSC[CS]

Introduction to Python string


How to declare a string in various method used in python ?(5 marks)

 A string is a series of characters. In Python, anything inside quotes is a string. And you
can use either single or double quotes. For example:
message = 'This is a string in Python'
message = "This is also a string"Code language: Python (python)

 If a string contains a single quote, you should place it in double-quotes like this:

message = "It's a string"Code language: Python (python)

 And when a string contains double quotes, you can use the single quotes:

message = '"Beautiful is better than ugly.". Said Tim Peters'Code language: Python

(python)

 To escape the quotes, you use the backslash (\). For example:

message = 'It\'s also a valid string'Code language: Python (python)

The Python interpreter will treat the backslash character (\) special. If you don’t want it to do so,
you can use raw strings by adding the letter r before the first quote. For example:

message = r'C:\python\bin'Code language: Python (python)

Creating multiline strings

To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’. For example:

help_message = '''
Usage: mysql command
-h hostname
-d database name
-u username
-p password
'''

print(help_message)Code language: Python (python)

It’ll output the following if you execute the program:

Usage: mysql command


-h hostname
-d database name
-u username
66
PYTHON PROGRAMMING III-BSC[CS]
-p passwordCode language: Python (python)

Using variables in Python strings with the f-strings


Sometimes, you want to use the values of variables in a string.

For example, you may want to use the value of the name variable inside the message string
variable:

name = 'John'
message = 'Hi'Code language: Python (python)

To do it, you place the letter f before the opening quotation mark and put the brace around the
variable name:

name = 'John'
message = f'Hi {name}'
print(message)Code language: Python (python)

Python will replace the {name} by the value of the name variable. The code will show the
following on the screen:

Hi JohnCode language: Python (python)

The message is a format string, or f-string in short. Python introduced the f-string in version 3.6.

Concatenating Python strings

When you place the string literals next to each other, Python automatically concatenates them
into one string. For example:

greeting = 'Good ' 'Morning!'


print(greeting)Code language: Python (python)

Output:

Good Morning!Code language: Python (python)

To concatenate two string variables, you use the operator +:

67
PYTHON PROGRAMMING III-BSC[CS]
greeting = 'Good '
time = 'Afternoon'

greeting = greeting + time + '!'


print(greeting)Code language: Python (python)

Output:

Good Afternoon!Code language: Python (python)

Accessing string elements

Since a string is a sequence of characters, you can access its elements using an index. The first
character in the string has an index of zero.

The following example shows how to access elements using an index:

str = "Python String"


print(str[0]) # P
print(str[1]) # yCode language: Python (python)

How it works:

 First, create a variable that holds a string "Python String".


 Then, access the first and second characters of the string by using the square brackets []
and indexes.

If you use a negative index, Python returns the character starting from the end of the string. For
example:

str = "Python String"


print(str[-1]) # g
print(str[-2]) # nCode language: Python (python)

The following illustrates the indexes of the string "Python String":

+---+---+---+---+---+---+---+---+---+---+---+---+---+
| P | y | t | h | o | n | | S | t | r | i | n | g |
+---+---+---+---+---+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Code language: Python (python)

Getting the length of a string

68
PYTHON PROGRAMMING III-BSC[CS]
To get the length of a string, you use the len() function. For example:

str = "Python String"


str_len = len(str)
print(str_len)Code language: Python (python)

Output:

13Code language: Python (python)

Slicing strings

Slicing allows you to get a substring from a string. For example:

str = "Python String"


print(str[0:2])Code language: Python (python)

Output:

PyCode language: Python (python)

The str[0:2] returns a substring that includes the character from the index 0 (included) to 2
(excluded).

The syntax for slicing is as follows:

string[start:end]Code language: Python (python)

The substring always includes the character at the start and excludes the string at the end.

The start and end are optional. If you omit the start, it defaults to zero. If you omit the end, it
defaults to the string’s length.

Python strings are immutable


Python strings are immutable. It means that you cannot change the string. For example, you’ll
get an error if you update one or more characters in a string:

str = "Python String"


str[0] = 'J' Code language: Python (python)

When want to modify a string, you need to create a new one from the existing string. For
example:

str = "Python String"

69
PYTHON PROGRAMMING III-BSC[CS]
new_str = 'J' + str[1:]
print(new_str)Code language: Python (python)

Output:

Python String

Strings operator in python

 In Python, strings support various operators and operations. Here are some commonly
used string operators in Python:

Concatenation (+):
 You can concatenate two strings using the + operator:

str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2
print(result)
# Output: Hello, World

Repetition (*):

 You can repeat a string using the * operator:

str3 = "abc"
result = str3 * 3
print(result)
# Output: abcabcabc

Membership (in and not in):

 You can check if a substring is present in a string using the in and not in operators:
text = "Python is powerful"
print("Python" in text) # Output: True
print("Java" not in text) # Output: True

Comparison (<, <=, >, >=, ==, !=):


70
PYTHON PROGRAMMING III-BSC[CS]

Strings can be compared lexicographically:

str1 = "apple"
str2 = "banana"
print(str1 < str2) # Output: True
print(str1 == str2) # Output: False
Slice ([:]):

You can use slicing to extract a portion of a string:


text = "Hello, World!"
substring = text[7:12]
print(substring)
# Output: World
Length (len()):

 You can use the len() function to get the length of a string:
text = "Python"
length = len(text)
print(length)
# Output: 6

String Formatting:

String formatting allows you to create dynamic strings with placeholders:


name = "Alice"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

Escape Characters:

Escape characters are used to include special characters in a string:

escaped_string = "This is a line.\nThis is a new line."


print(escaped_string)
# Output:
# This is a line.
# This is a new line.
These operators and operations make it convenient to work with strings in Python, providing
71
PYTHON PROGRAMMING III-BSC[CS]
flexibility and ease of manipulation for various tasks.

Explain the concept of string built in methods (10 marks)


Definition
 Python provides a variety of built-in methods for working with strings.
 A string is a series of characters. In Python, anything inside quotes is a string. And you
can use either single or double quotes Here are some commonly used string methods:

1. len()

 Returns the length of a string.


text = "Hello, World!"
length = len(text)
print(length)
# Output: 13

2. str()

 Converts a value into a string.


number = 42
string_number = str(number)
print(string_number)
# Output: "42"

3. lower()

 Converts all characters in a string to lowercase.


text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text)
# Output: "hello, world!"

4. upper()
 Converts all characters in a string to uppercase.
text = "Hello, World!"
uppercase_text = text.upper()
print(uppercase_text)
# Output: "HELLO, WORLD!"
5. capitalize()

 Capitalizes the first character of a string.


text = "hello, world!"
capitalized_text = text.capitalize()
print(capitalized_text)
# Output: "Hello, world!"

72
PYTHON PROGRAMMING III-BSC[CS]

6. title()

 Converts the first character of each word to uppercase.


text = "hello world"
title_text = text.title()
print(title_text)
# Output: "Hello World"

7. strip(), lstrip(), rstrip()


 Remove whitespace characters from the beginning and/or end of a string.
text = " Hello, World! "
stripped_text = text.strip()
print(stripped_text)
# Output: "Hello, World!"

8. replace()

Replaces a specified substring with another substring.


text = "Hello, World!"
new_text = text.replace("Hello", "Hi")
print(new_text)
# Output: "Hi, World!"

9. find(), index()

Find the index of a substring in a string.


text = "Hello, World!"
index = text.find("World")
print(index)
# Output: 7

# Note: If substring is not found, find() returns -1, while index() raises a ValueError.

10. count()

Counts the occurrences of a substring in a string.


text = "apple, banana, cherry, apple"
count = text.count("apple")
print(count)
# Output: 2

String methods are powerful tools for manipulating and working with text data efficiently.

73
PYTHON PROGRAMMING III-BSC[CS]
QUESTION BANK

1. How to declare a numbers in python language ?(5 marks)


2. Explain the Python logical operators with give examples(5 marks)
3. Explain the simple Python if statement(5 marks)
4. Explain the Python if…else statement (5 marks)
5. Explain the Python if…elif…else statement(5 marks)
6. Explain Python in Ternary Operator(5 marks)
7. What are the Limitations of Python Ternary Operator(5 MARKS)
8. Describe the Numeric type Functions or Explain the concept of numberic type
functions(5 marks)
9. Explain the operators in python (10 marks)

ONE MARK

CHOOSE THE CORRECT ANSWER

1) What is the maximum possible length of an identifier?


a.16 b.32 c.64 d.None of these above
Answer: (d) None of these above

2) Who developed the Python language?


A) Zim Den b)Guido van Rossum
C)Niene Stom D)Wick van Rossum
Answer: (b) Guido van Rossum

3) In which year was the Python language developed?


a)1995 b)1972 c)1981 d)1989 Answer: (d) 1989

4) In which language is Python written?


A.English b.PHP c.C d.All of the above Answer: (b) C

5. Which one of the following is the correct extension of the Python file?
A..py b..python c..p d.None of these Answer: (a) .py
6. In which year was the Python 3.0 version developed?
a.2008 b.2000 c.2010 d.2005 Answer: (a) 2008

7) What do we use to define a block of code in Python language?


A.Key b.Brackets c.Indentation d.None of these Answer: (c) Indentation

8) Which character is used in Python to make a single line comment?


a. / b.// c.# d.! Answer: (c) #

9) Which of the following statements is correct regarding the object-oriented programming


concept in Python?

74
PYTHON PROGRAMMING III-BSC[CS]

a.Classes are real-world entities while objects are not real

b.Objects are real-world entities while classes are not realc.

c.Both objects and classes are real-world entities d.All of the above

Answer: (b) Objects are real-world entities while classes are not real

11) What is the method inside the class in python language?


a.Object b.Function c.Attribute d.Argument Answer: (b) Function

12) Which of the following declarations is incorrect?


a. _x = 2 b. x = 3 c. xyz = 5 d.None of these

Answer: (d) None of these

13) Why does the name of local variables start with an underscore discouraged?
A. To identify the variable B. It confuses the interpreter
C. It indicates a private variable of a class D. None of these
Answer: (c) It indicates a private variable of a class

14) Which of the following is not a keyword in Python language?


a. val B.raise C.try D.with Answer: (a) val

18) Which of the following operators is the correct option for power(ab)?
a. a^b B.a**b C.a ^ ^ b D.a ^ * b Answer: (b) a**b

19.Which one of the following has the highest precedence in the expression?

a. Division B.Subtraction C.Power D.Parentheses

Answer: (d) Parentheses

20.Which of the following functions is a built-in function in python language?

a. val() B.print() C.Print() D.None of these Answer: (b) print()

21) Study the following function:

round(4.576) What will be the output of this function?

75
PYTHON PROGRAMMING III-BSC[CS]
a.4 b.5 c576 d.5 Answer: (d) 5

22). Python is a object-oriented programming language.

A. Special purpose C. General purpose


B. Medium level programming language D. All of the mentioned above

Answer: C) General purpose

23. Amongst the following, who is the developer of Python programming?

A. Guido van Rossum B. Denis Ritchie


B. Y.C. Khenderakar D. None of the mentioned above
Answer: A) Guido van Rossu

24Amongst which of the following is / are the application areas of Python programming?

A. Web Development C. Game Development


B. Artificial Intelligence and Machine Learning D. All of the mentioned above

Answer: D) All of the mentioned above

25. Amongst which of the following is / are the Numeric Types of Data Types?

A. int B. float C. complex d.All

Answer: D) All

26. list, tuple, and range are the of Data Types.

A. Sequence Types C. Binary Types


B. Boolean Types D. None of the mentioned above

Answer: A) Sequence Types

27.Float type of data type is represented by the float class.

A. True B. False Answer: A) True

28.bytes, bytearray, memoryview are type of the data type.

A. Mapping Type B. Boolean Type


76
PYTHON PROGRAMMING III-BSC[CS]
B. Binary Types D. None of the mentioned above

Answer: C) Binary Types

29.The type() function can be used to get the data type of any object.

A. True B. False Answer: A) True

30. Binary data type is a fixed-width string of length bytes?


A. True B. False Answer: A) True

31.Varbinary data type returns variable-width string up to a length of max-length bytes?

A. TRUE B. FALSE Answer: A) TRUE

32. Amongst which of the following is / are the logical operators in Python?

A. and B.or C. not D.All of the mentioned above

Answer: D) All of the mentioned above

33. Is Python supports exception handling?

A. Yes B. No Answer: A) Yes

34.What is the name of the operator ** in Python?

A. Exponentiation C. Modulus
B. Floor division D. None of the mentioned above

Answer: A) Exponentiation

35.The % operator returns the .

A. Quotient B. Divisor
B. Remainder D. None of the mentioned above

Answer: C) Remainder

36.Amongst which of the following is / are the method of list?

A. append() C.extend()
77
PYTHON PROGRAMMING III-BSC[CS]
B. insert() D.All of the mentioned above

Answer: D) All of the mentioned above

37.The list.pop ([i]) removes the item at the given position in the list?
A. True B.False Answer: A) True

38.The list.index(x[, start[, end]]) is used to .

A. Return zero-based index in the list


B. Raises a ValueError if there is no such item
C. Both A and B
D. None of the mentioned above

Answer: C) Both A and B

39. Python Dictionary is used to store the data in a format.

A. Key value pair b. Group value pair


B. Select value pair c. None of the mentioned above

Answer: A) Key value pair

40.Python Literals is used to define the data that is given in a variable or constant?

A. True b. False Answer: A) True

41.Conditional statements are also known as _ statements.

A. Decision-making b.Array
B. List d.None of the mentioned above

Answer: A) Decision-making

42.The if statement is the most fundamental decision-making statement?

A. True b. False Answer: A) True

43.In Python, defines a block of statements.

A. Block b. Loop
B. Indentation d. None of the mentioned above

78
PYTHON PROGRAMMING III-BSC[CS]
Answer: C) Indentation

44.An statement has less number of conditional checks than two successive ifs.

A. if else if b.if elif c.if-else d.None Answer: C) if-else

45.In Python, the break and continue statements, together are called statement.

A. Jump b. goto c.compound d.None Answer: B) goto

46.The elif statement allows us to check multiple expressions.

A. True b. False Answer: A) True

47.If a condition is true the not operator is used to reverse the logical state?

A. True b. False Answer: A) True

48.Loops are known as in programming.

A. Control flow statements b. Conditional statements


B. Data structure statements d. None of the mentioned above

Answer: A) Control flow statements

49. The for loop in Python is used to over a sequence or other iterable objects.

A. Jump b. Iterate c. Switch d.All of the mentioned above

Answer: B) Iterate

50.With the break statement we can stop the loop before it has looped through all the
items?

A. True b. False Answer: A) True

79
PYTHON PROGRAMMING III-BSC[CS]

UNIT-3
Explain the Python Mapping Types operators with given examples?(5 marks)
Mapping Types

 A mapping object maps values of one type (the key type) to arbitrary objects. Mappings
are mutable objects.

what is the dictionary ?

 There is currently only one standard mapping type, the dictionary .


 A dictionary’s keys are almost arbitrary values. The only types of values not acceptable
as keys are values containing lists or dictionaries or other mutable types that are
compared by value rather than by object identity.
 Numeric types used for keys obey the normal rules for numeric comparison: if two
numbers compare equal (e.g., 1 and 1.0) then they can be used interchangeably to index
the same dictionary entry.

Mapping Types operators

 objects are used to map hash table values to arbitrary objects.


 In python there is mapping type called dictionary.
 It is mutable.
 The keys of the dictionary are arbitrary. As the value, we can use different kind of elements
like lists, integers or any other mutable type objects.
 Some dictionary related methods and operations are –
Dictionaries are created by placing a comma-separated list of key: value pairs with in
braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}.

The operations in the following table are defined on mappings (where a is a mapping, k is a key
and x is an arbitrary object).

Operation Result Notes

len(a) The number of items in a

a[k] The item of a with key k 1

80
PYTHON PROGRAMMING III-BSC[CS]
a[k] = x Set a[k] to x

del a[k] Remove a[k] from a (1)

a.clear() Remove all items from a

a.copy() A (shallow) copy of a

Operation Result Notes

a.has_key(k) 1 if a has a key k, else 0

a.items() A copy of a’s list of (key, value) pairs 2

a.keys() A copy of a’s list of keys 2

a.update(b) For k, v in b.items(): a[k] = v 3

a.values() A copy of a’s list of values 2

a.get(k[, f]) The value of a with key k 4

Method len(d)

The len() method returns the number of elements in the dictionary.

Operation d[k]

It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped.

Method iter(d)

This method will return an iterator over the keys of dictionary. We can also perform this taks by
using iter(d.keys()).

Method get(key[, default])

The get() method will return the value from the key. The second argument is optional. If the key
81
PYTHON PROGRAMMING III-BSC[CS]
is not present, it will return the default value.

Method items()

It will return the items using (key, value) pairs format.


Method keys()

Return the list of different keys in the dictionary.

Method values()

Return the list of different values from the dictionary.

Method update(elem)

Modify the element elem in the dictionary.

Example Code

Live Demo

myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40}


print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))

#create items from the key-value pairs


print(list(myDict.items()))

myDict.update({'fifty' : 50})
print(myDict)

Output

{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}


['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}

So finally, A dictionary maps keys to values. Keys need to be hash able objects, while values can
82
PYTHON PROGRAMMING III-BSC[CS]
be of any arbitrary type. Dictionaries are mutable objects.
Mapping Type Built In And Factory Functions:

Explain the concept of mapping factory functions or describe the types of


mapping types built in factory functions (5 marks)

 In Python, mapping types primarily refer to dictionaries (dict).


 Dictionaries are mutable, unordered collections of key-value pairs, and they allow you to
map keys to values.
 There are different ways to create dictionaries in Python, including using built-in
methods and factory functions. Here's an explanation of both:

Built-in Methods:
Python provides built-in methods for creating and manipulating dictionaries. Some common
built-in methods include:

Literal Syntax:
You can create a dictionary using literal syntax, where you define key-value pairs within curly
braces {}:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict() Constructor:
The dict() constructor can be used to create a dictionary. You can pass key-value pairs as
arguments or provide an iterable of key-value pairs:
my_dict = dict(key1='value1', key2='value2', key3='value3')
fromkeys() Method:
The fromkeys() method creates a new dictionary with specified keys and a default value:
keys = ['key1', 'key2', 'key3']
default_value = 'default'
my_dict = dict.fromkeys(keys, default_value)
Factory Functions:
In addition to built-in methods, there are factory functions provided by the collections module
that allow you to create specialized mapping types. One notable factory function is defaultdict.
defaultdict:
defaultdict is a dictionary subclass that provides a default value for each new key. This can be
useful when you want to avoid key errors.
from collections import defaultdict
# Create a defaultdict with default value as int (default is 0)
my_default_dict = defaultdict(int)

83
PYTHON PROGRAMMING III-BSC[CS]
my_default_dict['key1'] += 1
defaultdict is particularly handy when you are counting occurrences or initializing values in a
dictionary.
These are some ways to create and work with mapping types in Python. Choose the method that
best suits your needs based on the specific requirements of your code.

Explain the Mapping Types Of Built In Methods or Explain the concept of mapping type
built in functions(10marks)

 In Python, mapping types, specifically dictionaries (dict), come with a variety of built-in
methods that allow you to perform operations on them.
 Here's an overview of some common built-in methods for dictionaries:

1. clear():

Removes all items from the dictionary.

my_dict = {'key1': 'value1', 'key2': 'value2'}

my_dict.clear()

2. copy():

Returns a shallow copy of the dictionary.

original_dict = {'key1': 'value1', 'key2': 'value2'}

copy_dict = original_dict.copy()

3. get(key, default=None):
Returns the value for the specified key. If the key is not found, it returns the default value
(default is None if not specified).
my_dict = {'key1': 'value1', 'key2': 'value2'}

value = my_dict.get('key3', 'default_value')

4.items():

Returns a view of the dictionary's key-value pairs as tuples.

my_dict = {'key1': 'value1', 'key2': 'value2'}

84
PYTHON PROGRAMMING III-BSC[CS]
items = my_dict.items()

5. keys():

Returns a view of the dictionary's keys.

my_dict = {'key1': 'value1', 'key2': 'value2'}

keys = my_dict.keys()

6. values():

Returns a view of the dictionary's values.

my_dict = {'key1': 'value1', 'key2': 'value2'}

values = my_dict.values()

7. pop(key, default):

Removes and returns the value for the specified key. If the key is not found, it returns the default
value (or raises a KeyError if default is not provided).
my_dict = {'key1': 'value1', 'key2': 'value2'}

value = my_dict.pop('key1', 'default_value')

8.popitem():

Removes and returns an arbitrary (key, value) pair as a tuple. Raises a KeyError if the dictionary
is empty.
my_dict = {'key1': 'value1', 'key2': 'value2'}

item = my_dict.popitem()

9.update(iterable):

Updates the dictionary with elements from another iterable (e.g., another dictionary or a
sequence of key-value pairs).
my_dict = {'key1': 'value1', 'key2': 'value2'}

my_dict.update({'key3': 'value3', 'key4': 'value4'})

85
PYTHON PROGRAMMING III-BSC[CS]

10. setdefault(key, default):

Returns the value for the specified key. If the key is not found, inserts the key with the specified
default value.
my_dict = {'key1': 'value1', 'key2': 'value2'}

value = my_dict.setdefault('key3', 'default_value')

11. del statement:

Deletes the key-value pair with the specified key.

my_dict = {'key1': 'value1', 'key2': 'value2'}

del my_dict['key1']

These are just a few examples of the built-in methods for dictionaries in Python.

conditionals and loops:


Explain the concept of conditional statementrs with given
examples(5 marks)(or)Explain the if,else and elif statements with
given examples(10 marks)

In Python, conditional loops are created using if, elif (else if), and else statements to control the

86
PYTHON PROGRAMMING III-BSC[CS]
flow of the program based on certain conditions. Additionally, loops like or can be
while for
used in conjunction with conditional statements to create more complex control structures.

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

 these conditions can be used in several ways, most commonly in "if statements" and
loops.

 An "if statement" is written by using the if keyword.

Examples:

a = 33
b = 200
if b > a:
print("b is greater than a") o/p: b is greater than a

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example

a = 200

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

else:

print("a is greater than b")

87
PYTHON PROGRAMMING III-BSC[CS]

In this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".
we can also have an else without the elif:

Example

a = 200

b = 33

if b > 2a:

print("b is greater than a")

else:

print("b is not greater than a")

Elif

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
Example

a = 33

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so
we print to screen that "a and b are equal".
Write a note on Short Hand If ... Else(5 marks)
If you have only one statement to execute, one for if, and one for else, you can put it all on the
same line:
Example
88
PYTHON PROGRAMMING III-BSC[CS]

One line if else statement:

a=2

b = 330

print("A") if a > b else print("B")

Here's an example of a simple conditional loop using if, elif, and else statements:

Example 1: Simple conditional loop

x = 10

if x > 0:

print("x is positive")

elif x == 0:

print("x is zero")

else:

print("x is negative")

In this example, the program checks the value of the variable x and prints a message based on
the condition.

89
PYTHON PROGRAMMING III-BSC[CS]

Explain the Python for Loops (10 marks)or Explain the looping
statements(10 marks)
he for loop in Python has the ability to iterate over the items of any sequence, such as a list, tuple
or a string.
Syntax

for iterating_var in sequence:


statements(s)
 If a sequence contains an expression list, it is evaluated first. Then, the first item (at 0th
index) in the sequence is assigned to the iterating variable iterating_var.
 Next, the statements block is executed. Each item in the list is assigned to iterating_var,
and the statement(s) block is executed until the entire sequence is exhausted.
The following flow diagram illustrates the working of for loop –

 Since the loop is executed for each member element in a sequence, there is no need for
explicit verification of Boolean expression controlling the loop (as in while loop).
 The sequence objects such as list, tuple or string are called iterables, as the for loop
iterates through the collection. Any iterator object can be iterated by the for loop.
 The view objects returned by items(), keys() and values() methods of dictionary are also
iterables, hence we can run a for loop with these methods.
 Python's built-in range() function returns an iterator object that streams a sequence of
numbers. We can run a for loop with range as well.

Using "for" with a String

 A string is a sequence of Unicode letters, each having a positional index. The following
example compares each character and displays if it is not a vowel ('a', 'e', 'I', 'o' or 'u')

90
PYTHON PROGRAMMING III-BSC[CS]

Example
zen = '''
Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

'''

for char in zen:

if char not in 'aeiou':

print (char, end='')

Output

On executing, this code will produce the following output −

Using "for" with a Tuple

 Python's tuple object is also an indexed sequence, and hence we can traverse its items
with a for loop.

Example

In the following example, the for loop traverses a tuple containing integers and returns the total
of all numbers.

numbers = (34,54,67,21,78,97,45,44,80,19)

total = 0

for num in numbers:

total+=num

print ("Total =", total) Output

On executing, this code will produce the following output - Total = 539

91
PYTHON PROGRAMMING III-BSC[CS]
Using "for" with a List

Python's list object is also an indexed sequence, and hence we can traverse its items with a for
loop.
Example

In the following example, the for loop traverses a list containing integers and prints only those
which are divisible by 2.
numbers = [34,54,67,21,78,97,45,44,80,19]

total = 0

for num in numbers:

if num%2 == 0:

print (num)

Output

On executing, this code will produce the following output −

34

54

78
44

80

Using "for" with a Range Object

 Python's buil-in range() function returns a range object.


 Python's range object is an iterator which generates an integer with each iteration.
 The object contains integrrs from start to stop, separated by step parameter.

Syntax

The range() function has the following syntax −

range(start, stop, step)

Parameters

Start − Starting value of the range. Optional. Default is 0


92
PYTHON PROGRAMMING III-BSC[CS]

Stop − The range goes upto stop-1

Step − Integers in the range increment by the step value. Option, default is 1.

Return Value

The range() function returns a range object. It can be parsed to a list sequence.

Example

numbers = range(5)

''

start is 0 by default,

step is 1 by default,

range generated from 0 to 4

'''

print (list(numbers))
# step is 1 by default, range generated from 10 to 19

numbers = range(10,20)

print (list(numbers))

# range generated from 1 to 10 increment by step of 2

numbers = range(1, 10, 2)

print (list(numbers))

Output

On executing, this code will produce the following output −

[0, 1, 2, 3, 4]

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[1, 3, 5, 7, 9].

Using "for" Loop with Sequence Index

93
PYTHON PROGRAMMING III-BSC[CS]
 To iterate over a sequence, we can obtain the list of indices using the range() function

Indices = range(len(sequence))

We can then form a for loop as follows:

numbers = [34,54,67,21,78]

indices = range(len(numbers))

for index in indices:

print ("index:",index, "number:",numbers[index])

On executing, this code will produce the following output −

index: 0 number: 34

index: 1 number: 54

index: 2 number: 67
index: 3 number: 21

index: 4 number: 78

Using "for" with Dictionaries

Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do
not have a positional index. However, traversing a dictionary is still possible with different
techniques.
Running a simple for loop over the dictionary object traverses the keys used in it.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}

for x in numbers:

print (x)

On executing, this code will produce the following output −


10
20

30

40

94
PYTHON PROGRAMMING III-BSC[CS]

Python while Loops


Explain the Python while Loops with given examples(10marks)
Normally, flow of execution of steps in a computer program goe from start to end. However,
instead of the next step, if the flow is redirected towards any earlier step, it constitutes a loop.

 A while loop statement in Python programming language repeatedly executes a target


statement as long as a given boolean expression is true.

Syntax

 The syntax of a while loop in Python programming language is −

while expression:
statement(s)

 The while keyword is followed by a boolean expression, and then by colon symbol, to
start an indented block of statements.
 Here, statement(s) may be a single statement or a block of statements with uniform
indent. The condition may be any expression, and true is any non-zero value. The loop
iterates while the boolean expression is true.
 As soon as the expression becomes false, the program control passes to the line
immediately following the loop.
 If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully
stopped. Such a loop is called infinite loop, which is undesired in a computer program

Example
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code.

Python uses indentation as its method of grouping statements.

count=0

while count<5:

count+=1

95
PYTHON PROGRAMMING III-BSC[CS]
print ("Iteration no. {}".format(count))

print ("End of while loop")

We initialize count variable to 0, and the loop runs till "count<5".

In each iteration, count is incremented and checked. If it's not 5 next repetion takes place. Inside
the looping block, instantenous value of count is printed. When the while condition becomes
false, the loop terminates, and next statement is executed, here it is End of while loop message.
Output

On executing, this code will produce the following output −


Iteration no. 1

Iteration no. 2

Iteration no. 3

Iteration no. 4

Iteration no. 5

End of while loop

The following flow diagram illustrates the while loop −

The Infinite Loop

 A loop becomes infinite loop if a condition never becomes FALSE.


 we must be cautious when using while loops because of the possibility that this condition
never resolves to a FALSE value.
 This results in a loop that never ends. Such a loop is called an infinite loop.

96
PYTHON PROGRAMMING III-BSC[CS]
 An infinite loop might be useful in client/server programming where the server needs to
run continuously so that client programs can communicate with it as and when required.

The while-else Loop

 Python supports having an else statement associated with a while loop statement.
 If the else statement is used with a while loop, the else statement is executed when the
condition becomes false before the control shifts to the main line of execution.
 The following flow diagram shows how to use else with while statement −

Example

The following example illustrates the combination of an else statement with a while statement.
Till the count is less than 5, the iteration count is printed.
As it becomes 5, the print statement in else block is executed, before the control is passed to the
next statement in the main program.
count=0

while count<5:

count+=1

print ("Iteration no. {}".format(count))

else:

print ("While loop over. Now in else block")

print ("End of while loop")

Python break Statement


Explain the concept of Python break Statement(5 marks)
 It terminates the current loop and resumes execution at the next statement, just like the

97
PYTHON PROGRAMMING III-BSC[CS]
traditional break statement in C.
 The most common use for break is when some external condition is triggered requiring a
hasty exit from a loop. The break statement can be used in both while and for loops.
 If you are using nested loops, the break statement stops the execution of the innermost
loop and start executing the next line of code after the block.
Syntax

The syntax for a break statement in Python is as follows −

break

Example

for letter in 'Python': # First Example

if letter == 'h':

break

print ('Current Letter :', letter)

var = 10 # Second Example

while var > 0:

print ('Current variable value :', var)

var = var -1

if var == 5:

break

print ("Good bye!")

When the above code is executed, it produces the following result −

Current Letter : P

Current Letter : y

Current Letter : t

98
PYTHON PROGRAMMING III-BSC[CS]
Current variable value : 10

Current variable value : 9

Current variable value : 8

Current variable value : 7

Current variable value : 6

Good bye!

Python Continue Statement


Explain the concept of Python Continue Statement(5 marks )
 The continue statement in Python returns the control to the beginning of the current loop.
When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.
 The continue statement can be used in both while and for loops.

Syntax

continue

Flow Diagram

The flow diagram of the continue statement looks like this −

The continue statement is just the opposite to that of break. It skips the remaining statements in
99
PYTHON PROGRAMMING III-BSC[CS]
the current loop and starts the next iteration.
Example

for letter in 'Python': # First Example

if letter == 'h':

continue

print ('Current Letter :', letter)

var = 10 # Second Example

while var > 0:

var = var -1

if var == 5:

continue

print ('Current variable value :', var)

print ("Good bye!")

When the above code is executed, it produces the following output −

Current Letter : P

Current Letter : y

Current Letter : t

Current Letter : o

Current Letter : n

Current variable value : 9

Current variable value : 8

Current variable value : 7

Current variable value : 6

Current variable value : 4

100
PYTHON PROGRAMMING III-BSC[CS]
Current variable value : 3

Current variable value : 2

Current variable value : 1

Current variable value : 0

Good bye!

Python pass Statement


Illustrate the Python pass Statement wityh examples(5 marks)
 The Python pass statement is used when a statement is required syntactically but you do
not want any command or code to execute.
 The Python pass statement is a null operation; nothing happens when it executes.
 The pass statement is also useful in places where your code will eventually go, but has
not been written yet, i.e., in stubs).
Syntax

pass
Example

The following code shows how you can use the pass statement in Python –
for letter in 'Python':

if letter == 'h':

pass

print ('This is pass block')

print ('Current Letter :', letter)

print ("Good bye!")

When the above code is executed, it produces the following output −

Current Letter : P

Current Letter : y

Current Letter : t

101
PYTHON PROGRAMMING III-BSC[CS]
This is pass block

Current Letter : h

Current Letter : o

Current Letter : n

Good bye!

Dummpy Infinite Loop with Pass

This is simple enough to create an infinite loop using pass statement. For instance, if you want to
code an infinite loop that does nothing each time through, do it with a pass:
while True: pass # Type Ctrl-C to stop

Because the body of the loop is just an empty statement, Python gets stuck in this loop. As
explained earlier pass is roughly to statements as None is to objects — an explicit nothing.
Using Ellipses ... as pass Alternative

Python 3.X allows ellipses coded as three consecutive dots ...to be used in place of pass
statement. This ... can serve as an alternative to the pass statement.
For example if we create a function which does not do anything especially for code to be filled in
later, then we can make use of ...
def func1():

... # Alternative to pass

def func2(): ... # Works on same line too

func1() # Does nothing if called

func2() # Does nothing if called

Explain about Iterator And The Iter()Functions(5 marks)


 In Python, an iterator is an object that implements the iterator protocol, which consists of
the iter () and next () methods.
 An iterator is used to represent a stream of data and allows you to traverse the elements
of a sequence, such as a list or a tuple, one at a time.
 Here's a brief explanation of the iterator protocol and the iter() function:

102
PYTHON PROGRAMMING III-BSC[CS]

Iterator Protocol:

1. iter () Method:

This method returns the iterator object itself. It is called when an iterator is created for an object.

2. next () Method:

This method returns the next value from the iterator. If there are no more items to return, it
should raise the StopIteration exception.
Here's a simple example of an iterable and an iterator:

class MyIterator:

def iter (self):

self.current = 1

return self

def next (self):

if self.current <= 5:

result = self.current

self.current += 1

return result

else:

raise StopIteration

my_iterator = MyIterator()

for num in my_iterator:

print(num)

iter() Function:

The iter() function is a built-in function in Python that takes an iterable object and returns an
iterator.
If the object passed to iter() has an iter () method, it returns the result of that method. If the
103
PYTHON PROGRAMMING III-BSC[CS]
object has a getitem () method, iter() creates an iterator that indexes from 0 up to len(object)
- 1.

Example using iter():

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

my_iterator = iter(my_list)

print(next(my_iterator)) # prints 1

print(next(my_iterator)) # prints 2

In many cases, the for loop implicitly uses the iter() function to create an iterator and the
next () method to retrieve the next element until a StopIteration exception is raised.
Understanding iterators and the iterator protocol is crucial for working with Python's for loop
and comprehending how looping constructs operate in the language.

Files And Input Output Objects

Describe the input and output objects (5 marks)


 In Python, input and output operations are commonly performed using files.
 The built-in open() function is used to open a file and create a file object, which is then
used for reading or writing data. Here's an overview of file handling in Python:
Opening a File:

To open a file, you use the open() function. It takes two arguments: the filename and the mode
(read, write, append, etc.).
# Opening a file for reading

file_path = "example.txt"

with open(file_path, "r") as file:

# Perform operations on the file

content = file.read()

print(content)

# File is automatically closed when exiting the 'with' block

Reading from a File:

After opening a file for reading, you can use various methods like read(), readline(), or
104
PYTHON PROGRAMMING III-BSC[CS]
readlines() to read its content.
with open("example.txt", "r") as file:

content = file.read() # Reads the entire file

print(content)

Writing to a File:
To write to a file, you open it in write mode ("w"). Be cautious, as this will overwrite the existing
content of the file.
with open("example.txt", "w") as file:

file.write("Hello, World!\n")

file.write("This is a new line.")

Appending to a File:

To append to a file, open it in append mode ("a"). This will add new content at the end of the
file.
with open("example.txt", "a") as file:

file.write("\nAppending a new line.")

Reading and Writing in Binary Mode:

You can also work with files in binary mode by specifying "rb" (read binary) or "wb" (write
binary).
with open("binary_file.bin", "wb") as binary_file:

binary_file.write(b'\x48\x65\x6c\x6c\x6f') # Writing binary data

with open("binary_file.bin", "rb") as binary_file:

content = binary_file.read() # Reading binary data

print(content)

Using input() for User Input:

The input() function is used to take user input from the console.

user_input = input("Enter something: ")

print("You entered:", user_input)


105
PYTHON PROGRAMMING III-BSC[CS]
These are basic examples of file handling and user input/output in Python. They cover common
scenarios, but file handling can become more complex depending on your specific requirements,
such as working with different file formats or handling exceptions during file operations.

File Built In Functions In Python

Explain the concept of file built in methods(10 marks)


 In Python, there are several built-in functions and methods associated with file handling.
 These functions allow you to perform various operations on files, such as opening,
reading, writing, and closing. Here are some commonly used file-related functions in
Python:
open() Function:

Opens a file and returns a file object.

file = open("example.txt", "r")

read(size) Method:

Reads and returns the specified number of bytes from the file. If no size is specified, it reads the
entire file.
content = file.read(10) # Reads the first 10 characters

readline() Method:

Reads and returns the next line from the file.

line = file.readline()

readlines() Method:

Reads all the lines from the file and returns them as a list of strings.

lines = file.readlines()

write(string) Method:

Writes the specified string to the file.

106
PYTHON PROGRAMMING III-BSC[CS]
file.write("Hello, World!")

writelines(lines) Method:

Writes a list of lines to the file.

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

file.writelines(lines)

close() Method:

Closes the file. It's important to close the file when you're done with it to free up system
resources.
file.close()

flush() Method:

Flushes the internal buffer, ensuring that all data is written to the file.

file.flush()

seek(offset, whence) Method:

Moves the file cursor to the specified position. The whence parameter determines the reference
point for the offset (0 for the beginning, 1 for the current position, 2 for the end).
file.seek(0, 0) # Move to the beginning of the file

tell() Method:

Returns the current position of the file cursor.

position = file.tell()

with Statement:

A context manager that simplifies the process of opening and closing files by automatically
closing the file when exiting the block.
with open("example.txt", "r") as file:

content = file.read()

107
PYTHON PROGRAMMING III-BSC[CS]
These are some of the basic file-related functions and methods in Python. File handling in
Python is versatile, and depending on your requirements, you may need to explore additional
functionalities and consider error handling, especially when dealing with file operations.

File Built In Attributes In Python

Explain the concept of File Built In Attributes In Python(5 marks)


 In Python, file objects have several built-in attributes that provide information about the
file.
 These attributes can be accessed after opening a file using the open() function. Here are
some commonly used file-related attributes:
Name Attribute:Returns the name of the file.

file = open("example.txt", "r")

print(file.name)

mode Attribute:

Returns the access mode with which the file was opened (e.g., "r" for read, "w" for write, "a" for
append).
file = open("example.txt", "r")

print(file.mode)

closed Attribute:

Returns True if the file is closed, and False otherwise.

file = open("example.txt", "r")

print(file.closed) # False

file.close()

print(file.closed) # True

108
PYTHON PROGRAMMING III-BSC[CS]
encoding Attribute:

Returns the encoding used for the file. This attribute is available only if the file was opened with
an encoding parameter.
file = open("example.txt", "r", encoding="utf-8")

print(file.encoding)

buffer Attribute:

Returns the underlying buffer object if the file uses binary mode.

file = open("binary_file.bin", "rb")

print(file.buffer)

errors Attribute:

Returns the Unicode error handling scheme used for decoding and encoding file data. This
attribute is available only if the file was opened with an encoding parameter.
file = open("example.txt", "r", encoding="utf-8", errors="ignore")

print(file.errors)

 These attributes provide information about the file object and its properties.
 Keep in mind that some attributes, such as encoding and errors, are specific to text mode
files.
 When working with binary mode files, these attributes may not be present.
 It's important to note that file attributes are read-only and cannot be modified directly.
 They provide information about the state and properties of the file object.

Python - Files I/O


Explain the concept of files I/O functions (10 marks)

 This concept covers all the basic I/O functions available in Python.

Printing to the Screen


 The simplest way to produce output is using the print statement where you can
pass zero or more expressions separated by commas.
 This function converts the expressions you pass into a string and writes the
result to standard output as follows −

109
PYTHON PROGRAMMING III-BSC[CS]
Live Demo

#!/usr/bin/python

print "Python is really a great language,", "isn't it?"

This produces the following result on your standard screen −

Python is really a great language, isn't it?

Reading Keyboard Input

 Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard.
 These functions are −

 raw_input
 input

The raw_input Function

The raw_input([prompt]) function reads one line from standard input and returns it as
a string (removing the trailing newline).

#!/usr/bin/python

str = raw_input("Enter your input: ")


print "Received input is : ", str

110
PYTHON PROGRAMMING III-BSC[CS]
This prompts you to enter any string and it would display same string on the screen.
When I typed "Hello Python!", its output is like this −

Enter your input: Hello Python


Received input is : Hello Python

The input Function

 The input([prompt]) function is equivalent to raw_input, except that it assumes


the input is a valid Python expression and returns the evaluated result to you.

#!/usr/bin/python

str = input("Enter your input: ")


print "Received input is : ", str

This would produce the following result against the entered input −

Enter your input: [x*5 for x in range(2,10,2)]


Recieved input is : [10, 20, 30, 40]

Opening and Closing Files

 Until now, you have been reading and writing to the standard input and output.
Now, we will see how to use actual data files.
 Python provides basic functions and methods necessary to manipulate files by
default. You can do most of the file manipulation using a file object.

The open Function

Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to call
other support methods associated with it.

111
PYTHON PROGRAMMING III-BSC[CS]
Syntax
file object = open(file_name [, access_mode][, buffering])

Here are parameter details −

 file_name − The file_name argument is a string value that contains the name of
the file that you want to access.
 access_mode − The access_mode determines the mode in which the file has to
be opened, i.e., read, write, append, etc. A complete list of possible values is
given below in the table. This is optional parameter and the default file access
mode is read (r).
 buffering − If the buffering value is set to 0, no buffering takes place. If the
buffering value is 1, line buffering is performed while accessing a file.
 If you specify the buffering value as an integer greater than 1, then buffering
action is performed with the indicated buffer size. If negative, the buffer size is
the system default(default behavior).

Here is a list of the different modes of opening a file −

Sr.No. Modes & Description

r
1 Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.

rb
Opens a file for reading only in binary format. The file pointer is placed at the
2
beginning of the file. This is the default mode.

r+

3 Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.

112
PYTHON PROGRAMMING III-BSC[CS]

rb+
4 Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.

w
Opens a file for writing only. Overwrites the file if the file exists. If the file does
5
not exist, creates a new file for writing.

wb
Opens a file for writing only in binary format. Overwrites the file if the file exists.
6
If the file does not exist, creates a new file for writing.

w+
Opens a file for both writing and reading. Overwrites the existing file if the file
7
exists. If the file does not exist, creates a new file for reading and writing.

wb+
Opens a file for both writing and reading in binary format. Overwrites the existing
8
file if the file exists. If the file does not exist, creates a new file for reading and
writing.

a
Opens a file for appending. The file pointer is at the end of the file if the file
9
exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.

ab
Opens a file for appending in binary format. The file pointer is at the end of the
10
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.

a+
Opens a file for both appending and reading. The file pointer is at the end of the
11
file if the file exists. The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.

113
PYTHON PROGRAMMING III-BSC[CS]

ab+
Opens a file for both appending and reading in binary format. The file pointer is
12
at the end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.

The file Object Attributes

Once a file is opened and you have one file object, you can get various information
related to that file.

Here is a list of all attributes related to file object −

Sr.No. Attribute & Description

1 file.closed
Returns true if file is closed, false otherwise.

file.mode
2 Returns access mode with which file was opened.

file.name
3 Returns name of the file.

file.softspace
4 Returns false if space explicitly required with print, true otherwise.

Example
Live Demo

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

114
PYTHON PROGRAMMING III-BSC[CS]
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace

This produces the following result −

Name of the file: foo.txt


Closed or not : False
Opening mode : wb
Softspace flag : 0

The close() Method

 The close() method of a file object flushes any unwritten information and closes
the file object, after which no more writing can be done.
 Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to
close a file.

Syntax
fileObject.close()

Example
Live Demo

#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()

This produces the following result −

115
PYTHON PROGRAMMING III-BSC[CS]
Name of the file: foo.txt

Reading and Writing Files


The file object provides a set of access methods to make our lives easier. We would
see how to use read() and write() methods to read and write files.

The write() Method


 The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
 The write() method does not add a newline character ('\n') to the end of the
string −

Syntax
fileObject.write(string)

Here, passed parameter is the content to be written into the opened file.

Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Close opend file
fo.close()

The above method would create foo.txt file and would write given content in that file

and finally it would close that file. If you would open this file, it would have
following content.

Python is a great language.


Yeah its great!!

116
PYTHON PROGRAMMING III-BSC[CS]
The read() Method

The read() method reads a string from an open file. It is important to note that Python
strings can have binary data. apart from text data.

Syntax
fileObject.read([count])

Here, passed parameter is the number of bytes to be read from the opened file. This

method starts reading from the beginning of the file and if count is missing, then it

tries to read as much as possible, maybe until the end of file.

Example

Let's take a file foo.txt, which we created above.

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

This produces the following result −

Read String is : Python is

File Positions

 The tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.

117
PYTHON PROGRAMMING III-BSC[CS]
 The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved.
 The from argument specifies the reference position from where the bytes are to be
moved.

Renaming and Deleting Files


 Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files.
 To use this module you need to import it first and then you can call any related
functions.

The rename() Method


The rename() method takes two arguments, the current filename and the new
filename.

Syntax
os.rename(current_file_name, new_file_name)

Example

Following is the example to rename an existing file test1.txt −

#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )

The remove() Method


You can use the remove() method to delete files by supplying the name of the file to
be deleted as the argument.

118
PYTHON PROGRAMMING III-BSC[CS]
Syntax
os.remove(file_name)

Example

Following is the example to delete an existing file test2.txt −


#!/usr/bin/python
import os
# Delete file test2.txt
os.remove("text2.txt")

Directories in Python

 All files are contained within various directories, and Python has no problem
handling these too.
 The os module has several methods that help you create, remove, and change
directories.

The mkdir() Method


 we can use the mkdir() method of the os module to create directories in the
current directory.
 we need to supply an argument to this method which contains the name of the
directory to be created.

Syntax
os.mkdir("newdir")

Example

Following is the example to create a directory test in the current directory −

#!/usr/bin/python
import os

119
PYTHON PROGRAMMING III-BSC[CS]

# Create a directory "test"


os.mkdir("test")

The chdir() Method


We can use the chdir() method to change the current directory.

The chdir() method takes an argument, which is the name of the directory that you
want to make the current directory.

Syntax
os.chdir("newdir")
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")

The getcwd() Method


The getcwd() method displays the current working directory.

Syntax
os.getcwd()
Following is the example to give current directory −
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()

120
PYTHON PROGRAMMING III-BSC[CS]
The rmdir() Method
 The rmdir() method deletes the directory, which is passed as an argument in the
method.
 Before removing a directory, all the contents in it should be removed.

Syntax
os.rmdir('dirname')

Following is the example to remove "/tmp/test" directory. It is required to give fully


qualified name of the directory, otherwise it would search for that directory in the
current directory.

#!/usr/bin/python
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )

File & Directory Related Methods


There are three important sources, which provide a wide range of utility methods to
handle and manipulate files & directories on Windows and Unix operating systems.
They are as follows −

 File Object Methods: The file object provides functions to manipulate files.
 OS Object Methods: This provides methods to process files as well as
directories.

File Handling in Python

121
PYTHON PROGRAMMING III-BSC[CS]

PYTHON PROGRAMMING III-BSC[CS]

Explain the concept of file handling in python (5 marks)

 Apart from the most commonly used file handling functions:


 open()
 read()
 write()
 close()
 readline()

 write()

 writelines()

 tell()

 seek()
 there are a lot more functions that are used for file handling in Python.
Here is a list of some commonly used file-handling functions in Python.

Function Description

open() Used to open a file.

readable() Used to check whether the file can be read or not.

readline() Used to read a single line from the file.

readlines() Used to read all the content in the form of lines.

read() Used to read whole content at a time.

writable() Used to check whether the file is writable or not.

write() Used to write a string to the file.

writelines() Used to write multiple strings at a time.

close() Used to close the file from the program.

122
PYTHON PROGRAMMING III-BSC[CS]

When we want to read from or write to a file we need to open it first. When we are done, it needs to be
closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.

 Open a file

 Read or write (perform operation)

 Close the file

File Built-in Function [open ()]


 Python has a built-in function open() to open a file.
 Which accepts two arguments, file name and access mode in which the file is accessed.
 The function returns a file object which can be used to perform various operations like reading,
writing, etc.
 Syntax:

 Fileobject = open (file-name, access-mode)

 file-name: It specifies the name of the file to be opened.


 access-mode: There are following access modes for opening a file
close()
 The close() method used to close the currently opened file, after which no more writing or
Reading can be done.
 Python automatically closes a file when the reference object of a file is reassigned to another
file. It is a good practice to use the close() method to close a file.
Syntax:

Fileobject.close()

readline()

 Python facilitates us to read the file line by line by using a function readline().

 The readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines of the file.

123
PYTHON PROGRAMMING III-BSC[CS]
Syntax:

Fileobject.readline()

 function open() to open a file.


 method read() to read a file.

write()

 The write () method is used to write the content into file.

 To write some text to a file, we need to open the file using the open method with one of the
following access modes.
 It will overwrite the file if any file exists. The file pointer point at the beginning of the file in
this mode.
Syntax:

Fileobject.write(content)

writelines()

The writelines () method is used to write multiple lines of content into file. To write some lines to a
file
Syntax:

Fileobject.writelines(list)

list − This is the Sequence of the strings.

File Positions
Methods that set or modify the current position within the file

124
PYTHON PROGRAMMING III-BSC[CS]
tell()

The tell() method returns the current file position in a file stream. You can change the current file
position with the seek() method.
Syntax:

Fileobject.tell()

seek()

The seek() method sets and returns the current file position in a file stream.

Syntax:

Fileobject.seek(offset)

Python - File Methods


Explain the concept of file methods or filer built in methods in python(5
marks)

 A file object is created using open() function.


 The file class defines the following methods with which different file IO
operations can be done.
 The methods can be used with any file like object such as byte stream or
network stream.

Sr.No. Methods & Description

file.close()
1 Close the file. A closed file cannot be read or written any more.

2 file.flush()

125
PYTHON PROGRAMMING III-BSC[CS]

Flush the internal buffer, like stdio's fflush. This may be a no-op on
some file-like objects.

file_fileno()
Returns the integer file descriptor that is used by the underlying
3 implementation to request I/O operations from the operating system.

file.isatty()
4 Returns True if the file is connected to a tty(-like) device, else False.

next(file)
5 Returns the next line from the file each time it is being called.

file.read([size])
Reads at most size bytes from the file (less if the read hits EOF before
6 obtaining size bytes).

file.readline([size])
Reads one entire line from the file. A trailing newline character is kept
7
in the string.

file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines.
If the optional sizehint argument is present, instead of reading up to
8 EOF, whole lines totalling approximately sizehint bytes (possibly after
rounding up to an internal buffer size) are read.

file.seek(offset[, whence])
9 Sets the file's current position

file.tell()
10 Returns the file's current position

126
PYTHON PROGRAMMING III-BSC[CS]

file.truncate([size])
11 Truncates the file's size. If the optional size argument is present, the file
is truncated to (at most) that size.

file.write(str)
12 Writes a string to the file. There is no return value.

file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any
13 iterable object producing strings, typically a list of strings.

Let us go through the above methods briefly.

Python - OS File/Directory Methods

The os module provides a big range of useful methods to manipulate files.

Most of the useful methods are listed here −

Sr.No. Methods with Description

1 os.close(fd)

Close file descriptor fd.

2 os.closerange(fd_low, fd_high)

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive),


ignoring errors.
3 os.dup(fd)

Return a duplicate of file descriptor fd.


4 os.fdatasync(fd)

127
PYTHON PROGRAMMING III-BSC[CS]

Force write of file with filedescriptor fd to disk.


5 os.fdopen(fd[, mode[, bufsize]])

Return an open file object connected to the file descriptor fd.


6 os.fsync(fd)

Force write of file with filedescriptor fd to disk.


7 os.ftruncate(fd, length)

Truncate the file corresponding to file descriptor fd, so that it is at most


length bytes in size.
8 os.lseek(fd, pos, how)

Set the current position of file descriptor fd to position pos, modified by


how.
9 os.open(file, flags[, mode])

Open the file file and set various flags according to flags and possibly its
mode according to mode.
10 os.read(fd, n)

Read at most n bytes from file descriptor fd. Return a string containing
the bytes read. If the end of the file referred to by fd has been reached,
an empty string is returned.
11 os.tmpfile()

Return a new file object opened in update mode (w+b).


12 os.write(fd, str)

Write the string str to file descriptor fd. Return the number of bytes
actually written.

128
PYTHON PROGRAMMING III-BSC[CS]
File Built-in Attributes

Describe File Built-in Attributes(5 marks)


Python Supports following built-in attributes, those are

 file.name - returns the name of the file which is already opened.

 file.mode - returns the access mode of opened file.

 file.closed - returns true, if the file closed, otherwise false.

 Examples:

f = open ("myfile.txt", "r")


print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)

output:

myfile.txt
r
False
True

Python program to print number of lines, words and characters in given file.

function open() to open a file.


method read() to read a file.
Python is the modern day language.
Python supports Files
python supports Strings

129
PYTHON PROGRAMMING III-BSC[CS]

 In Python, file attributes provide information about a file, such as its size, creation time,
modification time, etc.
 The built-in os module and os.path module (deprecated in Python 3.10 and later) are
commonly used for working with file attributes.
 Here are some common file attributes and how you can retrieve them using Python:

File Path:
import os

file_path = 'example.txt'

print("File Path:", os.path.abspath(file_path))

File Size:
import os

file_path = 'example.txt'

size_in_bytes = os.path.getsize(file_path)

print("File Size (in bytes):", size_in_bytes)

File Creation Time:

import os

import datetime

file_path = 'example.txt'

creation_time = os.path.getctime(file_path)

creation_time_formatted = datetime.datetime.fromtimestamp(creation_time).strftime('%Y-%m-
%d %H:%M:%S')

print("File Creation Time:", creation_time_formatted)

File Modification Time:


import os

import datetime

file_path = 'example.txt'

modification_time = os.path.getmtime(file_path)

130
PYTHON PROGRAMMING III-BSC[CS]
modification_time_formatted =
datetime.datetime.fromtimestamp(modification_time).strftime('%Y-%m-%d %H:%M:%S')
print("File Modification Time:", modification_time_formatted)

Is a Directory:
import os

file_path = 'example_directory'

is_directory = os.path.isdir(file_path)

print("Is a Directory:", is_directory)

Is a File:

import os

file_path = 'example.txt'

is_file = os.path.isfile(file_path)

print("Is a File:", is_file)

Python standard I/O

Illustrate about Python standard I/O Explain with example(10 marks)

 There are three basic I/O connections: standard input, standard output and standard error.
Standard input is the data that goes to the program.
 The standard input comes from a keyboard. Standard output is where we print our data
with the print keyword.
 Unless redirected, it is the terminal console. The standard error is a stream where
programs write their error messages. It is usually the text terminal.

The standard input and output in Python are objects located in the sys module.

Object Description

sys.stdin standard input

131
PYTHON PROGRAMMING III-BSC[CS]

sys.stdout standard output

sys.stderr standard error

Conforming to the UNIX philosophy, the standard I/O streams are file objects.

Python standard input

Standard input is the data that goes to the program.

read_name.py

#!/usr/bin/env python

# read_name.py

import sys

print('Enter your name: ', end='')

name = ''

sys.stdout.flush()

while True:

c = sys.stdin.read(1)

if c == '\n':
break

name = name + c

print('Your name is:', name)

The read method reads one character from the standard input. In our example we get a
prompt saying "Enter your name". We enter our name and press Enter. The Enter key
generates the new line character: \n.

132
PYTHON PROGRAMMING III-BSC[CS]
$ ./read_name.py
Enter your name: Peter
Your name is: Peter

For getting input we can use higher level functions: input and raw_input .

The input function prints a prompt if it is given and reads the input.

input_example.py

#!/usr/bin/env python

# input_example.py

data = input('Enter value: ')

print('You have entered:', data)


$ ./input_example.py
Enter value: Hello there
You have entered: Hello there

Python standard output

The standard output is where we print our data.

std_output.py

#!/usr/bin/env python

# std_output.py

import sys

sys.stdout.write('Honore de Balzac, Father Goriot\n')


sys.stdout.write('Honore de Balzac, Lost Illusions\n')

In the example, we write some text to the standard output. This is in our case the
terminal console. We use the write method.

$ ./stdout.py

133
PYTHON PROGRAMMING III-BSC[CS]
Honore de Balzac, Father Goriot
Honore de Balzac, Lost Illusions

The print function puts some text into the sys.stdout by default.

print_fun.py

#!/usr/bin/env python

# print_fun.py

print('Honore de Balzac')
print('The Splendors and Miseries of Courtesans', 'Gobseck', 'Father Goriot', sep=":")

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

for e in vals:
print(e, end=' ')

print()

In this example, we use the sep and end parameters. The sep separates the printed objects
and the end defines what is printed at the end

Describe Command Line Arguments In Python(5 marks)

 Python Command Line Arguments provides a convenient way to accept some


information at the command line while running the program.
 The arguments that are given after the name of the Python script are known as Command
Line Arguments and they are used to pass some information to the program. For example
 $ python script.py arg1 arg2 arg3
 Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3 are
command line arguments for the program. There are following three Python modules
which are helpful in parsing and managing the command line arguments:
 sys module

134
PYTHON PROGRAMMING III-BSC[CS]
 getopt module
 argparse module

1.sys module - System-specific parameters

The Python sys module provides access to any command-line arguments via the sys.argv. This
serves two purposes −
sys.argv is the list of command-line arguments.

len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example

Consider the following script test.py −

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'

print 'Argument List:', str(sys.argv)

Now run above script as below. All the programs in this tutorial need to be run from the
command line, so we are unable to provide online compile & run option for these programs.
Kindly try to run these programs at your computer.
$ python test.py arg1 arg2 arg3

This produce following result −

Number of arguments: 4 arguments.

Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

As mentioned above, first argument is always script name and it is also being counted in number
of arguments.
Parsing Command-Line Arguments

Python provided a getopt module that helps you parse command-line options and arguments.
This module provides two functions and an exception to enable command line argument parsing.

135
PYTHON PROGRAMMING III-BSC[CS]
getopt.getopt method

This method parses command line options and parameter list. Following is simple syntax for this
method −
getopt.getopt(args, options, [long_options])

Here is the detail of the parameters −

args − This is the argument list to be parsed.

options − This is the string of option letters that the script wants to recognize, with options that
require an argument should be followed by a colon (:).
long_options − This is optional parameter and if specified, must be a list of strings with the
names of the long options, which should be supported. Long options, which require an argument
should be followed by an equal sign ('='). To accept only long options, options should be an
empty string.
This method getopt.getopt() returns value consisting of two elements: the first is a list of (option,
value) pairs. The second is the list of program arguments left after the option list was stripped.
Each option-and-value pair returned has the option as its first element, prefixed with a hyphen
for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option').
Example

Following is a Python program which takes three arguments at command line:

First command line argument is -h which will be used to display the usage help of the program.

Second argument is either -i or --ifile which we are considering as input file.

Third argument is either -o or --ofile which we are considering as output file.

 In Python, you can access command line arguments using the sys module or the more
powerful argparse module.
 The sys.argv variable is a list in the sys module that contains the command-line
arguments passed to the script.
 However, the argparse module is more flexible and provides a way to define and handle
command-line arguments in a structured manner.

136
PYTHON PROGRAMMING III-BSC[CS]
Using sys.argv:

import sys

# The first element in sys.argv is the script name itself

script_name = sys.argv[0]

# The rest of the elements are the command-line arguments

arguments = sys.argv[1:]

print(f"Script Name: {script_name}")

print(f"Arguments: {arguments}")

When you run a script with command line arguments, like this:

Using argparse:

The argparse module provides a more sophisticated way to handle command-line arguments,
allowing you to define options, positional arguments, and more.
argparse allows you to define various argument types, specify default values, and generate help
messages, making it a powerful tool for handling command-line arguments in a structured and
user-friendly way.
1. The continue keyword is used to the current iteration in a loop.

A. Initiate C. Start
B. End D. None of the mentioned above

Answer: C) End

2. The is a built-in function that returns a range object that consists series of integer
numbers, which we can iterate using a for loop.

A. range() B. set()
B. dictionary{} D. None of the mentioned above

Answer: A) range()

3.A function is a group of related statements which designed specifically to perform a .

A. Write code B. Specific task

137
PYTHON PROGRAMMING III-BSC[CS]
B. Create executable file D. None of the mentioned above

Answer: B) Specific task

4. once we have defined a function, we can call it?

A. True b.False Answer: A) True

5. Amongst which of the following shows the types of function calls in Python?

A. Call by value b.Call by reference

c.Both A and B d.None of the mentioned above

Answer: C) Both A and B

6. Amongst which of the following is a function which does not have any name?

A. Del function b. Show function


B. Lambda function d. None of the mentioned above

Answer: C) Lambda function

7. Can we pass List as an argument in Python function?

A. Yes b. No Answer: A) Yes

8. A method refers to a function which is part of a class?

A. True b. False Answer: A) True

9. Amongst which of the following is / are the key functions used for file handling in
Python?

A. open() and close() B. read() and write()


B. append() D. All of the mentioned above

Answer: D) All of the mentioned above

10. Amongst which of the following is / are needed to open an existing file?

138
PYTHON PROGRAMMING III-BSC[CS]
A. filename B. mode
B. Both A and B D. None of the mentioned above

Answer: C) Both A and B

11. Binary files are stored in the form of 0s and 1s?

A. True B.False Answer: A) True

12. the function file_object.close() is used to .

A. To open the existing file C. To append in an opened file


B. To close an opened file D. None of the mentioned above

Answer: C) To close an opened file

13. The write() method takes a string as an argument and .


A. writes it to the text file B. read from the text file
B. append in a text file D. None of the mentioned above

Answer: A) writes it to the text file

14. The seek() method is used to .

A. Saves the file in secondary storage


B. Position the file object at a particular position in a file
C. Deletes the file form secondary storage
D. None of the mentioned above

Answer: B) Position the file object at a particular position in a file

15. Amongst which of the following function is / are used to create a file and writing data?

A. append() B. open()
B. close() D. None of the mentioned above Answer: B) open()

16. The readline() is used to read the data line by line from the text file.

A. True B. False Answer: A) True

17. . Python is a object-oriented programming language.

139
PYTHON PROGRAMMING III-BSC[CS]
A. Special purpose B. General purpose
B. Medium level programming language D.All of the mentioned above

Answer: B) General purpose

18. A text file contains only textual information consisting of .

A. Alphabets B. Numbers
B. Special symbols D. All of the mentioned above

Answer: D) All of the mentioned above

19. The writelines() method is used to write multiple strings to a file?


A. True B. False Answer: A) True

20. Amongst which of the following is / are the method used to unpickling data from a
binary file?

A. load() B. set() method


B. dump() method D. None of the mentioned above

Answer: B) set() method

21. What will be the output of the following code :

print type(type(int))

(A) type ‘int’ (B) type ‘type’ (C) Error (D) 0


Answer: (B)
22. What is the output of the following code :
L = ['a','b','c','d']
print("".join(L))
(A) Error (B) None (C) abcd D) [‘a’,’b’,’c’,’d’]

Answer: (C)
23. What is the output of the following program

y=8

z = lambda x : x * y

print (z(6))

(A) 48 (B) 14 (C) 64 (D) None of the above

140
PYTHON PROGRAMMING III-BSC[CS]

Answer: (A)
24. What is the output of the following segment :
chr(ord('A'))

(A) A (B) B (C) a (D) Error

Answer: (A)
25. What is called when a function is defined inside a class?

(A)Module (B)Class (C)Another Function (D)Method

Answer: (D)
26. Which of the following is the use of id() function in python?
(A) Id returns the identity of the object
(B) Every object doesn’t have a unique id
(C) All of the mentioned
(D) None of the mentioned

Answer: (A)
What is the output of the following program :

27. import re
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.groupdict())
(A) {‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}
(B) (‘horses’, ‘are’, ‘fast’)
(C) ‘horses are fast’
(D) ‘are’

Answer: (A)
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.pop(1)?
(A) [3, 4, 5, 20, 5, 25, 1, 3] (B) [1, 3, 3, 4, 5, 5, 20, 25]
(C) [3, 5, 20, 5, 25, 1, 3] (D) [1, 3, 4, 5, 20, 5, 25]

Answer: (C)
28. time.time() returns __ __
(A) the current time
(B) the current time in milliseconds
(C) the current time in milliseconds since midnight
(D) the current time in milliseconds since midnight, January 1, 1970
(E) the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time)

141
PYTHON PROGRAMMING III-BSC[CS]

Answer: (E)
29. Consider the results of a medical experiment that aims to predict whether someone is
going to develop myopia based on some physical measurements and heredity. In this
case, the input dataset consists of the person’s medical characteristics and the target
variable is binary: 1 for those who are likely to develop myopia and 0 for those who
aren’t. This can be best classified as
(A) Regression
(B) Decision Tree
(C) Clustering
(D) Association Rules
Which of these is not a core data type?
(A) Lists (B) Dictionary (C) Tuples (D) Class

Answer: (D)
30. What data type is the object below ?
L = [1, 23, ‘hello’, 1]
(A) List (B) Dictionary (C) Tuple (D) Array

Answer: (A)
31. Which of the following function convert a string to a float in python?
(A) int(x [,base]) (B) long(x [,base] )
(C) float(x) (D) str(x)

Answer: (C)
32. Find the output of the following program:
a = {i: i * i for i in range(6)}
print (a)
(A) Dictionary comprehension doesn’t exist
(B) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}
(C) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}
(D) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Answer: (D)

33. Find the output of the following program:

nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']

pos = nameList.index("GeeksforGeeks")

142
PYTHON PROGRAMMING III-BSC[CS]
print (pos * 3)

(A) GeeksforGeeks GeeksforGeeks GeeksforGeeks


(B) Harsh
(C) Harsh Harsh Harsh
(D) ValueError: ‘GeeksforGeeks’ is not in list

Answer: (D)
34:Find the output of the following program:
D = dict() for x in enumerate(range(2)):

D[x[0]] = x[1]

D[x[1]+7] = x[0]
print(D)

(A) {0: 1, 7: 0, 1: 1, 8: 0} (B) {1: 1, 7: 2, 0: 1, 8: 1}


(C) {0: 0, 7: 0, 1: 1, 8: 1} (D) KeyError

Answer: (C)

35. What is the output of the following program :

print \"Hello World\"[::-1]

(A)dlroW olleH (B)Hello Worl (C)d (D)Error

Answer: (A)

36. Which function overloads the >> operator?

(A) more() (B) gt() (C) ge() D) None of the above

Answer: (D)

37. Which operator is overloaded by the or() function?

(A) || (B) | (C) // (D) /

Answer: (B)
143
PYTHON PROGRAMMING III-BSC[CS]
38. What is the output of the following code :

print 9//2

(A)4.5 (B)4.0 (C)4 (D)Error

Answer: (C)

39. What is the output of the following program :

i=0

while i < 3:
print i

i++

print i+1

(A)0 2 1 3 2 4 (B)0 1 2 3 4 5 (C)Error (D)1 0 2 4 3 5 Answer: (C)

40. Which of the following is not used as loop in Python?

A. for loop B. while loop

C. do-while loop D. None of the above Ans : C

41. Which one of the following is a valid Python if statement :

A. if a>=2 : B. if (a >= 2)

C. if (a => 22) D. if a >= 22 Ans : A

42. What keyword would you use to add an alternative condition to an if statement?

A. else if B. elseif C. elif D. None of the above Ans : C

43. Can we write if/else into one line in python?

A. Yes B. No

C. if/else not used in python D. None of the above Ans : A

44. In a Python program, a control structure:

A. Defines program-specific data structures

B. Directs the order of execution of the statements in the program

C. Dictates what happens before the program starts and after it terminates

D. None of the above Ans : B

144
PYTHON PROGRAMMING III-BSC[CS]
45. A while loop in Python is used for what type of iteration?

A. indefinite B. discriminant

C. definite D. indeterminate Ans : A

46. A loop becomes infinite loop if a condition never becomes .

A. TRUE B. FALSE

C. Null D. Both A and C Ans : B


47. If the else statement is used with a while loop, the else statement is executed when the
condition becomes .
A. TRUE B. FALSE C. Infinite D. Null Ans : B

48. Python programming language allows to use one loop inside another loop known as?

A. switch B. foreach C. nested D. forall Ans : C

49. The statement is a null operation.

A. break B. exit C. return D. pass

Ans : D

50. The continue statement can be used in?

A. while loop B. for loop C. do-while D. Both A and B

Ans : D

145
PYTHON PROGRAMMING III-BSC[CS]

UNIT -IV

FUNCTIONS AND FUNCTIONAL PROGRAMMING :


Functions and functional programming are fundamental concepts in computer science and
software development. Let's explore these concepts:

Functions:
1. Definition:
A function is a self-contained block of code that performs a specific task.

Functions take input, process it, and produce output.

2. Characteristics:
Modularity: Functions promote code modularity by breaking down a program into smaller,
manageable parts.
Reusability: Functions can be reused in different parts of a program or even in different
programs.
Abstraction: Functions hide the internal details of their implementation, providing a high-level
interface.
3. Syntax (in a programming language like Python):
def function_name(parameters):

# function body

return result

4. Types of Functions:

Built-in Functions: Provided by the programming language.

User-defined Functions: Created by the programmer.

Describe about Functional Programming(5 marks)

1. Definition:

Functional programming is a programming paradigm that treats computation as the evaluation of


mathematical functions and avoids changing state and mutable data.
2. Core Concepts:
First-Class Functions: Functions are treated as first-class citizens, meaning they can be passed
as arguments, returned from other functions, and assigned to variables.
Pure Functions: Functions that, given the same input, always produce the same output and have
no side effects.

146
PYTHON PROGRAMMING III-BSC[CS]
Immutability: Data, once created, cannot be changed. Instead of modifying existing data, new
data is created.
3. Principles:
Referential Transparency: An expression can be replaced with its value without changing the
program's behavior.
Avoiding Side Effects: Functions should not modify external state; their only purpose is to
produce output.
4. Examples of Functional Programming Languages:
Haskell: A purely functional programming language.

Clojure, Lisp, and Scheme: Functional programming languages that run on the Lisp platform.

Functional Features in Python, JavaScript, and Scala: These languages support functional
programming concepts.
5. Benefits:
Conciseness: Code tends to be shorter and more expressive.

Parallelism: Functional programs can be easier to parallelize, as functions with no side effects
can be executed concurrently.
6. Higher-Order Functions:

Functions that take other functions as arguments or return functions.

7. Examples of Higher-Order Functions:


map: Applies a function to each element in a list.
filter: Selects elements from a list based on a given condition.

reduce: Combines elements of a list into a single value.

Explain define functions and explain the fundamentals?(5 marks)


In Python, functions are a fundamental building block of the language. Here are the key aspects
of working with functions in Python:
Defining a Function:
In Python, you define a function using the def keyword, followed by the function name,
parameters in parentheses, and a colon. The function body is indented.
Syntax:
def my_function(parameter1, parameter2):

# function body

result = parameter1 + parameter2

return result

147
PYTHON PROGRAMMING III-BSC[CS]
Calling a Function:
Once a function is defined, you can call it by using the function name followed by parentheses,
passing any required arguments.
result = my_function(3, 4)

print(result) # Output: 7

Function Parameters:

Python supports various types of function parameters:

Positional Parameters: Parameters passed by position.

Keyword Parameters: Parameters passed by name.

Default Parameters: Parameters with default values.


Variable-Length Parameters: Allowing a variable number of arguments.

def example_function(a, b, c=0, *args, **kwargs):

# function body

pass

example_function(1, 2, 3, 4, 5, keyword1="value1", keyword2="value2")

Return Statement:
A function can return a value using the return statement. If no return statement is present, the
function returns None by default.
def add(a, b):

return a + b

result = add(2, 3)

print(result) # Output: 5

Docstrings:

It is good practice to include a docstring (documentation string) to describe the purpose and
usage of the function.
def greet(name):

"""

This function greets the person passed in as a parameter.

"""

return f"Hello, {name}!"

148
PYTHON PROGRAMMING III-BSC[CS]
Lambda Functions:
Lambda functions, or anonymous functions, can be created using the lambda keyword. They are
useful for short, one-line operations.
multiply = lambda x, y: x * y

result = multiply(3, 4)

print(result) # Output: 12

Scope of Variables:

Variables defined inside a function have local scope, while variables defined outside functions
have global scope. Use the global keyword to modify a global variable within a function.
Examples:

global_var = 10

def my_function(x):
local_var = 5

return x + local_var + global_var

result = my_function(3)

print(result) # Output: 18

These are the basics of working with functions in Python. Understanding function parameters,
return values, and scoping is crucial for effective Python programming.

Python - Functions

 A Python function is a block of organized, reusable code that is used to perform a single,
related action.
 Functions provide better modularity for your application and a high degree of code
reusing.
 A top-to-down approach towards building the processing logic involves defining blocks
of independent reusable functions.
 A Python function may be invoked from any other function by passing required data
(called parameters or arguments). The called function returns its result back to the
calling environment.

149
PYTHON PROGRAMMING III-BSC[CS]

Explain the Types of Python Functions(10 marks)


Python provides the following types of functions −

 Built-in functions
 Functions defined in built-in modules
 User-defined functions

 Python's standard library includes number of built-in functions.


 Some of Python's built-in functions are print(), int(), len(), sum(), etc.
 These functions are always available, as they are loaded into computer's memory as soon
as you start Python interpreter.
 The standard library also bundles a number of modules. Each module defines a group of
functions. These functions are not readily available.
 You need to import them into the memory from their respective modules.
 In addition to the built-in functions and functions in the built-in modules, you can also
create your own functions.
 These functions are called user-defined functions.

Defining a Function in Python

 You can define custom functions to provide the required functionality. Here are simple
rules to define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
 The first statement of a function can be an optional statement; the documentation string of
the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an expression
150
PYTHON PROGRAMMING III-BSC[CS]
to the caller. A return statement with no arguments is the same as return None.

Syntax
def functionname( parameters ):

"function_docstring"

function_suite

return [expression]

151
PYTHON PROGRAMMING III-BSC[CS]

 By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
 Once the function is defined, you can execute it by calling it from another function or
directly from the Python prompt.

Example
def greetings():

"This is docstring of greetings function"


print ("Hello World")
return
greetings()
 The following example shows how to define a function greetings(). The bracket is empty
so there aren't any parameters.
The first line is the docstring. Function block ends with return statement. when this
function is called, Hello world message will be printed.

Explain the Calling a Function in Python (5 marks)


 Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
 Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt.
 Following is the example to call printme() function −

# Function definition is here

def printme( str ):

"This prints a passed string into this function"


print (str)
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following output −

152
PYTHON PROGRAMMING III-BSC[CS]

I'm first call to user defined function!


Again second call to the same function

Illustrate about Pass by Reference vs Value(5 marks)


or diffrenciate between call by value and call by reference
 The function calling mechanism of Python differs from that of C and C++.
There are two main function calling mechanisms:
 Call by Value and
 Call by Reference.
 When a variable is passed to a function, what does the function do to it? If any
changes to its variable does not get reflected in the actual argument, then it uses
call by value mechanism.
On the other hand, if the change is reflected, then it becomes call by reference
mechanism.

Difference between call by value and call by reference in Python


Call by value Call by reference
Call by value:-The parameter values are Call by reference:-
copied to function parameter and then two The actual, as well as the formal
types of parameters are stored in the parameters refer to the same location
memory locations. and if changes are made inside the
When changes are made the functions are functions the functions are reflected in
not reflected in the parameter of the caller.
the actual parameter of the caller.

153
PYTHON PROGRAMMING III-BSC[CS]
While calling the function we pass values and At the time of calling instead of passing
called as call by values. the values we pass the address of the
variables that means the location of
variables so called call by reference.
The value of each variable is calling the The address of variable in function while
function and copy variable into the variables calling is copied into dummy variables of
of the function. a function.
The changes are made to dummy variables By using the address we have the
in the called function that have no effect on access to the actual variable.
the actual variable of the function.
We cannot change the values of the actual We can change the values of the actual
variable through a function call. variable through a function call.

The values are passed by the simple The pointers are necessary to define
techniques and store the address of variables.

Call by value Example:- Call by reference:-

def primtme (str): def changeme(mylist):


print str
mylist.append(1, 2, 3, 4]);
return;
printme(“I’m first call to user defined print”values inside the function:” mylist
function!”) return
printme(“Again second call to same mylist= [10, 20, 30];
function”) changeme (mylist);
Output:- print”values outside the function:” mylist
I’m first call to user defined function! Output:-
values inside the function: [10, 20, 30,
Again second call to same function
[1, 2, 3, 4]]
values outside the function: [10, 20, 30,
[1, 2, 3, 4]]

call by value call by reference


C/C++ functions are said to be called by Python uses pass by reference mechanism
value.

154
PYTHON PROGRAMMING III-BSC[CS]
 When a function in C/C++ is called,  . As variable in Python is a label or
the value of actual arguments is reference to the object in the memory,
copied to the variables . representing the both the variables used as actual
the formal arguments. argument as well as formal arguments
really refer to the same object in the
memory.

 In the Call by Value method, there is  In the Call by Reference method,


no modification in the original value. theris a modification in the original
value.

 If the function modifies the value of We can verify this fact by checking
formal aergument, it doesn't reflect the the id() of the passed variable before
variable that was passed to it and after passing.

What is the Function Arguments ? explain briefly(5 marks)

 The process of a function often depends on certain data provided to it while calling it.
 While defining a function, you must give a list of variables in which the data passed to it
is collected.
 The variables in the parentheses are called formal arguments.
 When the function is called, value to each of the formal arguments must be provided.
 Those are called actual arguments.

Example

155
PYTHON PROGRAMMING III-BSC[CS]
Let's modify greetings function and have name an argument. A string passed to the
function as actual argument becomes name variable inside the function.

def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return
greetings("Samay")
greetings("Pratima")
greetings("Steven")
It will produce the following

output −
Hello Samay
Hello Pratima
Hello Steven

Explain the concept of Function with Return Value with given


examples(5 marks)

 The return keyword as the last statement in function definition indicates end of function
block, and the program flow goes back to the calling function.
 Although reduced indent after the last statement in the block also implies return but using
explicit return is a good practice.
 Along with the flow control, the function can also return value of an expression to the
calling function.
 The value of returned expression can be stored in a variable for further processing.
Example
Let us define the add() function. It adds the two values passed to it and returns the addition. The
returned value is stored in a variable called result.
def add(x,y):
z=x+y
return z
a=10
b=20
result = add(a,b)
print ("a = {} b = {} a+b = {}".format(a, b, result))
It will produce the following output −
a = 10 b = 20 a+b = 30

156
PYTHON PROGRAMMING III-BSC[CS]

Explain the Types of Function Arguments(5 marks)

Based on how the arguments are declared while defining a Python function, they are classified
into the following categories −

 Positional or required arguments


 Keyword arguments
 Default arguments
 Positional-only arguments
 Keyword-only arguments
 Arbitrary or variable-length arguments

In the next few chapters, we will discuss these function arguments at length.

Order of Arguments

A function can have arguments of any of the types defined above. However, the arguments must
be declared in the following order −

 The argument list begins with the positional-only args, followed by the slash (/) symbol.

 It is followed by regular positional args that may or may not be called as keyword
arguments.
 Then there may be one or more args with default values.
 Next, arbitrary positional arguments represented by a variable prefixed with single
asterisk, that is treated as tuple. It is the next.
 If the function has any keyword-only arguments, put an asterisk before their names start.
Some of the keyword-only arguments may have a default value.
 Last in the bracket is argument with two asterisks ** to accept arbitrary number of
keyword arguments.
The following diagram shows the order of formal arguments –

157
PYTHON PROGRAMMING III-BSC[CS]
How To Create A Functions In Python ?
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Creating a function in Python involves using the def keyword, specifying
the function name, parameters (if any), and the function body. Here's the
basic syntax:

def function_name(parameter1, parameter2, ...):

# function body

# perform operations

return result # optional, used to return a value

# Example function without parameters

def greet():

print("Hello, welcome!")

# Example function with parameters and return statement

def add_numbers(a, b):

result = a + b

return result

# Example function with default parameter

def greet_person(name, greeting="Hello"):

print(f"{greeting}, {name}!")

# Example function with variable-length arguments

def sum_all(*args):
158
PYTHON PROGRAMMING III-BSC[CS]
result = sum(args)

return result

# Example function with keyword arguments


def print_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

# Example function with a combination of parameter types

def complex_function(a, b, *args, c=0, **kwargs):

result = a + b + c + sum(args) + sum(kwargs.values())

return result

# Calling the functions

greet()

sum_result = add_numbers(3, 4)

print(sum_result)

greet_person("Alice")

greet_person("Bob", greeting="Hi")

total = sum_all(1, 2, 3, 4, 5)

print(total)

print_info(name="John", age=25, city="New York")

result = complex_function(1, 2, 3, 4, c=5, x=6, y=7)

print(result)

In this example:

greet() is a simple function without parameters.

add_numbers(a, b) takes two parameters and returns their sum.

159
PYTHON PROGRAMMING III-BSC[CS]
greet_person(name, greeting="Hello") has a default value for the greeting parameter.

sum_all(*args) uses variable-length arguments to accept any number of positional arguments.

print_info(**kwargs) uses variable-length keyword arguments to accept any number of


keyword arguments.
complex_function(a, b, *args, c=0, **kwargs) showcases a function with a mix of parameter
types.
Passing a function as an argument
 We have a list of strings represent fruit names:

>>> fruits = ['kumquat', 'cherimoya', 'Loquat', 'longan', 'jujube']

 If we wanted to alphabetize this list we could pass it to the built-in sorted function:

>>> sorted(fruits)

['Loquat', 'cherimoya', 'jujube', 'kumquat', 'longan']

 Except that sorted doesn't quite alphabetize this list because when Python sorts strings it
puts all the uppercase letters before all the lowercase letters (due to their ASCII/unicode
ordering).
We can fix this, by supplying a key argument to the built-in sorted function.

>>> help(sorted)

sorted(iterable, /, *, key=None, reverse=False)

. ..

This key argument should be a function that will be called with each of the individual items in
our fruits iterable and it should return the thing to sort by.

In our case, we could make a function that lowercases any string given to it in order to sort by
the lowercase versions of each string:
>>> def lowercase(string):
... return string.lower()

...

To sort by lowercased strings we'll call sorted with a key argument that points to this lowercase
function:

160
PYTHON PROGRAMMING III-BSC[CS]

>>> sorted(fruits, key=lowercase)

['cherimoya', 'jujube', 'kumquat', 'longan', 'Loquat']

That properly alphabetized our list of strings (while maintaining their original capitalization in
the resulting list).

Notice that when we called sorted, we didn't put parentheses (()) after lowercase to call it, like
this:

>>> lowercase('X')

'x'

We didn't call lowercase at all. Instead we just referred to lowercase:

>>> lowercase

<function lowercase at 0x7fc8a3fc09d0>

We passed the lowercase function object to the sorted function (via its key argument):

>>> sorted(fruits, key=lowercase)

So that sorted could call lowercase itself repeatedly on each of the individual items of fruits list
(using the return value it got as a sort of comparison key to sort by).

So in Python, there are functions that accept other functions as arguments.

How do apply ,map, reduce and filter functions work in Python?(10 marks)
 Python's, map(), filter(), and reduce() functions add a touch of functional programming
to the language.
 All of these are convenience functions that can be replaced with List Comprehensions or
loops but offer a more elegant and concise solution to some problems.

 map(), filter(), and reduce() all work in the same way. These functions accept a function
and a sequence of elements and return the result of applying the received function to each
element in the sequence.
161
PYTHON PROGRAMMING III-BSC[CS]

apply() method :
Definition and Usage

The apply() method allows you to apply a function along one of the axis of the DataFrame, default 0,
which is the index (row) axis.

Syntax

dataframe.apply(func, axis, raw, result_type, args, kwds)

Example :

import pandas as pd

def calc_sum(x):
return x.sum()

data = {
"x": [50, 40, 30],
"y": [300, 1112, 42]
}

df = pd.DataFrame(data)

PYTHON PROGRAMMING III-BSC[CS]

x = df.apply(calc_sum)

print(x)

Parameters
The axis, raw, result_type, and args parameters are keyword arguments.

Parameter Value Description

162
PYTHON PROGRAMMING III-BSC[CS]

func Required. A function to apply to the DataFrame.

axis 0 Optional, Which axis to apply the function to. default 0.


1
'index'
'columns'

raw True Optional, default False. Set to true if the row/column should be passed a s
False object

result_type 'expand' Optional, default None. Specifies how the result will be
'reduce'
'broadcast' returned

None

args a tuple Optional, arguments to send into the function

kwds keyword Optional, keyword arguments to send into the function


arguments

163
PYTHON PROGRAMMING III-BSC[CS]

map() function

 Like reduce(), the map() function allows you to iterate over each item in an iterable.
Map(), on the other hand, operates independently on each item rather than producing a
single result.
 Finally, the map() function can be used to perform mathematical operations on two or
more lists. It can even be used to manipulate any type of array.
The map() function’s time complexity= O (n)
Syntax

map(function, iterable)

Parameters
function − The function to be used in the code.

iterable − This is the value that is iterated in the code.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –

 Create a function with the name multiplyNumbers that returns the multiplication result of
the number passed to it.
 Return the given number multiplied by 3, inside the function.
 Use the map() function for applying the multiplyNumbers() function for each element of
the list by passing the function name, and list as arguments to it.
 Print the resultant list items after multiplying them with 3.

Filter() function

The filter() function creates a new iterator that filters elements from a previously created one (like
a list, tuple, or dictionary).

The filter() function checks whether or not the given condition is present in the sequence and then
prints the result.

The filter() function’s time complexity= O (n)

Syntax
filter(function, iterable)
164
PYTHON PROGRAMMING III-BSC[CS]
Parameters
 function − The function to be used in the code.
 iterable − This is the value that is iterated in the code.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –

 Create a function with the name votingAge that returns the eligibility ages for voting from
the list.
 Use the if conditional statement to check whether the number passed to the function is
greater than or equal to 18.
 If the above statement is true Return the number.
 Create a variable to store the input list.
 Use the filter() function by passing the function name, and input list as arguments to it to
filter the ages greater than or equal to 18 from the list. Here it applies the votingAge()
function to every element of the list and the result stores only the values of the list that are
returned by the votingAge() function(Here votingAge() function returns the number if it is
greater than 18).
 Print the filter object
 Use the list() function(returns a list of an iteratable), to convert the above filter object into
a list and print it.

reduce()

 In Python, the reduce() function iterates through each item in a list or other iterable data
type, returning a single value. It's in the functools library. This is more efficient than
looping.

Syntax

reduce(function, iterable)

Parameters
 function − The function to be used in the code.
 iterable − This is the value that is iterated in the code.

Algorithm (Steps)

 Following are the Algorithm/steps to be followed to perform the desired task –


 Use the import keyword to import the reduce() function from functools module
 Create a function with the name addNumbers() that returns the sum of all list items.
 Create a variable to store the input list
165
PYTHON PROGRAMMING III-BSC[CS]
 Use the reduce() function, bypassing the addNumbers() function, and input list as
arguments to get the sum of all list items.
modules and files
n Python, modules and files are essential concepts for organizing and structuring code.
Modules:
Definition:A module in Python is a file containing Python definitions and statements.
The file name is the module name with the suffix .py.
Creating a Module:

Create a Python file (e.g., my_module.py).


Write functions, classes, or variables in the file.
Example :# my_module.py
def greet(name):
print(f"Hello, {name}!")
def square(x):
return x ** 2

Using a Module:

1. Import the module using the import keyword.


2. Access functions, classes, or variables using dot notation.
# main.py
import my_module

my_module.greet("Alice")
result = my_module.square(5)
print(result)
Files in Python:
Reading from a File:
Use the open() function to open a file.
Read its contents using methods like read(), readline(), or readlines().
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)

166
PYTHON PROGRAMMING III-BSC[CS]
Writing to a File:

Use the open() function with the mode "w" to open a file for writing.
Write to the file using the write() method.
# Writing to a file
Example :
with open("output.txt", "w") as file:
file.write("Hello, this is a sample text.")
Appending to a File:

Use the open() function with the mode "a" to open a file for appending.

# Appending to a file

with open("output.txt", "a") as file:


file.write("\nThis text is appended.")

Working with CSV Files (using csv module):

Use the csv module to read and write CSV files.


import csv

# Reading from a CSV file


with open("data.csv", "r") as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
print(row)

# Writing to a CSV file


with open("output.csv", "w", newline="") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Name", "Age"])
csv_writer.writerow(["Alice", 25])

167
PYTHON PROGRAMMING III-BSC[CS]
csv_writer.writerow(["Bob", 30])
These examples provide a basic overview of modules and file handling in Python.
Modules help organize code, and file operations allow you to read from and write to files,
making data storage and retrieval possible in your programs.

1. What is the full form of DBMS?


a) Data of Binary Management System b) Database Management System

c) Database Management Service d) Data Backup Management System

Answer: b

2. What is a database?
a) Organized collection of information that cannot be accessed, updated, and managed

b) Collection of data or information without organizing

c) Organized collection of data or information that can be accessed, updated, and managed

d) Organized collection of data that cannot be updated

Answer: C

3. What is DBMS?
a) DBMS is a collection of queries b) DBMS is a high-level language

c) DBMS is a programming language D) DBMS stores, modifies and retrieves data

Answer: d

4. Who created the first DBMS?


a) Edgar Frank Codd b) Charles Bachman c) Charles Babbage d) Sharon B. Codd

Answer: b

5. Which type of data can be stored in the database?


a) Image oriented data b) Text, files containing data

c) Data in the form of audio or video d) All of the above

Answer: d

6. In which of the following formats data is stored in the database management system?

168
PYTHON PROGRAMMING III-BSC[CS]
a) Image b) Tex tc) Table d) GrapH Answer: c

7. Which of the following is not a type of database?


a) Hierarchicalb) Network c) Distributed d) Decentralized

Answer: d

8. Which of the following is not an example of DBMS?


a) MySQL b) Microsoft Acess c) IBM DB2 d) Google

Answer: d

9. Which of the following is not a feature of DBMS?


a) Minimum Duplication and Redundancy of Data b) High Level of Security

c) Single-user Access only d) Support ACID Property

Answer: c

10. Which of the following is a feature of the database?


a) No-backup for the data stored b) User interface provided

c) Lack of Authentication d) Store data in multiple locations

Answer: b

11. To open a file c:\scores.txt for reading, we use

a) infile = open(“c:\scores.txt”, “r”) b) infile = open(“c:\\scores.txt”, “r”)

c) infile = open(file = “c:\scores.txt”, “r”) d) infile = open(file = “c:\\scores.txt”, “r”)

Answer: b

12. To open a file c:\scores.txt for writing, we use


a) outfile = open(“c:\scores.txt”, “w”) b) outfile = open(“c:\\scores.txt”, “w”)

c) outfile = open(file = “c:\scores.txt”, “w”) d) outfile = open(file = “c:\\scores.txt”, “w”)

Answer: b

13. To open a file c:\scores.txt for appending data, we use


a) outfile = open(“c:\\scores.txt”, “a”) b) outfile = open(“c:\\scores.txt”, “rw”)

c) outfile = open(file = “c:\scores.txt”, “w”) d) outfile = open(file = “c:\\scores.txt”, “w”)

169
PYTHON PROGRAMMING III-BSC[CS]
Answer: a

14. Which of the following statements are true?


a) When you open a file for reading, if the file does not exist, an error occurs

b) When you open a file for writing, if the file does not exist, a new file is created

c) When you open a file for writing, if the file exists, the existing file is overwritten with the new
file
d) All of the mentioned

Answer: d

15. To read two characters from a file object infile, we use

a) infile.read(2) b) infile.read()

c) infile.readline() d) infile.readlines() Answer: a

16. To read the entire remaining contents of the file as a string from a file object infile, we
use
a) infile.read(2) b) infile.read()

c) infile.readline() d) infile.readlines() Answer: b

17. What will be the output of the following Python code?

f = None

for i in range (5):

with open("data.txt", "w") as f:

if i > 2:

break

print(f.closed)

a) True b) False c) None d) Error

Answer: a

18.To read the next line of the file from a file object infile, we use
a) infile.read(2) b) infile.read()

c) infile.readline() d) infile.readlines()

170
PYTHON PROGRAMMING III-BSC[CS]
Answer: c

19. To read the remaining lines of the file from a file object infile, we use
a) infile.read(2) b)infile.read()

c) infile.readline() d) infile.readlines() Answer: d

Explanation: Execute in the shell to verify.

20. The readlines() method returns


a) str b) a list of lines

c) a list of single characters d) a list of integers Answer: b

21. Which are the two built-in functions to read a line of text from standard input, which
by default comes from the keyboard?
a) Raw_input & Input b) Input & Scan

c) Scan & Scanner d) Scanner Answer: a

22. Which one of the following is not attributes of file?


a) closed b) softspace c) rename d) mode Answer: c

23. What is the use of tell() method in python?


a) tells you the current position within the file b) tells you the end position within the file

c) tells you the file is opened or not d) none of the mentioned

Answer: a

24. What is the current syntax of rename() a file?

a) rename(current_file_name, new_file_name)b) rename(new_file_name, current_file_name,)

c) rename(()(current_file_name, new_file_name)) d) none of the mentioned

Answer: a

25. What is the current syntax of remove() a file?


a) remove(file_name) b) remove(new_file_name, current_file_name,)

c) remove(() , file_name)) d) none of the mentioned

171
PYTHON PROGRAMMING III-BSC[CS]

Answer: a

26. What is the use of truncate() method in file?


a) truncates the file size b) deletes the content of the file

c) deletes the file size d) none of the mentioned

Answer: a

27. Which is/are the basic I/O connections in file?


a) Standard Input b) Standard Output

c) Standard Errors d) All of the mentioned Answer: d

28. Which of the following mode will refer to binary data?

a) r b) w c) + d) b Answer:d

29. What is the pickling?


a) It is used for object serialization b) It is used for object deserialization

c) None of the mentioned d) All of the mentioned


Answer: a
30. What is unpickling?
a) It is used for object serialization

b) It is used for object deserialization

c) None of the mentioned

d) All of the mentioned


Answer: b

31. Correct syntax of file.writelines() is?


a) file.writelines(sequence)

b) fileObject.writelines()

c) fileObject.writelines(sequence)

d) none of the mentioned


Answer: c

32. Correct syntax of file.readlines() is?

a) fileObject.readlines( sizehint );

b) fileObject.readlines();

c) fileObject.readlines(sequence)

d) none of the mentioned

172
PYTHON PROGRAMMING III-BSC[CS]

Answer: a

33. In file handling, what does this terms means “r, a”?

a) read, append b) append, read

c) write, append d) none of the mentioned

Answer: a

34. What is the use of “w” in file handling?

a) Read b) Write

c) Append d) None of the mentioned

Answer: b

35. What is the use of “a” in file handling?


a) Read b) Write

c) Append d) None of the mentioned

Answer: c

36. Which function is used to read all the characters?

a) Read() b) Readcharacters()

c) Readall() d) Readchar()

Answer: a

37. Which function is used to read single line from file?

a) Readline()

b) Readlines()

c) Readstatement()

d) Readfullline()

173
PYTHON PROGRAMMING III-BSC[CS]

Answer: b

38. Which function is used to write all the characters?

a) write()

b) writecharacters()

c) writeall()

d) writechar()

Answer: a

39. Which function is used to write a list of string in a file?


a) writeline()

b) writelines()

c) writestatement()

d) writefullline()

Answer: a

40. Which function is used to close a file in python?

a) Close()

b) Stop()

c) End()

d) Closefile()

Answer: a

41. Is it possible to create a text file in python?

a) Yes

b) No

c) Machine dependent

d) All of the mentioned

174
PYTHON PROGRAMMING III-BSC[CS]
42. Which of the following are the modes of both writing and reading in binary format in
file?
a) wb+

b) w

c) wb

d) w+

Answer: a

43. Which of the following is not a valid mode to open a file?

a) ab b) rw c) r+ d) w+

Answer: b

44. How do you get the name of a file from a file object (fp)?

a) fp.name b) fp.file(name)

c) self. name (fp) d) fp. name ()

Answer: a

45. Which of the following is not a valid attribute of a file object (fp)?

a) fp.name b) fp.closed

c) fp.mode d) fp.size

Answer: d

46. How do you close a file object (fp)?

a) close(fp) b) fclose(fp)

c) fp.close() d) fp. close ()

Answer: c

47. How do you get the current position within the file?
175
PYTHON PROGRAMMING III-BSC[CS]

a) fp.seek() b) fp.tell()
c) fp.loc d) fp.pos

Answer: b

48. How do you rename a file?

a) fp.name = ‘new_name.txt’

b) os.rename(existing_name, new_name)

c) os.rename(fp, new_name)

d) os.set_name(existing_name, new_name)

Answer: b

Explanation: os.rename() is used to rename files.

49. How do you delete a file?

a) del(fp) b) fp.delete()

c) os.remove(‘file’) d) os.delete(‘file’)

Answer: c

50. How do you change the file position to an offset value from the start?

a) fp.seek(offset, 0) b) fp.seek(offset, 1)

c) fp.seek(offset, 2) d) none of the mentioned

Answer: a

1. What happens if no arguments are passed to the seek function?

a) file position is set to the start of file

b) file position is set to the end of file

c) file position remains unchanged


d) error

Answer: d

176
PYTHON PROGRAMMING III-BSC[CS]

UNIT-5
DATABASE PROGRAMMING IN PYTHON

INTRODUCTION :

 Database programming involves creating, managing, and interacting with databases to


store, retrieve, and manipulate data.
 Databases are crucial components in software development, providing a structured and
organized way to store and manage information.
 Here's a brief introduction to key concepts in database programming:

Databases:
 A structured collection of data organized for efficient storage, retrieval, and update.
 Examples include relational databases (e.g., MySQL, PostgreSQL, SQLite) and NoSQL
databases (e.g., MongoDB, Cassandra).
Relational Databases:
 Organize data into tables with rows and columns.
 Use SQL (Structured Query Language) for data definition, manipulation, and control.
 Ensure data integrity through relationships and constraints.

SQL (Structured Query Language):


 Standardized language for interacting with relational databases.
 Enables operations like querying, inserting, updating, and deleting data.

Tables and Fields:


 Data in a relational database is organized into tables (relations).
 Tables consist of rows (records) and columns (attributes/fields).

Primary Keys and Foreign Keys:


Primary Key: A unique identifier for each record in a table.

Foreign Key: Establishes a link between tables, ensuring referential integrity.

Data Modeling:
 The process of designing the structure of a database.
 Involves defining tables, relationships, and constraints.

Normalization:
 The process of organizing data to eliminate redundancy and improve data integrity.
 Reduces data anomalies by breaking tables into smaller, related tables.

Indexes:

 Data structures that improve the speed of data retrieval operations.


 Accelerate query performance by providing quick access to specific data.
177
PYTHON PROGRAMMING III-BSC[CS]

Programming Aspects:

1. Database Management Systems (DBMS):

 Software that manages databases.


 Examples include MySQL, PostgreSQL, Microsoft SQL Server.
2. Database Connectivity:

 APIs (Application Programming Interfaces) or drivers enable programming languages to


interact with databases.
 Common interfaces include JDBC for Java, SQLAlchemy for Python, and ADO.NET for
.NET languages.

Transaction Management:

 Transactions ensure the atomicity, consistency, isolation, and durability (ACID


properties) of database operations.
Error Handling and Security:

 Robust error handling is essential to manage exceptions during database operations.


 Implement security measures to protect against unauthorized access and SQL injection
attacks.
Tools and Frameworks:
1. SQLite:
Lightweight, embedded relational database often used for smaller applications.

2. MySQL, PostgreSQL, Oracle, SQL Server:


Common enterprise-grade relational database management systems.

3. MongoDB, Cassandra, Redis:


Examples of NoSQL databases suitable for specific use cases.

4. ORMs (Object-Relational Mappers):


Libraries like SQLAlchemy (Python), Hibernate (Java), and Entity Framework (.NET) provide a
higher-level abstraction for database interaction.
Database programming is a fundamental skill for software developers, enabling them to create
applications that efficiently handle and manage data. Whether working with traditional relational
databases or newer NoSQL solutions, understanding database concepts is crucial for building
scalable and robust systems.
 In Python, you can interact with databases using various libraries and modules.
 One of the most popular libraries for database programming in Python is sqlite3, which
is included in the standard library for working with SQLite databases.
 Additionally, there are third-party libraries like SQLAlchemy that provide a more

178
PYTHON PROGRAMMING III-BSC[CS]
abstracted and ORM (Object-Relational Mapping) approach, allowing you to work with
different database systems more seamlessly.
 Here's a brief overview of using sqlite3 and SQLAlchemy in Python:
Using sqlite3 (SQLite Database):
 SQLite is a lightweight, file-based relational database.
 Python's sqlite3 module provides a simple way to interact with SQLite databases.
import sqlite3
# Connect to a database (or create if it doesn't exist)
conn = sqlite3.connect('example.db')

Python SQL

 Python can be used in database applications.

 One of the most popular databases is MySQL.

Install MySQL Driver

 Python needs a MySQL driver to access the MySQL database.


 In this concepts we will use the driver "MySQL Connector".
 We recommend that you use PIP to install "MySQL Connector".
 PIP is most likely already installed in your Python environment.
 Navigate your command line to the location of PIP, and type the following:
 Download and install "MySQL Connector":
 C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip
install mysql-connector-python

Now you have downloaded and installed a MySQL driver

Test MySQL Connector

To test if the installation was successful, or if you already have "MySQL Connector" installed, create
a Python page with the following content:

demo_mysql_test.py:

import mysql.connector

If the above code was executed with no errors, "MySQL Connector" is installed and ready to be used.

179
PYTHON PROGRAMMING III-BSC[CS]
Create Connection

Start by creating a connection to the database.

Use the username and password from your MySQL database:

demo_mysql_connection.py:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

print(mydb)

Now we can start querying the database using SQL statements.

Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:

ExampleGet your own Python Server

create a database named "mydatabase":

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

180
PYTHON PROGRAMMING III-BSC[CS]
mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

Check if Database Exists


You can check if a database exist by listing all databases in your system by using the "SHOW
DATABASES" statement:

Example

Return a list of your system's databases:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)

how to create a Creating a Table in database using sql in python?(5 marks)

181
PYTHON PROGRAMMING III-BSC[CS]
To create a table in MySQL, use the "CREATE TABLE" statement.

Make sure you define the name of the database when you create the connection

Example

Create a table named "customers":

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address


VARCHAR(255))")

If the above code was executed with no errors, you have now successfully created a table.

Primary Key
When creating a table, you should also create a column with a unique key for each record.

This can be done by defining a PRIMARY KEY.

example:

mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT


PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
Insert Into Table
To fill a table in MySQL, use the "INSERT INTO" statement.

182
PYTHON PROGRAMMING III-BSC[CS]
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = ("John", "Highway 21")

mycursor.execute(sql, val)

mydb.commit()
print(mycursor.rowcount, "record inserted.")
output:

1 record inserted.

Insert Multiple Rows


To insert multiple rows into a table, use the executemany() method.

The second parameter of the executemany() method is a list of tuples, containing the data you want
to insert:

Example : mycursor.executemany(sql, val)

mydb.commit().
It is required to make the changes, otherwise no changes are made to the table.
Select From a Table

183
PYTHON PROGRAMMING III-BSC[CS]
To select from a table in MySQL, use the "SELECT" statement:
Example :
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
Select With a Filter
When selecting records from a table, you can filter the selection by using the "WHERE" statement:

mycursor = mydb.cursor()

sql = "SELECT * FROM customers WHERE address ='Park Lane 38'"

mycursor.execute(sql)

Sort the Result


 Use the ORDER BY statement to sort the result in ascending or descending order.
 The ORDER BY keyword sorts the result ascending by default. To sort the result in
descending order, use the DESC keyword.
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name"

mycursor.execute(sql)

Delete Record
We can delete records from an existing table by using the "DELETE FROM" statement:

mycursor = mydb.cursor()

sql = "DELETE FROM customers WHERE address = 'Mountain 21'"

mycursor.execute(sql)

Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
mycursor = mydb.cursor()

sql = "DROP TABLE customers"

mycursor.execute(sql)

Update Table
184
PYTHON PROGRAMMING III-BSC[CS]

You can update existing records in a table by using the "UPDATE" statement:

mycursor = mydb.cursor()

sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"

mycursor.execute(sql)

Python - Databases and SQL

 The Python programming language has powerful features for database programming.
Python supports various databases like SQLite, MySQL, Oracle, Sybase, PostgreSQL,
etc.
 Python also supports Data Definition Language (DDL), Data Manipulation Language
(DML) and Data Query Statements.
 The Python standard for database interfaces is the Python DB-API. Most Python database
interfaces adhere to this standard.
 Here is the list of available Python database interfaces: Python Database Interfaces and
APIs.
 You must download a separate DB API module for each database you need to access.
 In this chapter we will see the use of SQLite database in python programming language.
It is done by using python’s inbuilt, sqlite3 module.
 You should first create a connection object that represents the database and then create
some cursor objects to execute SQL statements.
How to Connect To Database in python programming ? or Explain the basic
database operations?(5 marks)

 Following Python code shows how to connect to an existing database.


 If the database does not exist, then it will be created and finally a database object will be
returned.

#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";

185
PYTHON PROGRAMMING III-BSC[CS]

 Here, you can also supply database name as the special name :memory: to create
adatabase in RAM.

 Now, let's run the above program to create our database test.db in the current directory.
 You can change your path as per your requirement. Keep the above code in sqlite.py file
and execute it as shown below.
 If the database is successfully created, then it will display the following message.

$chmod +x sqlite.py
$./sqlite.py
Open database successfully

Create a Table

Following Python program will be used to create a table in the previously created database.

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute('''CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS
CHAR(50), SALARY REAL);''')
print "Table created successfully";

conn.close()

When the above program is executed, it will create the COMPANY table in your test.db and it
will display the following messages −

Opened database successfully


Table created successfully

Insert Operation

Following Python program shows how to create records in the COMPANY table created in the
above example.
186
PYTHON PROGRAMMING III-BSC[CS]

#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (1, 'Paul', 32, 'California', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");
conn.commit()
print "Records created successfully";
conn.close()

When the above program is executed, it will create the given records in the COMPANY table
and it will display the following two lines −

Opened database successfully


Records created successfully

Select Operation

Following Python program shows how to fetch and display records from the COMPANY table
created in the above example.

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";
187
PYTHON PROGRAMMING III-BSC[CS]

cursor = conn.execute("SELECT id, name, address, salary from COMPANY")


for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


conn.close()

When the above program is executed, it will produce the following result.

Opened database successfully


ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

188
PYTHON PROGRAMMING III-BSC[CS]
Update Operation

Following Python code shows how to use UPDATE statement to update any record and then
fetch and display the updated records from the COMPANY table.

#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1")
conn.commit
print "Total number of rows updated :", conn.total_changes
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


conn.close()

When the above program is executed, it will produce the following result.

Opened database successfully


Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy

189
PYTHON PROGRAMMING III-BSC[CS]
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully


Delete Operation

Following Python code shows how to use DELETE statement to delete any record and then fetch
and display the remaining records from the COMPANY table.

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("DELETE from COMPANY where ID = 2;")


conn.commit()
print "Total number of rows deleted :", conn.total_changes

cursor = conn.execute("SELECT id, name, address, salary from COMPANY")


for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


conn.close()

When the above program is executed, it will produce the following result.

190
PYTHON PROGRAMMING III-BSC[CS]
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

Examples of using Database adapters mysql in python

To interact with a MySQL database in Python, you can use the mysql-connector library, which is
a MySQL driver for Python. Before using this library, you need to install it using:

pip install mysql connector python


Here's an example of how to use the mysql-connector library to connect to a MySQL database,
create a table, insert data, and perform a simple query:
import mysql.connector

# Connect to the MySQL server conn = mysql.connector.connect(

host='your_host',

user='your_username',

password='your_password',

database='your_database' )

# Create a cursor object to interact with the database

191
PYTHON PROGRAMMING III-BSC[CS]
cursor = conn.cursor()

# Create a table
create_table_query = ''' CREATE TABLE IF NOT EXISTS users (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50),

email VARCHAR(100) ) '''

cursor.execute(create_table_query)

# Insert data into the table

insert_data_query = ''' INSERT INTO users (username, email) VALUES (%s, %s) '''

user_data = ('john_doe', 'john.doe@example.com')

cursor.execute(insert_data_query, user_data) # Commit the changes to the database


conn.commit()
# Perform a query

select_query = '''

SELECT * FROM users ''' cursor.execute(select_query) #

Fetch and print the results results = cursor.fetchall() for row in results: print(row) # Close the
cursor and connection cursor.close() conn.close()
Make sure to replace 'your_host', 'your_username', 'your_password', and 'your_database' with
your MySQL server details. This example demonstrates connecting to a MySQL server, creating
a table, inserting data, and querying the data. Adjust the queries and table structure based on your
specific use case.

REs and python


Explain the concept of REs and python(5 marks)
 In Python, the re module provides support for regular expressions (regex).
 Regular expressions are powerful tools for pattern matching and text manipulation.

192
PYTHON PROGRAMMING III-BSC[CS]
 Here's an overview of using regular expressions in Python with the re module:

1.Importing the re module:

import re

Basic Pattern Matching:

• The re.search() function is used to search for a pattern within a string.

Example :

• import re
• pattern = r"apple"
• text = "I like apples and oranges."
• match = re.search(pattern, text)
• if match:
• print("Pattern found:", match.group())

Pattern Matching with Groups:

• You can use groups to capture specific parts of the match.

match = re.search(pattern, text)

if match:

year, month, day = match.groups()

• print(f"Year: {year}, Month: {month}, Day: {day}")

Findall:

• The re.findall() function returns a list of all occurrences of a pattern in a string.


numbers = re.findall(pattern, text)

Substitution:

• The re.sub() function is used for replacing patterns in a string.


• updated_text = re.sub(pattern, "10", text)
• print("Updated Text:", updated_text)

Flags:

193
PYTHON PROGRAMMING III-BSC[CS]

• Flags can be used to modify the behavior of the regex pattern.


• import re
• pattern = r"apple"
• text = "I like Apples and oranges."
• # Case-insensitive search
• match = re.search(pattern, text, re.IGNORECASE)
• if match:
• print("Pattern found:", match.group())

 These are just basic examples, and regular expressions can become quite complex.
 The module provides a variety of functions and options for working with regular
re
expressions.
 If you're dealing with more complex pattern matching, it's often helpful to refer to the
Python module documentation for a comprehensive understanding of the available
re
features and options: Python re module documentation.

SPECIAL SYMBOLS AND CHARACTERS IN SQL IN PYTHON

what are the special characters using SQL in python ?(5 marks)
 In SQL, and consequently when working with SQL databases in Python, there are
certain special symbols and characters that have specific meanings or uses.
 Here are some commonly used special symbols and characters in SQL:
Semicolon (;):

• Used to terminate SQL statements. In Python, when executing SQL queries, it's
common to end each query with a semicolon
Single Quote (' or "):

• Used to define string literals. In SQL, string values must be enclosed in single quotes.

• conn = sqlite3.connect('example.db')

cursor.execute("INSERT INTO my_table (name) VALUES ('John');")

Double Quote (" or ’):

• Used to define identifiers (e.g., table or column names). The usage may vary
depending on the database system.

ursor.execute('CREATE TABLE "my_table" ("id" INTEGER PRIMARY KEY, "name"


TEXT);')

194
PYTHON PROGRAMMING III-BSC[CS]
Wildcards (% and _):

• Used in LIKE clauses for pattern matching. % represents zero or more characters, and
_ represents a single character.

cursor.execute("SELECT * FROM my_table WHERE name LIKE 'J%';")

 These are just a few examples, and the usage of special symbols can vary depending
on the specific SQL database system you are working with (e.g., SQLite, MySQL,
PostgreSQL).
 Always refer to the documentation of the specific database system for details on its
SQL syntax and conventions.
QUESTION BANK
ONE MARK
CHOOSE THE CORRECT ANSWER.

1. Who developed Python Programming Language?


a) Wick van Rossum b) Rasmus Lerdorf
c) Guido van Rossum d) Niene Stom Answer: c.
2. Which type of Programming does Python support?
a) object-oriented programming b) structured programming
c) functional programming d) all of the mentioned Answer: d
3. Is Python case sensitive when dealing with identifiers?
a) no b) yes c) machine dependent d) none of the mentioned Answer: b
4. Which of the following is the correct extension of the Python file?
a) .python b) .pl c) .py d) .p Answer: c
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 Answer: a.
6. All keywords in Python are in
a) Capitalized b) lower case
c) UPPER CASE d) None of the mentioned Answer: d
7. What will be the value of the following Python expression?

4+3%5

a) 7 b) 2 c) 4 d) 1 Answer: a

8. Which of the following is used to define a block of code in Python language?


a) Indentation b) Key
c) Brackets d) All of the mentioned Answer: a
9. Which keyword is used for function in Python language?
a) Function b) def c) Fun d) Define Answer: b
10. Which of the following character is used to give single-line comments in Python?

195
PYTHON PROGRAMMING III-BSC[CS]
a) // b) # c) ! d) /* Answer: b

11. What will be the output of the following Python code?

i=1
while True:
if i%3 == 0:
break
print(i)

i+=1

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

12. Which of the following functions can help us to find the version of python that we are
currently working on?
a) sys.version(1) b) sys.version(0)
c) sys.version( d) sys.version Answer: d

13. Python supports the creation of anonymous functions at runtime, using a construct called

a) pi b) anonymous c) lambda d) none of the mentioned


Answer: c.

14. What is the order of precedence in python?


a) Exponential, Parentheses, Multiplication, Division, Addition, Subtraction
b) Exponential, Parentheses, Division, Multiplication, Addition, Subtraction
c) Parentheses, Exponential, Multiplication, Division, Subtraction, Addition
d) Parentheses, Exponential, Multiplication, Division, Addition, Subtraction
Answer: d
15. What will be the output of the following Python code snippet if x=1?

x<<2

a) 4 b) 2 c) 1 d) 8 Answer: a
16. What does pip stand for python?
a) Pip Installs Python b) Pip Installs Packages
c) Preferred Installer Program d) All of the mentioned Answer: c
Explanation: pip is a package manager for python. Which is also called Preferred Installer
Program.
17. Which of the following is true for variable names in Python?
a) underscore and ampersand are the only two special characters allowed
b) unlimited length
c) all private members must have leading and trailing underscores
196
PYTHON PROGRAMMING III-BSC[CS]
d) none of the mentioned
Answer: b

18. What are the values of the following Python expressions?

2**(3**2)
(2**3)**2
2**3**2

a) 512, 64, 512 b) 512, 512, 512


c) 64, 512, 64 d) 64, 64, 64 Answer: a

19. Which of the following is the truncation division operator in Python?


a) | b) // c) / d) % Answer: b

20. What will be the output of the following Python code?

l=[1, 0, 2, 0, 'hello', '', []]


list(filter(bool, l))

197
PYTHON PROGRAMMING III-BSC[CS]
a) [1, 0, 2, ‘hello’, ”, []] b) Error
c) [1, 2, ‘hello’] d) [1, 0, 2, 0, ‘hello’, ”, []]
Answer: c

21. Which of the following functions is a built-in function in python?


a) factorial() b) print()
c) seed() d) sqrt()
Answer: b

22. Which of the following is the use of id() function in python?


a) Every object doesn’t have a unique id b) Id returns the identity of the object
c) All of the mentioned d) None of the mentioned
Answer: b
23. The following python program can work with parameters.

def f(x):
def f1(*args, **kwargs):
print("Sanfoundry")
return x(*args, **kwargs)
return f1

a) any number of b) 0 c) 1 d) 2 Answer: a


24. What will be the output of the following Python function?
min(max(False,-3,-4), 2,7)

a) -4 b) -3 c) 2 d) False Answer: d

25. Which of the following is not a core data type in Python programming?
a) Tuples b) Lists c) Class d) Dictionary

198
PYTHON PROGRAMMING III-BSC[CS]
Answer: c

26. What will be the output of the following Python expression if x=56.236?

print("%.2f"%x)

a) 56.236 b) 56.23 c) 56.0000 d) 56.24

Answer: d

27. Which of these is the definition for packages in Python?


a) A set of main modules b) A folder of python modules
c) A number of files containing Python definitions and statements
d) A set of programs making use of Python modules
Answer: b

28. What will be the output of the following Python function?

len(["hello",2, 4, 6])

a) Error b) 6 c) 4 d) 3
Answer: c

29. What will be the output of the following Python code?

x = 'abcd'
for i in x:
print(i.upper())

a)Abcd b) a b c d c) error d)ABCD

Answer: d

199
PYTHON PROGRAMMING III-BSC[CS]
30. What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the built-in namespace, then the global namespace and finally the local
namespace
b) Python first searches the built-in namespace, then the local namespace and finally the global
namespace
c) Python first searches the local namespace, then the global namespace and finally the built-in
namespace
d) Python first searches the global namespace, then the local namespace and finally the built-in
namespace
Answer: c
31. What will be the output of the following Python code snippet?

for i in [1, 2, 3, 4][::-1]:


print(i, end=' ')

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

Answer: a

32. What will be the output of the following Python statement?

1. >>>"a"+"bc"

a) bc b) abc c) a d) bca

Answer: b
33. Which function is called when the following Python program is executed?

f = foo()
format(f)

a) str() b) format() c) str () d) format ()


View Answer

200
PYTHON PROGRAMMING III-BSC[CS]
Answer: c
34. Which one of the following is not a keyword in Python language?
a) pass b) eval c) assert d) nonlocal Answer: b

35. What will be the output of the following Python code?

1. class tester:
2. def init (self, id):
3. self.id = str(id)
4. id="224"
5.
6. >>>temp = tester(12)
7. >>>print(temp.id)
a) 12 b) 224 c) None d) Error Answer: a

36. What will be the output of the following Python program?

def foo(x):
x[0] = ['def']
x[1] = ['abc']
return id(x)
q = ['abc', 'def']
print(id(q) == foo(q))

a) Error b) None c) False d) True

Answer: d

37. Which module in the python standard library parses options received from the command
line?
a) getarg b) getopt c) main d) os
Answer: b

38. What will be the output of the following Python program?

z=set('abc')
z.add('san')
z.update(set(['p', 'q']))
z

a) {‘a’, ‘c’, ‘c’, ‘p’, ‘q’, ‘s’, ‘a’, ‘n’} b) {‘abc’, ‘p’, ‘q’, ‘san’}

201
PYTHON PROGRAMMING III-BSC[CS]
c) {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’} d) {‘a’, ‘b’, ‘c’, [‘p’, ‘q’], ‘san}

Answer: c

39. What arithmetic operators cannot be used with strings in Python?


a) * b) – c) + d) All of the mentioned

Answer: b
40. What will be the output of the following Python code?

print("abc. DEF".capitalize())

a) Abc. def b) abc. def c) Abc. Def d) ABC. DEF

Answer: a

41. Which of the following statements is used to create an empty set in Python?
a) ( ) b) [ ] c) { } d) set()

Answer: d
42. What will be the value of ‘result’ in following Python program?

list1 = [1,2,3,4]list2 = [2,4,5,6]list3 = [2,6,7,8]result = list()


result.extend(i for i in list1 if i not in (list2+list3) and i not in result)
result.extend(i for i in list2 if i not in (list1+list3) and i not in result)
result.extend(i for i in list3 if i not in (list1+list2) and i not in result)

a) [1, 3, 5, 7, 8] b) [1, 7, 8] c) [1, 2, 4, 7, 8] d) error

Answer: a
43. To add a new element to a list we use which Python command?
a) list1.addEnd(5) b) list1.addLast(5)
c) list1.append(5) d) list1.add(5)
Answer: c
44. What will be the output of the following Python code?

print('*', "abcde".center(6), '*', sep='')

a) * abcde * b) *abcde * c) * abcde* d) * abcde *

Answer: b

45. What will be the output of the following Python code?

1. >>>list1 = [1, 3]
2. >>>list2 = list1
3. >>>list1[0] = 4
4. >>>print(list2) 202
PYTHON PROGRAMMING III-BSC[CS]
a) [1, 4] b) [1, 3, 4] c) [4, 3] d) [1, 3]

Answer: c
46. Which one of the following is the use of function in python?
a) Functions don’t provide better modularity for your application
b) you can’t also create your own functions
c) Functions are reusable pieces of programs
d) All of the mentioned
Answer: c

47. Which of the following Python statements will result in the output: 6?

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

a) A[2][1] b) A[1][2] c) A[3][2] d) A[2][3]

Answer: b
48. What is the maximum possible length of an identifier in Python?
a) 79 characters b) 31 characters
c) 63 characters d) none of the mentioned
Answer: d

203

You might also like