Python Unit 1 to 5- Final
Python Unit 1 to 5- Final
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,
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:
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 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's origins:
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.
These features contribute to Python's popularity and make it a go-to language for a broad
spectrum of applications and industries.
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:
Interpreter:
This is the most frequently used way to run a Python code. Here basically we do the following:
Hello World!
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
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. 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
EXAMPLE :
x=5
y = "John"
print(x)
print(y)
OUTPUT:
5
John
python
# Assigning values to variables
name = "Alice"
age = 30
height = 5.8
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)
Variables do not need to be declared with any particular type, and can even change type after they have
been set.
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.
python
my_variable = 42
My_Variable = "Hello"
MY_VARIABLE = 3.14
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.
Orange
Banana
Cherry
Output Variables
x = "Python is awesome"
print(x)
OUTPUT:
Python is awesome
x = "Python"
y = "is"
z = "awesome"
9
PYTHON PROGRAMMING III-BSC[CS]
print(x, y, z)
OUTPUT:
Python is awesome
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
x=5
y = "John"
print(type(x))
print(type(y))
OUTPUT:
<class 'int'>
<class 'str'>
10
PYTHON PROGRAMMING III-BSC[CS]
Case-Sensitive
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.
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
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:
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 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:
Example:
python
x, y, z = 10, 20, 30
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
This method is also called Ternary operators. So Basic Syntax of a Conditional Operator is:-
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).
#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
14
PYTHON PROGRAMMING III-BSC[CS]
In the another example, we have used one liner if-else conditional statement in Python.
Output
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:
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
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.
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:
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:
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:
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)
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.
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
Explain the Python object with give some examples ?Or how to creating a
python object ?(5 marks)
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.
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
print(Audi.model)
print(Audi.price)
Output:
R8
100000
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:
class Car:
# Class Variable
vehicle = 'car'
# Instance Variable
self.model = model
# Driver Code
Audi = Car("R8")
Audi.setprice(1000000)
print(Audi.getprice())
Output:
1000000
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
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
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
Identity Operators:
python
# is (checks if two variables reference the same object)
result = "hello" is "hello" # 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.).
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:
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
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:
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
python
num_str = "42"
num_int = int(num_str) # Result: 42
31
PYTHON PROGRAMMING III-BSC[CS]
python
python
num_int = 42
num_float = float(num_int) # Result: 42.0
2.Mathematical Functions:
python
result = abs(-5) # Result: 5
python
numbers = [1, 5, 3, 7, 2]
max_value = max(numbers) # Result: 7
3.String Functions:
python
text = "Hello, Python!"
length = len(text) # Result: 14
python
text = "Hello, Python!"
upper_case = text.upper() # Result: 'HELLO, PYTHON!'
3. String Functions:
python
numbers = [1, 2, 3, 4, 5]
length = len(numbers) # Result: 5
python
numbers = [1, 2, 3]
numbers.append(4) # numbers is now [1, 2, 3, 4]
32
PYTHON PROGRAMMING III-BSC[CS]
python
input(prompt): Reads a line from input and returns it as a string.name = input("Enter your name: ")
python
print("Hello, Python!")
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)
34
PYTHON PROGRAMMING III-BSC[CS]
a.system.getversion b.sys.version(1)
c.system.get d.None of the above
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.[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
37
PYTHON PROGRAMMING III-BSC[CS]
38
PYTHON PROGRAMMING III-BSC[CS]
print(x + y)
c.To define a section of a webpage that contains metadata about the document
39
PYTHON PROGRAMMING III-BSC[CS]
Unit-2
Introduction to numbers
How to declare a numbers in python language ?(5 marks)
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:
40
PYTHON PROGRAMMING III-BSC[CS]
1.0
>>> 0.5 * 0.5
0.25Code language: Python (python)
>>> 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:
Just keep this in mind when you perform calculations with floats. And you’ll learn how to handle
situations like this in later tutorials.
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.
For example, in languages like C, C++, and Java, you might declare a double-precision in
python variable like this:
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:
To make the long numbers more readable, you can group digits using underscores, like this:
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)
Note that the underscores in numbers have been available since Python 3.6
Complex numbers
real_part = complex_num.real
imaginary_part = complex_num.imag
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.
Defintion :
In programming,we want to compare a value with another value. To do that, you use comparison
operators.
Bascic Comparision Operators:
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.
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:
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:
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)
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:
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)
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:
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:
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:
The equal to operator (==) compares two values and returns True if the left value is equal to the
right value. Otherwise, it returns False :
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:
46
PYTHON PROGRAMMING III-BSC[CS]
True
>>> 'apple' == 'orange'
FalseCode language: Python (python)
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.
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:
and
or
not
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]
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:
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.
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:
The not operator applies to one condition. And it reverses the result of that condition, True
becomes False and False becomes True.
If the condition is True, the not operator returns False and vice versa.
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:
Here is another example that combines the not and the and operators:
In this example, Python evaluates the conditions based on the following order:
49
PYTHON PROGRAMMING III-BSC[CS]
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:
if condition:
if-blockCode language: Python (python)
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.
For example:
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.
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:
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:
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.
52
PYTHON PROGRAMMING III-BSC[CS]
The following example illustrates you how to use the if...else statement:
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:
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.
if if-condition:
if-block
elif elif-condition1:
elif-block1
elif elif-condition2:
elif-block2
...
else:
else-blockCode language: Python (python)
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 example uses the if...elif..else statement to determine the ticket price based
on the age:
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.
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]
Here we will see the different example to use Python Ternary Operator:
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
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
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.
a, b = 10, 20
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
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
In this example, we are finding the larger number among two numbers using ternary operator in
python3.
a=5
b=7
Output
7 is Greater
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
^
The following program prompts you for your age and determines the ticket price based on it:
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:
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:
7. Logarithmic Functions:
9. Statistical Functions:
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"
my_string = "Python"
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
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
61
PYTHON PROGRAMMING III-BSC[CS]
print("My name is {} and I am {} years old.".format(name, age))
Escape Characters:
You can use escape characters to include special characters in a string, such as newline (\n), tab
(\t), or a backslash (\\).
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:
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:
62
PYTHON PROGRAMMING III-BSC[CS]
Modifying Lists:
my_list[0] = 100
Removing Elements:
List Operations:
List Comprehensions:
Nested Lists:
63
PYTHON PROGRAMMING III-BSC[CS]
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
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:
Accessing Elements:
print(my_tuple[0]) # Output: 1
Immutable Nature:
Unlike lists, tuples cannot be modified once they are created. The following code 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:
tuple1 = (1, 2, 3)
Tuple Methods:
Tuples have limited methods compared to lists due to their immutability. Some common
methods include count() and index():
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)
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]
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:
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:
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:
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
'''
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:
The message is a format string, or f-string in short. Python introduced the f-string in version 3.6.
When you place the string literals next to each other, Python automatically concatenates them
into one string. For example:
Output:
67
PYTHON PROGRAMMING III-BSC[CS]
greeting = 'Good '
time = 'Afternoon'
Output:
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.
How it works:
If you use a negative index, Python returns the character starting from the end of the string. For
example:
+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 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)
68
PYTHON PROGRAMMING III-BSC[CS]
To get the length of a string, you use the len() function. For example:
Output:
Slicing strings
Output:
The str[0:2] returns a substring that includes the character from the index 0 (included) to 2
(excluded).
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.
When want to modify a string, you need to create a new one from the existing string. For
example:
69
PYTHON PROGRAMMING III-BSC[CS]
new_str = 'J' + str[1:]
print(new_str)Code language: Python (python)
Output:
Python String
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 (*):
str3 = "abc"
result = str3 * 3
print(result)
# Output: abcabcabc
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
str1 = "apple"
str2 = "banana"
print(str1 < str2) # Output: True
print(str1 == str2) # Output: False
Slice ([:]):
You can use the len() function to get the length of a string:
text = "Python"
length = len(text)
print(length)
# Output: 6
String Formatting:
Escape Characters:
1. len()
2. str()
3. lower()
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()
72
PYTHON PROGRAMMING III-BSC[CS]
6. title()
8. replace()
9. find(), index()
# Note: If substring is not found, find() returns -1, while index() raises a ValueError.
10. count()
String methods are powerful tools for manipulating and working with text data efficiently.
73
PYTHON PROGRAMMING III-BSC[CS]
QUESTION BANK
ONE MARK
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
74
PYTHON PROGRAMMING III-BSC[CS]
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
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
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?
75
PYTHON PROGRAMMING III-BSC[CS]
a.4 b.5 c576 d.5 Answer: (d) 5
24Amongst which of the following is / are the application areas of Python programming?
25. Amongst which of the following is / are the Numeric Types of Data Types?
Answer: D) All
29.The type() function can be used to get the data type of any object.
32. Amongst which of the following is / are the logical operators in Python?
A. Exponentiation C. Modulus
B. Floor division D. None of the mentioned above
Answer: A) Exponentiation
A. Quotient B. Divisor
B. Remainder D. None of the mentioned above
Answer: C) Remainder
A. append() C.extend()
77
PYTHON PROGRAMMING III-BSC[CS]
B. insert() 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
40.Python Literals is used to define the data that is given in a variable or constant?
A. Decision-making b.Array
B. List d.None of the mentioned above
Answer: A) Decision-making
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.
45.In Python, the break and continue statements, together are called statement.
47.If a condition is true the not operator is used to reverse the logical state?
49. The for loop in Python is used to over a sequence or other iterable objects.
Answer: B) Iterate
50.With the break statement we can stop the loop before it has looped through all the
items?
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.
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).
80
PYTHON PROGRAMMING III-BSC[CS]
a[k] = x Set a[k] to x
Method len(d)
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()).
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()
Method values()
Method update(elem)
Example Code
Live Demo
myDict.update({'fifty' : 50})
print(myDict)
Output
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:
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():
my_dict.clear()
2. copy():
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'}
4.items():
84
PYTHON PROGRAMMING III-BSC[CS]
items = my_dict.items()
5. keys():
keys = my_dict.keys()
6. values():
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'}
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'}
85
PYTHON PROGRAMMING III-BSC[CS]
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'}
del my_dict['key1']
These are just a few examples of the built-in methods for dictionaries in Python.
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.
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.
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:
elif a == b:
else:
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:
else:
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:
elif a == b:
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]
a=2
b = 330
Here's an example of a simple conditional loop using if, elif, and else statements:
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
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.
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.
'''
Output
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
total+=num
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
if num%2 == 0:
print (num)
Output
34
54
78
44
80
Syntax
Parameters
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,
'''
print (list(numbers))
# step is 1 by default, range generated from 10 to 19
numbers = range(10,20)
print (list(numbers))
print (list(numbers))
Output
[0, 1, 2, 3, 4]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[1, 3, 5, 7, 9].
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))
numbers = [34,54,67,21,78]
indices = range(len(numbers))
index: 0 number: 34
index: 1 number: 54
index: 2 number: 67
index: 3 number: 21
index: 4 number: 78
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.
for x in numbers:
print (x)
30
40
94
PYTHON PROGRAMMING III-BSC[CS]
Syntax
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.
count=0
while count<5:
count+=1
95
PYTHON PROGRAMMING III-BSC[CS]
print ("Iteration no. {}".format(count))
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
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
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.
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
else:
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
break
Example
if letter == 'h':
break
var = var -1
if var == 5:
break
Current Letter : P
Current Letter : y
Current Letter : t
98
PYTHON PROGRAMMING III-BSC[CS]
Current variable value : 10
Good bye!
Syntax
continue
Flow Diagram
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
if letter == 'h':
continue
var = var -1
if var == 5:
continue
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
100
PYTHON PROGRAMMING III-BSC[CS]
Current variable value : 3
Good bye!
pass
Example
The following code shows how you can use the pass statement in Python –
for letter in 'Python':
if letter == 'h':
pass
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!
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():
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:
self.current = 1
return self
if self.current <= 5:
result = self.current
self.current += 1
return result
else:
raise StopIteration
my_iterator = MyIterator()
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.
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.
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"
content = file.read()
print(content)
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:
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")
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:
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:
print(content)
The input() function is used to take user input from the console.
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:
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:
106
PYTHON PROGRAMMING III-BSC[CS]
file.write("Hello, World!")
writelines(lines) Method:
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()
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:
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.
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:
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.
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.
This concept covers all the basic I/O functions available in Python.
109
PYTHON PROGRAMMING III-BSC[CS]
Live Demo
#!/usr/bin/python
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([prompt]) function reads one line from standard input and returns it as
a string (removing the trailing newline).
#!/usr/bin/python
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 −
#!/usr/bin/python
This would produce the following result against the entered input −
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.
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])
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).
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.
Once a file is opened and you have one file object, you can get various information
related to that file.
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
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()
115
PYTHON PROGRAMMING III-BSC[CS]
Name of the file: foo.txt
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.
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
Example
#!/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()
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.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
118
PYTHON PROGRAMMING III-BSC[CS]
Syntax
os.remove(file_name)
Example
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.
Syntax
os.mkdir("newdir")
Example
#!/usr/bin/python
import os
119
PYTHON PROGRAMMING III-BSC[CS]
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
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')
#!/usr/bin/python
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as
directories.
121
PYTHON PROGRAMMING III-BSC[CS]
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
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
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()
write()
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)
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)
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.
1 os.close(fd)
2 os.closerange(fd_low, fd_high)
127
PYTHON PROGRAMMING III-BSC[CS]
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()
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
Examples:
output:
myfile.txt
r
False
True
Python program to print number of lines, words and characters in given file.
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'
File Size:
import os
file_path = 'example.txt'
size_in_bytes = os.path.getsize(file_path)
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')
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)
Is a File:
import os
file_path = 'example.txt'
is_file = os.path.isfile(file_path)
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
131
PYTHON PROGRAMMING III-BSC[CS]
Conforming to the UNIX philosophy, the standard I/O streams are file objects.
read_name.py
#!/usr/bin/env python
# read_name.py
import sys
name = ''
sys.stdout.flush()
while True:
c = sys.stdin.read(1)
if c == '\n':
break
name = name + c
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
std_output.py
#!/usr/bin/env python
# std_output.py
import sys
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
134
PYTHON PROGRAMMING III-BSC[CS]
getopt module
argparse module
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.
Example
import sys
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
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])
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
First command line argument is -h which will be used to display the usage help of the program.
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
script_name = sys.argv[0]
arguments = sys.argv[1:]
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()
137
PYTHON PROGRAMMING III-BSC[CS]
B. Create executable file D. None of the mentioned above
5. Amongst which of the following shows the types of function calls in Python?
6. Amongst which of the following is a function which does not have any name?
9. Amongst which of the following is / are the key functions used for file handling in
Python?
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
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.
139
PYTHON PROGRAMMING III-BSC[CS]
A. Special purpose B. General purpose
B. Medium level programming language D.All of the mentioned above
A. Alphabets B. Numbers
B. Special symbols D. All of the mentioned above
20. Amongst which of the following is / are the method used to unpickling data from a
binary file?
print type(type(int))
Answer: (C)
23. What is the output of the following program
y=8
z = lambda x : x * y
print (z(6))
140
PYTHON PROGRAMMING III-BSC[CS]
Answer: (A)
24. What is the output of the following segment :
chr(ord('A'))
Answer: (A)
25. What is called when a function is defined inside a class?
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)
pos = nameList.index("GeeksforGeeks")
142
PYTHON PROGRAMMING III-BSC[CS]
print (pos * 3)
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)
Answer: (C)
Answer: (A)
Answer: (D)
Answer: (B)
143
PYTHON PROGRAMMING III-BSC[CS]
38. What is the output of the following code :
print 9//2
Answer: (C)
i=0
while i < 3:
print i
i++
print i+1
A. if a>=2 : B. if (a >= 2)
42. What keyword would you use to add an alternative condition to an if statement?
A. Yes B. No
C. Dictates what happens before the program starts and after it terminates
144
PYTHON PROGRAMMING III-BSC[CS]
45. A while loop in Python is used for what type of iteration?
A. indefinite B. discriminant
A. TRUE B. FALSE
48. Python programming language allows to use one loop inside another loop known as?
Ans : D
Ans : D
145
PYTHON PROGRAMMING III-BSC[CS]
UNIT -IV
Functions:
1. Definition:
A function is a self-contained block of code that performs a specific task.
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:
1. Definition:
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:
# function body
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:
# function body
pass
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):
"""
"""
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
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]
Built-in functions
Functions defined in built-in modules
User-defined functions
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():
152
PYTHON PROGRAMMING III-BSC[CS]
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.
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.
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.
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
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]
Based on how the arguments are declared while defining a Python function, they are classified
into the following categories −
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:
# function body
# perform operations
def greet():
print("Hello, welcome!")
result = a + b
return result
print(f"{greeting}, {name}!")
def sum_all(*args):
158
PYTHON PROGRAMMING III-BSC[CS]
result = sum(args)
return result
print(f"{key}: {value}")
return result
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(result)
In this example:
159
PYTHON PROGRAMMING III-BSC[CS]
greet_person(name, greeting="Hello") has a default value for the greeting parameter.
If we wanted to alphabetize this list we could pass it to the built-in sorted function:
>>> sorted(fruits)
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)
. ..
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]
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'
>>> lowercase
We passed the lowercase function object to the sorted function (via its key argument):
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).
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
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)
x = df.apply(calc_sum)
print(x)
Parameters
The axis, raw, result_type, and args parameters are keyword arguments.
162
PYTHON PROGRAMMING III-BSC[CS]
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
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.
Algorithm (Steps)
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.
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)
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)
Using a 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
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.
Answer: b
2. What is a database?
a) Organized collection of information that cannot be accessed, updated, and managed
c) Organized collection of data or information that can be accessed, updated, and managed
Answer: C
3. What is DBMS?
a) DBMS is a collection of queries b) DBMS is a high-level language
Answer: d
Answer: b
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
Answer: d
Answer: d
Answer: c
Answer: b
Answer: b
Answer: b
169
PYTHON PROGRAMMING III-BSC[CS]
Answer: a
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
a) infile.read(2) b) infile.read()
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()
f = None
if i > 2:
break
print(f.closed)
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()
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
Answer: a
Answer: a
171
PYTHON PROGRAMMING III-BSC[CS]
Answer: a
Answer: a
a) r b) w c) + d) b Answer:d
b) fileObject.writelines()
c) fileObject.writelines(sequence)
a) fileObject.readlines( sizehint );
b) fileObject.readlines();
c) fileObject.readlines(sequence)
172
PYTHON PROGRAMMING III-BSC[CS]
Answer: a
33. In file handling, what does this terms means “r, a”?
Answer: a
a) Read b) Write
Answer: b
Answer: c
a) Read() b) Readcharacters()
c) Readall() d) Readchar()
Answer: a
a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()
173
PYTHON PROGRAMMING III-BSC[CS]
Answer: b
a) write()
b) writecharacters()
c) writeall()
d) writechar()
Answer: a
b) writelines()
c) writestatement()
d) writefullline()
Answer: a
a) Close()
b) Stop()
c) End()
d) Closefile()
Answer: a
a) Yes
b) No
c) Machine dependent
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
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)
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
a) close(fp) b) fclose(fp)
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
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
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)
Answer: a
Answer: d
176
PYTHON PROGRAMMING III-BSC[CS]
UNIT-5
DATABASE PROGRAMMING IN PYTHON
INTRODUCTION :
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.
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:
Programming Aspects:
Transaction Management:
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
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
demo_mysql_connection.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
180
PYTHON PROGRAMMING III-BSC[CS]
mycursor = mydb.cursor()
Example
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)
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
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
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.
example:
182
PYTHON PROGRAMMING III-BSC[CS]
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
output:
1 record inserted.
The second parameter of the executemany() method is a list of tuples, containing the data you want
to insert:
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()
mycursor.execute(sql)
mycursor.execute(sql)
Delete Record
We can delete records from an existing table by using the "DELETE FROM" statement:
mycursor = mydb.cursor()
mycursor.execute(sql)
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
mycursor = mydb.cursor()
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)
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)
#!/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 −
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";
When the above program is executed, it will create the given records in the COMPANY table
and it will display the following two lines −
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]
When the above program is executed, it will produce the following result.
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
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"
When the above program is executed, it will produce the following result.
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
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";
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
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:
host='your_host',
user='your_username',
password='your_password',
database='your_database' )
191
PYTHON PROGRAMMING III-BSC[CS]
cursor = conn.cursor()
# Create a table
create_table_query = ''' CREATE TABLE IF NOT EXISTS users (
username VARCHAR(50),
cursor.execute(create_table_query)
insert_data_query = ''' INSERT INTO users (username, email) VALUES (%s, %s) '''
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.
192
PYTHON PROGRAMMING III-BSC[CS]
Here's an overview of using regular expressions in Python with the re module:
import re
Example :
• import re
• pattern = r"apple"
• text = "I like apples and oranges."
• match = re.search(pattern, text)
• if match:
• print("Pattern found:", match.group())
if match:
Findall:
Substitution:
Flags:
193
PYTHON PROGRAMMING III-BSC[CS]
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.
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')
• Used to define identifiers (e.g., table or column names). The usage may vary
depending on the database system.
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.
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.
4+3%5
a) 7 b) 2 c) 4 d) 1 Answer: a
195
PYTHON PROGRAMMING III-BSC[CS]
a) // b) # c) ! d) /* Answer: b
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
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
2**(3**2)
(2**3)**2
2**3**2
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
def f(x):
def f1(*args, **kwargs):
print("Sanfoundry")
return x(*args, **kwargs)
return f1
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)
Answer: d
len(["hello",2, 4, 6])
a) Error b) 6 c) 4 d) 3
Answer: c
x = 'abcd'
for i in x:
print(i.upper())
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?
Answer: a
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)
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
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
def foo(x):
x[0] = ['def']
x[1] = ['abc']
return id(x)
q = ['abc', 'def']
print(id(q) == foo(q))
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
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
Answer: b
40. What will be the output of the following Python code?
print("abc. DEF".capitalize())
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?
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?
Answer: b
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]]
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