0% found this document useful (0 votes)
3 views13 pages

Python Assignment

The document covers various fundamental concepts in Python, including input/output functions, string and list operations, tuples, recursive functions, object-oriented programming, the Tkinter module for GUI, SQLite for database management, and data manipulation using Pandas and Matplotlib for visualization. Each section provides explanations, examples, and key features relevant to the topics discussed. This serves as a comprehensive guide for students in the BCA 4th semester.

Uploaded by

Musfera Kulsum
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)
3 views13 pages

Python Assignment

The document covers various fundamental concepts in Python, including input/output functions, string and list operations, tuples, recursive functions, object-oriented programming, the Tkinter module for GUI, SQLite for database management, and data manipulation using Pandas and Matplotlib for visualization. Each section provides explanations, examples, and key features relevant to the topics discussed. This serves as a comprehensive guide for students in the BCA 4th semester.

Uploaded by

Musfera Kulsum
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

PYTHON ASSIGNMENT- BCA 4th SEM

Q1. Explain Input and Output functions of python. [10M]

Input Functions in Python: Input functions are used to take data from the user
during program execution.
input() Function: The input() function reads data entered by the user through the
keyboard.
1. Displays a prompt message (optional).
2. Waits for the user to type something and press Enter.
3. Returns the entered value as a string.
Syntax: variable = input("prompt message")
Example: name = input("Enter your name: ")
print("Hello", name)
By default, input() always returns a string, even if the user enters a number.

To use numeric values, you must convert the input using type casting:

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


print(age + 5)
Output Functions in Python: Output functions are used to display information to
the user.
print() Function: The print() function is used to display data on the screen.
Syntax: print(object1, object2, ..., sep=' ', end='\

n') Parameters:
 sep: Separator between multiple values (default is space ' ').

 end: What to print at the end (default is newline \n).


Example: 1. print("Hello", "World")

2. print("2026", "04", "28", sep="-")

3. print("Hello", end=" ")


print("World")

Q2. Discuss Operations on Strings. [10M]


Python provides a rich set of operations on strings that allow you to manipulate and
work with text efficiently.
1. Creating Strings:
s1 = "Hello"
s2 = 'World'
s3 = '''Multi-line string'''

2. Accessing Characters (Indexing): Each character in a string has an index


starting from 0.
s = "Python"
print(s[0]) # P
print(s[5]) # n

3. String Slicing: Slicing extracts a part of a string.


s = "Python"
print(s[0:3]) # Pyt
print(s[2:]) # thon
print(s[:4]) # Pyth
print(s[::2]) # Pto (step = 2)

4. String Concatenation: Joining two or more strings using +.


a = "Hello"
b = "World"
print(a + " " + b) # Hello World.

5. Membership Operators: Check if a substring exists in a


string. s = "Python"
print("Py" in s) # True
print("Java" not in s) # True

Q3. Discuss Operations on Lists. [10M]

1. Creation of Lists

Lists are created using square brackets [].


my_list = [1, 2, 3, 4]
2. Accessing Elements

 Indexing (starts from

0): my_list[0] # Output: 1


3. Slicing
Extract a portion of the list:
my_list[1:3] # Output: [2, 3]
4. Updating Elements

Lists are mutable, so values can be changed:


my_list[1] = 10 # [1, 10, 3, 4]
5. Adding Elements

append() – adds to end:

my_list.append(5)
insert() – adds at specific position:

my_list.insert(1, 20)
extend() – adds multiple elements:

my_list.extend([6, 7])

Q4. Discuss Operations on Tuples. [10M]

1. Creation of Tuples

Tuples are created using parentheses ():

t = (1, 2, 3, 4)

2. Accessing Elements

 Indexing (starts from

0): t[0]# Output: 1

3. Slicing

Extract part of a tuple:

t[1:3] # Output: (2, 3)

4. Concatenation

Combine two tuples using +:

t1 = (1, 2)
t2 = (3, 4)

t1 + t2 # Output: (1, 2, 3, 4)

5. Repetition

Repeat elements using *:

t = (1, 2)

t * 2 # Output: (1, 2, 1, 2)

Q5. Explain Recursive Function in python[10M]

A recursive function in Python is a function that calls itself to solve a problem.


Instead of solving the entire problem at once, it breaks it into smaller subproblems
of the same type.

Example: Factorial Using Recursion

The factorial of a number 𝑛is:

𝑛! = 𝑛 × (𝑛 − 1)!

def factorial(n):

if n == 0: # Base case

return 1

else:

return n * factorial(n-1) # Recursive call

print(factorial(5)) # Output: 120

Another Example: Fibonacci Series

def fibonacci(n):

if n <= 1:

return n
else:

return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(6)) # Output: 8
Q6. What is Object Oriented Programming. Explain Classes and Objects with
suitable example. [10M]

Object-Oriented Programming (OOP) is a programming paradigm that organizes


code around objects rather than just functions and logic. It models real-world entities,
making programs easier to design, understand, and maintain.
In OOP, data and the operations that work on that data are bundled together into a
single unit called an object.
A class is like a blueprint or template used to create objects. It defines:

 Attributes (variables) → properties of an object


 Methods (functions) → actions an object can perform

An object is an instance of a class. It represents a real-world entity and contains:

 Actual values for attributes

 Ability to use methods defined in the class


Program: # Define a class

class Car:

def init (self, brand, color):


[Link] = brand # attribute
[Link] = color # attribute
def drive(self): # method
print([Link] + " car is driving")
# Create objects
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")
# Access attributes and methods
print([Link]) # Output: Toyota
print([Link]) # Output: Blue
[Link]() # Output: Toyota car is driving
Q7. Explain Tkinter Module in python. Write about windows widgets and
their uses. [10M]
Tkinter is Python’s standard library for creating Graphical User Interfaces
(GUI). It provides tools to build windows, buttons, labels, text boxes, and other
interactive components.
It is a wrapper around the Tk GUI toolkit, making it easy to design desktop
applications.
Features of Tkinter

 Built-in (no need to install separately)

 Simple and beginner-friendly

 Platform-independent (runs on Windows, macOS, Linux)

 Supports event-driven programming


Widgets

Widgets are GUI elements (components) like buttons, labels, text boxes, etc.,
that are placed inside a window.
Uses:

1. Label: Displays text or images.


label = [Link](root, text="Hello World")
[Link]()
2. Button: Used to perform an action when
clicked. def click():
print("Button clicked")

button = [Link](root, text="Click Me", command=click)


[Link]()

3. Entry: Single-line text input


field. entry = [Link](root)
[Link]()

4. Text: Multi-line text area.


text = [Link](root, height=5, width=30)
[Link]()

5. Frame: Container to organize


widgets. frame = [Link](root)
[Link]()
Q8. Explain SQLite Module.[10M]

The SQLite3 module is a built-in library in Python that allows you to work with SQLite
databases. SQLite is a lightweight, serverless database engine that stores data in a
single file on disk.
Think of it as a simple way to use SQL (Structured Query Language) without
needing a separate database server like MySQL or PostgreSQL.
Key Features of SQLite3

Serverless – no installation or configuration required


File-based – database is stored in a .db file
Lightweight – ideal for small to medium applications
ACID compliant – ensures reliable transactions
Cross-platform – works on Windows, macOS, Linux
How to Use SQLite3 in Python

1. Import the module


import sqlite3
2. Connect to a database

conn = [Link]("[Link]")
Creates the database file if it doesn’t exist
Returns a connection object
3. Create a cursor
cursor = [Link]()
Cursor is used to execute SQL commands
4. Create a table
[Link]("""
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT, age
INTEGER
) """)
5. Insert data

[Link]("INSERT INTO students (name, age) VALUES (?, ?)", ("Alice", 20))
[Link]()
? is a placeholder to prevent SQL injection
commit() saves changes
6. Retrieve data

[Link]("SELECT * FROM students")


rows = [Link]()
for row in
rows:
print(row)
7. Update data
[Link]("UPDATE students SET age = ? WHERE name = ?", (21, "Alice"))
[Link]()
8. Delete data

[Link]("DELETE FROM students WHERE name = ?", ("Alice",))


[Link]()
9. Close the connection
[Link]()

Q9. Explain Pandas.[10M]

Pandas is a powerful open-source Python library used for data analysis and
manipulation. It’s one of the most popular tools in the Data Science and is built on
top of NumPy, making it fast and efficient for handling structured data.
What Pandas Does

Pandas helps you work with data in a way that’s similar to spreadsheets (like Excel)
or SQL tables. You can:
Load data (CSV, Excel, databases, etc.)
Clean and preprocess messy data
Analyze and summarize datasets
Filter, group, and transform data
Visualize basic trends
Core Data Structures

1. Series
A Series is like a single column of data.
import pandas as pd
s = [Link]([10, 20, 30])
print(s)
Think of it as a labeled list.
2. DataFrame

A DataFrame is a table (rows + columns), like a spreadsheet.


data = {
"Name": ["Alice", "Bob"],
"Age": [25, 30]
}

df = [Link](data)
print(df)
Common Operations

1. Load data

df = pd.read_csv("[Link]")

2. View data
[Link]() # first 5 rows
[Link]() # structure of data
[Link]() # summary statistics

3. Select columns
df["Age"]
4. Filter rows

df[df["Age"] > 25]

5. Add new column


df["Age_plus_1"] = df["Age"] + 1

6. Grouping
[Link]("Age").mean()
Why Pandas Is Popular:

Easy to learn and use


Handles large datasets efficiently

Integrates with libraries like NumPy, Matplotlib, and Scikit-learn Widely


used in analytics, finance, machine learning, and research Example

import pandas as pd
df = pd.read_csv("[Link]") #
Average age
avg_age = df["Age"].mean() #
Students older than 20
older_students = df[df["Age"] > 20]
print(avg_age)
print(older_students)

Q10. Matplotlib Library. [10M]

Matplotlib Library in Python

Matplotlib is a popular Python library used for data visualization. It helps programmers
create graphs, charts, and plots to represent data visually. It is widely used in data
science, machine learning, scientific research, and analytics. ◻

Matplotlib +1

Why Matplotlib is Used


Matplotlib is used to:
Display data in graphical form
Analyze trends and patterns
Create professional charts
Generate reports and visual presentations
It can create:

Line charts
Bar graphs
Pie charts
Histograms
Scatter plots
3D plots and more ◻
[Link] +1
Installing Matplotlib
Bash
pip install matplotlib
Importing Matplotlib
Usually, we import its pyplot module:
Python

import [Link] as plt

pyplot provides functions similar to MATLAB for creating plots easily. ◻


GeeksforGeeks +1
Simple Example:

Line Plot

import [Link] as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

[Link](x, y)
[Link]("Simple Line Graph")
[Link]("X Values")
[Link]("Y Values")
[Link]()
Output

A line graph connecting the points: (1,10), (2,20), (3,25), (4,30)


Common Types of Plots
1. Line Plot

Used to show trends over time.


[Link](x, y)
2. Bar Chart

Used to compare categories.


students = ["A", "B", "C"]
marks = [80, 75, 90]
[Link](students, marks)
[Link]()

3. Pie Chart

sizes = [40, 30, 20, 10]

[Link](sizes)
[Link]()
4. Histogram

Shows frequency distribution.


data = [1,2,2,3,3,3,4,4,5]
[Link](data)
[Link]()
5. Scatter Plot

Shows relationship between two variables.


x = [1,2,3,4]
y = [5,7,8,10]
[Link](x, y)
[Link]()
Matplotlib is one of the most important Python libraries for visualization. It helps
convert raw data into meaningful graphs and charts, making analysis easier and
more understandable. It is commonly used with libraries like NumPy and Pandas.

You might also like