0% found this document useful (0 votes)
6 views11 pages

Ai Practical Python Code

The document contains various Python programs demonstrating basic functionalities such as grade assignment, list operations, area calculation, voting eligibility check, and data visualization using libraries like Matplotlib and Pandas. It also includes explanations of Python libraries, data types, and key programming concepts like sequences and membership operators. Additionally, it highlights differences between list methods and provides notes on tuples and Python commands.
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)
6 views11 pages

Ai Practical Python Code

The document contains various Python programs demonstrating basic functionalities such as grade assignment, list operations, area calculation, voting eligibility check, and data visualization using libraries like Matplotlib and Pandas. It also includes explanations of Python libraries, data types, and key programming concepts like sequences and membership operators. Additionally, it highlights differences between list methods and provides notes on tuples and Python commands.
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

Set 1

1. # Program to assign grade based on percentage

percentage = float(input("Enter your percentage: "))

if percentage >= 90:

grade = "A"

elif percentage >= 80:

grade = "B"

elif percentage >= 70:

grade = "C"

elif percentage >= 60:

grade = "D"

elif percentage >= 50:

grade = "E"

else:

grade = "F"

print("Your grade is:", grade)

2. # Program to create a list and display its elements

# Creating a list

my_list = [10, 20, 30, 40, 50]

# Displaying list elements

print("The list elements are:")

for item in my_list:

print(item)
set 2

1. # Program to calculate the area of a triangle

base = float(input("Enter the base of the triangle: "))

height = float(input("Enter the height of the triangle: "))

area = 0.5 * base * height

print("The area of the triangle is:", area)

2. import numpy as np

from scipy import stats

# Program to calculate mean, median, and mode

# Taking list input from user

data = list(map(float, input("Enter numbers separated by spaces: ").split()))

# Converting to numpy array

arr = [Link](data)

mean = [Link](arr)

median = [Link](arr)

mode = [Link](arr, keepdims=True)

print("Mean:", mean)

print("Median:", median)

print("Mode:", [Link][0])
set 3

1. # Program to check voting eligibility

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

if age >= 18:

print("You are eligible to vote.")

else:

print("You are not eligible to vote.")

2. import [Link] as plt

# Coordinates

x = [2, 9]

y = [5, 10]

# Plotting the line chart

[Link](x, y)

# Adding labels and title

[Link]("X-axis")

[Link]("Y-axis")

[Link]("Line Chart from (2,5) to (9,10)")

# Display the chart

[Link]()
set 4

1. print("The sum is:", sum(range(1, 11)))

2. import [Link] as plt

# Given points
x = [2, 9, 8, 5, 6]
y = [5, 10, 3, 7, 8]

# Scatter plot
[Link](x, y)

# Labels and title


[Link]("X-axis")
[Link]("Y-axis")
[Link]("Scatter Plot of Given Points")

# Display the chart


[Link]()
Set 5

1. # Program to check if a number is positive, negative, or zero

num = float(input("Enter a number: "))

if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")

2. import [Link] as plt

# Given data
subjects = ["eng", "sci", "maths", "ai"]
marks = [89, 87, 78, 90]

# Creating bar chart


[Link](subjects, marks)

# Adding labels and title


[Link]("Subjects")
[Link]("Marks")
[Link]("Marks of Subjects")

# Display the chart


[Link]()
Set 6

1. # Program to assign grade based on percentage

percentage = float(input("Enter your percentage: "))

if percentage >= 90:


grade = "A"
elif percentage >= 80:
grade = "B"
elif percentage >= 70:
grade = "C"
elif percentage >= 60:
grade = "D"
elif percentage >= 50:
grade = "E"
else:
grade = "F"

print("Your grade is:", grade)

2. import pandas as pd

# Read CSV file (change the file path to your actual file location)
df = pd.read_csv("C:/Users/YourName/Documents/[Link]")

# Display the entire data


print("CSV File Data:")
print(df)

# Display basic information about the file


print("\nInformation about the CSV file:")
print([Link]())

# Display basic statistics


print("\nStatistical Summary:")
print([Link]())
Set 7

1. # Program to add elements of two lists

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

result = []

for i in range(len(list1)):
[Link](list1[i] + list2[i])

print("List 1:", list1)


print("List 2:", list2)
print("Sum of elements:", result)

2. import [Link] as plt

# Data
x = ["food", "rent", "shopping", "education", "others"]
values = [20, 30, 25, 35, 50]

# Plotting the pie chart


[Link](figsize=(8, 8))
[Link](values, labels=x, autopct='%1.1f%%', startangle=140)
[Link]("Expenses Distribution")
[Link]()
Set 8

1. # Creating a list
my_list = ["apple", "banana", "cherry", "date", "elderberry"]

# Displaying list elements


print("The elements of the list are:")
for item in my_list:
print(item)

2. import [Link] as plt

# Points
x = [5, 10]
y = [10, 20]

# Plotting the line chart


[Link](x, y, marker='o', linestyle='-', color='b')
[Link]("Line Chart Example")
[Link]("X-axis")
[Link]("Y-axis")
[Link](True)
[Link]()
Q1. What is Python libraries and packages?

Python libraries and packages are collections of reusable code (functions, classes, and
modules) that make programming easier.

 A library is a bundle of useful functions.


 A package is a directory that contains multiple modules or libraries.
They help you avoid writing code from scratch.

Q2. What is the use of NumPy?

NumPy (Numerical Python) is used for:

 Handling large numerical data efficiently


 Working with arrays and matrices
 Performing mathematical, statistical, and scientific calculations
It is faster and more powerful than Python’s built-in lists.

Q3. What is Pandas?

Pandas is a Python library used for data analysis and data manipulation.
It provides two main structures:

 Series (1-dimensional data)


 DataFrame (2-dimensional data like tables)
It is widely used to clean, analyze, and organize data.

Q4. What is Matplotlib?

Matplotlib is a plotting library used to create graphs and charts such as line charts, bar
charts, pie charts, scatter plots, etc.
It helps visualize data in a clear and meaningful way.

Q5. What is OpenCV?

OpenCV (Open Source Computer Vision Library) is used for image processing and
computer vision.
It can perform tasks like:

 Reading and editing images


 Detecting faces and objects
 Working with videos
 Applying filters and transformations

Q8. Difference between append and extend

 append() – adds one element to the end of the list.


 extend() – adds all elements of another list/iterable to the list.

Q9. Difference between pop and remove

 pop() – removes element by index and returns it.


 remove() – removes element by value (first match), does not return it.

Q10. Difference between sort and sorted

 sort() – sorts the list in place (changes original list).


 sorted() – returns a new sorted list (original remains unchanged).

Q11. Note on index() function

 index() returns the position of the first occurrence of a given value in a list.
 Raises error if value not found.

Q12. Membership operators

 in → checks if a value exists in a sequence.


 not in → checks if a value does not exist.

Q13. What do you mean by slicing?

 Slicing is used to take a part of a list/string using [start:stop:step].

Q14. Difference between break and continue

 break – exits the loop completely.


 continue – skips to the next iteration of the loop.
Q17. Write a note on sequences

A sequence in Python is an ordered collection of items. Each item has a position (index).
Examples: strings, lists, tuples.
Sequences support indexing, slicing, repetition, and membership tests.

Q18. Write a note on Python commands

Python commands are instructions we give to Python to perform tasks.


Examples include printing output, taking input, assigning values, using loops, conditions, and
calling functions.
They form the basic building blocks of a Python program.

Q19. Data Types

Data types specify the kind of value a variable can store.


Common Python data types are:

 int (whole numbers)


 float (decimal numbers)
 str (text)
 bool (True/False)
 list, tuple, set, dict (collections)

Q20. Short note on tuples

A tuple is an ordered, immutable (unchangeable) collection of items.


It is written using parentheses: (1, 2, 3).
Tuples are faster than lists and are used for fixed data that should not be modified.

You might also like