0% found this document useful (0 votes)
2 views

python programs

The document provides a series of Python programming tasks, including printing personal information, generating patterns, calculating averages, and manipulating lists. It also covers basic statistics, data visualization with matplotlib, and reading CSV files using pandas. Additionally, it includes image processing tasks with PIL to display images and identify their shapes.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python programs

The document provides a series of Python programming tasks, including printing personal information, generating patterns, calculating averages, and manipulating lists. It also covers basic statistics, data visualization with matplotlib, and reading CSV files using pandas. Additionally, it includes image processing tasks with PIL to display images and identify their shapes.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

1. To print personal information like Name, Father’s Name, Class, School Name.

name = "John Doe"

fathers_name = "Mr. Richard Doe"

class_name = "10th Grade"

school_name = "Greenwood High School"

# Printing the personal information

print("Name:", name)

print("Father's Name:", fathers_name)

print("Class:", class_name)

print("School Name:", school_name)

2. To print the following patterns using multiple print commands-


n = 5 # Number of rows

for i in range(1, n + 1):

print('*' * i)

-------------------------------------

n = 5 # Height of the pyramid

for i in range(1, n + 1):

print(' ' * (n - i) + '*' * (2 * i - 1))

---------------------------------------

n = 5 # Number of rows

for i in range(n, 0, -1):

print('*' * i)

---------------------------------------

n = 5 # Half of the diamond's height

# Top half of the diamond

for i in range(1, n + 1):

print(' ' * (n - i) + '*' * (2 * i - 1))

---------------------------------------------

# Bottom half of the diamond

for i in range(n - 1, 0, -1):

print(' ' * (n - i) + '*' * (2 * i - 1))


n = 5 # Size of the square

for i in range(n):

print('*' * n)

------------------------------------

n = 5 # Number of rows

for i in range(1, n + 1):

print(''.join(str(x) for x in range(1, i + 1)))

n = 5 # Height of the pyramid

for i in range(1, n + 1):

# Print spaces

print(' ' * (n - i), end='')

# Print increasing numbers

for j in range(1, i + 1):

print(j, end='')

# Print decreasing numbers

for j in range(i - 1, 0, -1):

print(j, end='')

print()

--------------------------------------------------------------------------------------------------------------------------------------

3. To find square of number 7

number = 7 square = number ** 2

print("The square of", number, "is", square)

--------------------------------------------------------------------------------------------------------------------------------------

4. To calculate average marks of 3 subjects.

arks1 = float (input("Enter marks for Subject 1: "))

marks2 = float (input("Enter marks for Subject 2: "))

marks3 = float (input("Enter marks for Subject 3: "))

Average = (marks1 + marks2 + marks3) / 3

print ("The average marks are:", average)

--------------------------------------------------------------------------------------------------------------------------------------
5. Create a list in Python of children selected for science quiz with following namesArjun, Sonakshi,
Vikram, Sandhya, Sonal, Isha, Kartik

Perform the following tasks on the list in sequence-

○ Print the whole list

○ Delete the name “Vikram” from the list

○ Add the name “Jay” at the end

○ Remove the item which is at the second position.

# Creating the list of selected children

children = ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sonal", "Isha", "Kartik"]

# 1. Print the whole list

print("Original List:", children)

# 2. Delete the name "Vikram" from the list

children.remove("Vikram")

print("\nList after removing 'Vikram':", children)

# 3. Add the name "Jay" at the end

children.append("Jay")

print("\nList after adding 'Jay' at the end:", children)

# 4. Remove the item at the second position (index 1)

del children[1]

print("\nList after removing the item at the second position:", children)

--------------------------------------------------------------------------------------------------------------------------------

6. Create a list num=[23,12,5,9,65,44]

○ print the length of the list

○ print the elements from second to fourth position using positive indexing

○ print the elements from position third to fifth using negative indexing.

#Creating the list

num = [23, 12, 5, 9, 65, 44]

# 1. Print the length of the list

print("Length of the list:", len(num))

# 2. Print the elements from second to fourth position using positive indexing

# Positive indexing: Start from index 1 (second element) to index 3 (fourth element)
print("Elements from second to fourth position:", num[1:4])

# 3. Print the elements from third to fifth position using negative indexing

# Negative indexing: Start from -4 (third element from the end) to -2 (fifth element from the end)

print("Elements from third to fifth position using negative indexing:", num[-4:-1])

7. Create a list List_1=[10,20,30,40]. Add the elements [14,15,12] using extend

function. Now sort the final list in ascending order and print it.

# Initial list

List_1 = [10, 20, 30, 40]

# Using extend to add elements [14, 15, 12]

List_1.extend([14, 15, 12])

# Sorting the list in ascending order

List_1.sort()

# Printing the final sorted list

print(List_1)

8. Write a python Program to check if a person can vote or not?

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

if age >= 18:

Print ("You are eligible to vote!")

Else: print ("Sorry, you are not eligible to vote yet.")

9. Input a number and check if the number is positive, negative or zero and display an appropriate
message.

10. To print first 10 natural numbers.

i=1

while i <= 10:

print(i)

i += 1

11. Program to find the sum of all numbers stored in a list

Define a list of numbers

numbers = [1, 2, 3, 4, 5]

# Initialize a variable to hold the sum

total_sum = 0
# Iterate through the list and add each number to the sum

for num in numbers:

total_sum += num

# Print the result

print("The sum of all numbers in the list is:", total_sum)

11.Write a program to add the elements of the two lists.

List1 = [7, 5.7, 21, 18, 8/3]


List2 = [9, 15, 6.2, 1/3,11]
# printing original lists
print ("list1 : " + str(List1))
print ("list2 : " + str(List2))
newList = []
for n in range(0, len(List1)):
newList.append(List1[n] + List2[n])
print(newList)

12. Write a program to calculate mean, median and mode using Numpy

import numpy as np

from scipy import stats

def calculate_statistics(data):

mean = np.mean(data)

median = np.median(data)

mode = stats.mode(data).mode[0] # Get the mode value

return mean, median, mode

# Example data

data = [1, 2, 2, 3, 4, 4, 4, 5, 6]

# Calculate statistics

mean, median, mode = calculate_statistics(data)

print(f"Mean: {mean}")

print(f"Median: {median}")

print(f"Mode: {mode}")

13. Write a program to display line chart from (2,5) to (9,10).

import matplotlib.pyplot as plt


# Define the points

x_values = [2, 9]

y_values = [5, 10]

# Create the line chart

plt.plot(x_values, y_values, marker='o') # 'o' marks the points on the line

# Set the title and labels

plt.title('Line Chart from (2, 5) to (9, 10)')

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

# Set the x and y axis limits

plt.xlim(0, 10)

plt.ylim(0, 15)

# Display the grid

plt.grid()

# Show the plot

plt.show()

14. Write a program to display a scatter chart for the following points (2,5),

(9,10),(8,3),(5,7),(6,18).

import matplotlib.pyplot as plt

# Define the points

points = [(2, 5), (9, 10), (8, 3), (5, 7), (6, 18)]

x, y = zip(*points) # Unzip the points into x and y coordinates

# Create the scatter chart

plt.figure(figsize=(8, 6))

plt.scatter(x, y, color='blue', marker='o')

# Add titles and labels


plt.title('Scatter Chart of Points')

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

# Show grid

plt.grid(True)

# Display the plot

plt.show()

● Read csv file saved in your system and display 10 rows.

import pandas as pd

# Replace 'your_file.csv' with the path to your CSV file

file_path = 'your_file.csv'

# Read the CSV file

data = pd.read_csv(file_path)

# Display the first 10 rows

print(data.head(10))

● Read csv file saved in your system and display its information

import pandas as pd

# Replace 'your_file.csv' with the path to your CSV file

file_path = 'your_file.csv'

# Read the CSV file

data = pd.read_csv(file_path)

# Display basic information about the DataFrame


print("DataFrame Information:")

print(data.info())

# Optionally, display the first few rows of the DataFrame

print("\nFirst 5 Rows:")

print(data.head())

15. Write a program to read an image and display using Python

from PIL import Image

import matplotlib.pyplot as plt

# Replace 'your_image.jpg' with the path to your image file

image_path = 'your_image.jpg'

# Read the image

image = Image.open(image_path)

# Display the image

plt.imshow(image)

plt.axis('off') # Hide the axis

plt.show()

16. Write a program to read an image and identify its shape using Python

from PIL import Image

# Replace 'your_image.jpg' with the path to your image file

image_path = 'your_image.jpg'

# Read the image

image = Image.open(image_path)

# Get the image dimensions

width, height = image.size

# Print the dimensions

print(f"Image Shape: {height} x {width} (Height x Width)")

You might also like