0% found this document useful (0 votes)
2 views40 pages

Python Sem

The document provides an overview of Python programming, covering its definition, basic data types, algorithms, variables, input/output operations, operators, and control structures such as loops and conditional statements. It explains the object-oriented approach in Python, including classes, objects, methods, exception handling, and file handling, along with examples. Additionally, it highlights the advantages of Python's features and its applications in various fields.

Uploaded by

Rahul Rathod
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views40 pages

Python Sem

The document provides an overview of Python programming, covering its definition, basic data types, algorithms, variables, input/output operations, operators, and control structures such as loops and conditional statements. It explains the object-oriented approach in Python, including classes, objects, methods, exception handling, and file handling, along with examples. Additionally, it highlights the advantages of Python's features and its applications in various fields.

Uploaded by

Rahul Rathod
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

a) What is Python programming language?

Python is a high-level, interpreted, and general-purpose programming


language used for web development, data analysis, artificial intelligence, and
automation.

b) Define an algorithm in computer programming.

An algorithm is a step-by-step procedure or set of instructions used to solve


a problem or perform a task.

c) What are the different basic data types in Python?

Basic data types in Python include:

int (Integer)

Float (Decimal number)

str (String)

bool (Boolean)

d) What is the purpose of a variable in Python?

A variable is used to store data values in memory for later use in a program.

Example:

x = 10

e) Which function is used to take input from the user in Python?

The input() function is used to take input from the user.

Example:

name = input("Enter your name: ")

f) What is the difference between = and == operators?

= Operator == Operator
Assignment operator --Comparison operator

Assigns value to variable --Compares two values

Example: x = 5

x == 5

g) What is a Boolean value?

A Boolean value represents either True or False.

h) Name the conditional statements used in Python.

The conditional statements in Python are:

if if-else

if-elif-else

i) What is the purpose of a for loop?

A for loop is used to repeat a block of code multiple times.

Example:

for i in range(5):

print(i)

j) Define a list in Python.

A list is an ordered collection of multiple items that can store different data
types.

Example:

my_list = [1, 2, 3, "Python"]

k) What is the difference between logical and bitwise operators?


Logical Operators Bitwise Operators Work on Boolean values Work on binary
numbers Examples: and, or, not Examples: &,'

L) What is a module in Python?

A module is a file containing Python functions and variables that can be


imported into another program.

Example: math module.

m) What is exception handling?

Exception handling is a method of handling runtime errors using try and


except blocks.

n) What is an object in Object-Oriented Programming (OOP)?

An object is an instance of a class that contains data and methods.

o) Mention one application of Python in Pharmacoinformatics.

One application of Python in Pharmacoinformatics is drug discovery, where it


is used to analyze molecular data and predict drug behavior. a) What is
Python programming language?
2. Explain Python data types, variables,
input/output operations, and basic operators
with suitable examples.
Python is a high-level, interpreted, object-oriented programming language known for its
simple syntax and readability. Every value in Python belongs to a specific data type, and
variables are used to store these values. Python also provides built-in functions for taking input
from users and displaying output. Operators are used to perform various operations on data.

1. Python Data Types


A data type specifies the kind of value stored in a variable and determines the operations that
can be performed on it.

Major Data Types in Python


Data
Description Example
Type

int Integer numbers 25, -10

float Decimal numbers 3.14, 25.6

complex Complex numbers 4+3j

str Sequence of characters "Python"

bool Boolean values True, False

Ordered mutable
list [1,2,3]
collection

Ordered immutable
tuple (1,2,3)
collection

Unordered unique
set {1,2,3}
elements

{"A":10,"B":
dict Key-value pairs
20}
Example Program
a = 20
b = 3.5
c = "Hello"
d = True
e = [10,20,30]

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>

2. Variables in Python
A variable is a named memory location used to store data values.

Python is dynamically typed, meaning the programmer does not need to declare the variable
type explicitly.

Syntax
variable_name = value

Examples
name = "John"
age = 22
salary = 45000.50

Rules for Naming Variables


 Must start with a letter or underscore (_)
 Cannot start with a number
 Can contain letters, digits and underscores
 Cannot contain spaces
 Cannot use Python keywords
Valid
student_name = "Ram"
_marks = 80
x1 = 50

Invalid
2name = "Ram"
class = 10
student name = "Ram"

Dynamic Typing Example


x = 100
print(x)

x = "Python"
print(x)

Output
100
Python

The same variable can store different data types.

3. Input and Output Operations


Python provides built-in functions to accept input and display output.

Input Operation
The input() function is used to accept data from the user.

Syntax
variable = input("Message")

Example:

name = input("Enter your name: ")


print(name)

Output
Enter your name: Alice
Alice

Taking Integer Input


Since input() returns a string, conversion is required.

age = int(input("Enter age: "))


print(age)

Taking Float Input


salary = float(input("Enter salary: "))
print(salary)

Output Operation
The print() function displays information on the screen.

Syntax
print(value)

Example

print("Welcome to Python")

Output

Welcome to Python

Printing Multiple Values


name = "Amit"
age = 21

print(name, age)

Output

Amit 21

Formatted Output using f-string


name = "Amit"
marks = 95

print(f"{name} scored {marks} marks")

Output

Amit scored 95 marks

4. Basic Operators in Python


Operators perform operations on variables and values.

A. Arithmetic Operators
Used for mathematical calculations.

Operat Exampl
Meaning
or e

+ Addition a+b

- Subtraction a-b

Multiplicati
* a*b
on

/ Division a/b

% Modulus a%b

Floor
// a//b
Division

** Exponent a**b

Example

a = 10
b = 3

print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a//b)
print(a**b)

Output

13
7
30
3.3333
1
3
1000

B. Comparison (Relational) Operators


Used to compare values.

Operat
Meaning
or

== Equal to

!= Not equal

> Greater than

< Less than

Greater than or
>=
equal

<= Less than or equal

Example

a = 10
b = 20

print(a==b)
print(a<b)
print(a>b)

Output
False
True
False

C. Logical Operators
Used to combine conditions.

Operat
Meaning
or

Both conditions
and
true

or At least one true

Reverse
not
condition

Example

a = 10
b = 20

print(a>5 and b>5)


print(a>15 or b>10)
print(not(a>5))

Output

True
True
False

D. Assignment Operators
Used to assign values.

Operat Exampl
or e

= x=5
Operat Exampl
or e

+= x+=2

-= x-=2

*= x*=2

/= x/=2

Example

x = 10
x += 5
print(x)

Output

15

Advantages of Python Data Types and


Variables
 Easy to declare and use.
 Dynamic typing reduces coding effort.
 Supports multiple built-in data structures.
 Efficient memory management.
 Suitable for scientific computing, web development, and AI
applications.
3. Describe Boolean values, conditional
execution, loops, lists, and list processing in
Python with example programs.
Python is a high-level, interpreted programming language that provides simple and powerful
constructs for decision making, repetition of tasks, and data storage. Boolean values help in
logical decision-making, conditional statements control program flow, loops execute
statements repeatedly, and lists store multiple values efficiently. Together, these concepts form
the foundation of Python programming.

1. Boolean Values in Python


A Boolean value represents one of two logical states:

 True
 False

Boolean values are mainly used in decision making and loop control.

Syntax
variable = True
variable = False

Example Program
x = 10
y = 20

print(x < y)
print(x > y)
print(x == y)

Output
True
False
False

Here, each comparison returns a Boolean value.


Boolean Operators
Operat
Meaning
or

and Both conditions must be true

At least one condition must


or
be true

not Reverses the Boolean value

Example
a = 10
b = 5

print(a > b and b > 2)


print(a < b or b > 2)
print(not(a > b))

Output

True
True
False

2. Conditional Execution (Decision Making)


Conditional execution allows Python to execute different blocks of code depending on whether a
condition is True or False.

Python uses if, if-else, and if-elif-else statements.

A. if Statement
Executes code only if the condition is true.

Syntax
if condition:
statement

Example
age = 20

if age >= 18:


print("Eligible to vote")

Output

Eligible to vote

B. if-else Statement
Used when there are two possible outcomes.

Syntax
if condition:
statement1
else:
statement2

Example
num = 7

if num % 2 == 0:
print("Even")
else:
print("Odd")

Output

Odd

C. if-elif-else Statement
Used when multiple conditions are checked.

Syntax
if condition1:
statement1

elif condition2:
statement2

else:
statement3

Example
marks = 82

if marks >= 90:


print("Grade A")

elif marks >= 75:


print("Grade B")

else:
print("Grade C")

Output

Grade B

3. Loops in Python
Loops are used to execute a block of code repeatedly until a condition becomes false.

Python supports:

 for loop
 while loop

A. for Loop
Used for iterating over sequences such as lists, strings, tuples, and ranges.

Syntax
for variable in sequence:
statements

Example
for i in range(1,6):
print(i)

Output
1
2
3
4
5

Loop Through a String


word = "Python"

for letter in word:


print(letter)

Output

P
y
t
h
o
n

B. while Loop
Executes as long as the condition remains true.

Syntax
while condition:
statements

Example
i = 1

while i <= 5:
print(i)
i = i + 1

Output

1
2
3
4
5
Loop Control Statements
break
Terminates the loop immediately.

for i in range(10):

if i == 5:
break

print(i)

Output

0
1
2
3
4

continue
Skips the current iteration.

for i in range(5):

if i == 2:
continue

print(i)

Output

0
1
3
4

4. Lists in Python
A list is an ordered, mutable collection of multiple elements stored in a single variable.

Lists can contain different data types.


Syntax
list_name = [item1, item2, item3]

Example

numbers = [10,20,30,40]

Characteristics of Lists
 Ordered collection
 Mutable (can be modified)
 Allows duplicate values
 Stores multiple data types

Example Program
fruits = ["Apple","Mango","Orange"]

print(fruits)
print(fruits[0])

Output

['Apple', 'Mango', 'Orange']


Apple

Accessing List Elements


marks = [80,85,90]

print(marks[1])

Output

85

Modifying Lists
marks = [80,85,90]
marks[1] = 95

print(marks)

Output

[80, 95, 90]

Adding Elements
Using append()

numbers = [1,2,3]

[Link](4)

print(numbers)

Output

[1,2,3,4]

Removing Elements
Using remove()

numbers = [1,2,3,4]

[Link](3)

print(numbers)

Output

[1,2,4]

5. List Processing in Python


List processing refers to performing operations such as traversal, searching, counting,
updating, sorting, and summing elements of a list.
Traversing a List
numbers = [10,20,30,40]

for i in numbers:
print(i)

Output

10
20
30
40

Finding Sum of List Elements


numbers = [10,20,30,40]

total = sum(numbers)

print(total)

Output

100

Finding Maximum Element


numbers = [5,12,8,20]

print(max(numbers))

Output

20

Finding Minimum Element


numbers = [5,12,8,20]

print(min(numbers))

Output

5
Sorting a List
numbers = [40,10,20,5]

[Link]()

print(numbers)

Output

[5,10,20,40]

Searching an Element
numbers = [10,20,30,40]

if 30 in numbers:
print("Found")

Output

Found

List Comprehension (Simple List Processing


Method)
List comprehension provides a concise way to create new lists.

Syntax
new_list = [expression for variable in sequence]

Example
square = [x*x for x in range(1,6)]

print(square)

Output

[1,4,9,16,25]
Advantages of Lists
 Store multiple values in one variable.
 Easy insertion and deletion of elements.
 Supports indexing and slicing.
 Can store heterogeneous data.
 Useful for data analysis and scientific computing.

Applications
 Student record management
 Inventory systems
 Scientific data analysis
 Machine learning datasets
 Web applications
 Database result storage

4. Explain the Object-Oriented Approach in


Python, including classes, objects, methods,
exception handling, and file handling with
examples.
Python is an object-oriented programming (OOP) language that organizes programs around
objects rather than functions alone. OOP improves code reusability, modularity,
maintainability, and security by grouping data and functions together into classes. Python also
provides exception handling to manage runtime errors and file handling to store and retrieve
data permanently.

1. Object-Oriented Approach (OOP) in Python


The Object-Oriented Approach is a programming paradigm in which programs are designed
using classes and objects.

In OOP:

 Class acts as a blueprint.


 Object is an instance of a class.
 Methods define the behavior of objects.
 Attributes store the properties of objects.

Example from Real Life

 Class: Student
 Objects: Rahul, Priya, Amit
 Attributes: Name, Roll Number, Marks
 Methods: Display(), CalculateGrade()

Thus, one class can create many objects.

Advantages of OOP
 Promotes code reusability.
 Easy maintenance and debugging.
 Provides modular programming.
 Supports real-world modeling.
 Makes large programs easier to manage.

2. Class in Python
A class is a user-defined data type that contains variables (attributes) and functions (methods).
Syntax
class ClassName:
statements

Example
class Student:

name = "Rahul"

def display(self):
print([Link])

Here,

 Student is the class.


 name is an attribute.
 display() is a method.

3. Object in Python
An object is an instance of a class that occupies memory and can access class members.

Syntax
object_name = ClassName()

Example Program
class Student:

name = "Rahul"

def display(self):
print([Link])

s1 = Student()

[Link]()

Output
Rahul

Here,
 Student is the class.
 s1 is the object.

4. Methods in Python
A method is a function defined inside a class that performs operations on object data.

Methods always include self as the first parameter.

Syntax
class ClassName:

def method_name(self):
statements

Example Program
class Calculator:

def add(self, a, b):


print(a+b)

c = Calculator()

[Link](10,20)

Output
30

The __init__() Constructor Method


The constructor initializes object data automatically when an object is created.

Syntax
class ClassName:

def __init__(self):
statements
Example
class Student:

def __init__(self, name):


[Link] = name

def display(self):
print([Link])

s = Student("Amit")

[Link]()

Output
Amit

5. Exception Handling in Python


An exception is a runtime error that interrupts normal execution of a program.

Examples:

 Division by zero
 Invalid input
 File not found
 Index out of range

Python handles exceptions using try-except blocks.

Syntax
try:
statements

except:
statements

Example Program
try:

a = 10
b = 0

print(a/b)
except ZeroDivisionError:

print("Division by zero is not allowed")

Output
Division by zero is not allowed

Instead of terminating abruptly, the program handles the error gracefully.

try-except-else-finally
Python also supports else and finally blocks.

Syntax
try:
statements

except:
statements

else:
statements

finally:
statements

Example
try:

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

except ValueError:

print("Invalid input")

else:

print("Valid input")

finally:

print("Program finished")

The finally block executes whether an exception occurs or not.


Advantages of Exception Handling
 Prevents program crashes.
 Improves reliability.
 Makes debugging easier.
 Handles unexpected errors efficiently.
 Provides user-friendly error messages.

6. File Handling in Python


A file is used to store data permanently on secondary storage.

Python provides built-in functions for reading and writing files.

Opening a File
Syntax
file_object = open("filename","mode")

Example

file = open("[Link]","r")

File Modes
Mod
Meaning
e

r Read

w Write

a Append

x Create new
Mod
Meaning
e

file

rb Read binary

wb Write binary

Writing to a File
file = open("[Link]","w")

[Link]("Hello Python")

[Link]()

The text Hello Python is stored in the file.

Reading a File
file = open("[Link]","r")

data = [Link]()

print(data)

[Link]()

Output
Hello Python

Appending Data
file = open("[Link]","a")

[Link]("\nWelcome")

[Link]()

The file becomes:

Hello Python
Welcome

Using with Statement


Using with automatically closes the file after use.

Syntax
with open("[Link]","r") as file:
print([Link]())

This is the preferred method for file handling.

Applications of File Handling


 Student record systems
 Banking applications
 Hospital management systems
 Inventory management
 Data analysis
 Log file generation

Summary Table
Concept Description

Class Blueprint for creating objects

Object Instance of a class

Method Function inside a class

Initializes object
Constructor
automatically

Exception
Handles runtime errors
Handling

File Handling Reads and writes permanent


Concept Description

data

Advantages of Object-Oriented Programming


 Reusable code through classes.
 Better organization of programs.
 Easier maintenance.
 Real-world problem modeling.
 Improves scalability and flexibility.

5. Explain Modules, Packages, String Methods,


List Methods, and Exceptions in Python with
suitable examples
Python provides a large number of built-in modules and packages that make programming
easier by allowing code reuse and organization. It also includes powerful string methods and
list methods for data manipulation. Exception handling enables programmers to detect and
handle runtime errors gracefully, making programs more reliable and user-friendly.

1. Modules in Python
A module is a file containing Python code such as variables, functions, and classes that can be
imported and reused in another program.

Using modules avoids rewriting the same code and promotes code reusability.

Syntax
import module_name

or

from module_name import function_name


Example 1: Importing a Module
import math

print([Link](25))
print([Link](5))

Output
5.0
120

Here, math is a built-in module that provides mathematical functions.

Example 2: Importing Specific Function


from math import sqrt

print(sqrt(49))

Output
7.0

Advantages of Modules
 Code reusability
 Better organization
 Easy maintenance
 Reduced program size
 Faster development

2. Packages in Python
A package is a collection of related modules stored inside a directory.

Packages help organize large projects into smaller and manageable parts.

A package usually contains an __init__.py file.


Structure of a Package
MyPackage/

__init__.py

[Link]

[Link]

Syntax
import package_name.module_name

Example
Suppose calculator is a package containing [Link].

from calculator import addition

[Link](10,20)

This imports the addition module from the calculator package.

Advantages of Packages
 Organizes large programs
 Avoids name conflicts
 Improves readability
 Simplifies code management
 Encourages modular programming

3. String Methods in Python


A string is a sequence of characters enclosed within quotes.

Python provides many built-in methods for string manipulation.


Creating a String
name = "Python"

Common String Methods


Method Description

Converts to
upper()
uppercase

Converts to
lower()
lowercase

capitalize Capitalizes first


() letter

Capitalizes every
title()
word

strip() Removes spaces

replace() Replaces substring

Finds substring
find()
position

split() Splits string into list

count() Counts occurrences

Returns string
len()
length

Example Program
text = "python programming"

print([Link]())
print([Link]())
print([Link]("python","Java"))
print(len(text))

Output
PYTHON PROGRAMMING
Python programming
Java programming
18

Using split()
text = "Apple Mango Orange"

print([Link]())

Output
['Apple', 'Mango', 'Orange']

Using count()
text = "banana"

print([Link]("a"))

Output
3

4. List Methods in Python


A list is an ordered and mutable collection that stores multiple values.

Python provides several built-in methods for manipulating lists.

Creating a List
numbers = [10,20,30]

Common List Methods


Metho
Description
d

append
Adds element at end
()

insert() Inserts element at


Metho
Description
d

position

remove Removes specified


() element

pop() Removes last element

sort() Sorts list

reverse
Reverses list
()

Counts element
count()
occurrence

index() Returns position

extend(
Adds another list
)

clear() Removes all elements

Example: append()
numbers = [10,20,30]

[Link](40)

print(numbers)

Output
[10,20,30,40]

Example: insert()
numbers = [10,20,40]

[Link](2,30)

print(numbers)

Output
[10,20,30,40]
Example: remove()
numbers = [10,20,30]

[Link](20)

print(numbers)

Output
[10,30]

Example: sort()
numbers = [40,10,30,20]

[Link]()

print(numbers)

Output
[10,20,30,40]

Example: reverse()
numbers = [1,2,3,4]

[Link]()

print(numbers)

Output
[4,3,2,1]

5. Exceptions in Python
An exception is an error that occurs during program execution and interrupts the normal flow of
the program.

Python provides exception handling to prevent program termination.


Common Exceptions
Exception Cause

ZeroDivisionErr
Division by zero
or

ValueError Invalid input

Wrong data
TypeError
type

IndexError Invalid list index

FileNotFoundErr File does not


or exist

Undefined
NameError
variable

try-except Statement
Syntax
try:
statements

except ExceptionName:
statements

Example Program
try:

a = 10
b = 0

print(a/b)

except ZeroDivisionError:

print("Cannot divide by zero")

Output
Cannot divide by zero
Handling Invalid Input
try:

age = int(input("Enter age: "))

except ValueError:

print("Please enter numbers only")

If the user enters text instead of a number, the exception is handled safely.

try-except-else-finally
Syntax
try:
statements

except:
statements

else:
statements

finally:
statements

Example
try:

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

except ValueError:

print("Invalid input")

else:

print("Valid input")

finally:

print("Program Ended")

The finally block always executes, whether an exception occurs or not.


Advantages of Exception Handling
 Prevents sudden program termination.
 Makes programs more reliable.
 Improves debugging.
 Provides user-friendly error messages.
 Ensures smooth program execution.

Applications
 Scientific computing
 Web development
 Banking software
 Data analysis
 Automation scripts
 File processing systems

Summary Table
Topic Purpose

Reuse code stored in a


Module
file

Organize multiple
Package
modules

String
Manipulate text data
Methods

List Methods Manipulate list elements

Handle runtime errors


Exceptions
safely

You might also like