0% found this document useful (0 votes)
5 views14 pages

Python Programs For Practical File Class 11

The document provides a comprehensive set of Python programming exercises covering various fundamental concepts such as data handling, flow control, string manipulation, list manipulation, tuples, and dictionaries. Each exercise includes specific tasks such as calculating areas, swapping numbers, generating random integers, and performing arithmetic operations. The exercises are designed to enhance programming skills through practical coding challenges.

Uploaded by

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

Python Programs For Practical File Class 11

The document provides a comprehensive set of Python programming exercises covering various fundamental concepts such as data handling, flow control, string manipulation, list manipulation, tuples, and dictionaries. Each exercise includes specific tasks such as calculating areas, swapping numbers, generating random integers, and performing arithmetic operations. The exercises are designed to enhance programming skills through practical coding challenges.

Uploaded by

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

Python Fundamentals

1) Wap to obtain length and bredth of a rectangle and calculate its area.
2) Wap to input two numbers and swap them.
3) Wap to input three numbers and swap them as this: 1st number becomes the 2nd number, 2nd number
becomes the 3rd number and 3rd number becomes the first number.
4) Wap to enter two integers and perform all arithmetic operations on them.

Data Handling

5) Wap to generate two random integers between 450 and 950. Print these numbers along with their
average.
import random
num1 = [Link](450, 950)-450
num2 = [Link](450, 950)-450
average = (num1 + num2) / 2

print("First number:", num1)


print("Second number:", num2)
print("Average:", average)

6) Wap to given a list containing these values [22,13,28,13,22,25,7,13,25]. Write code to calculate mean,
median and mode of this list.
7) Wap to obtain x,y,z from user and calculate expression: 4x4 + 3y3 +9z +6π .

ANSWER  import math


x = int(input("Enter x: "))
y = int(input("Enter y: "))
z = int(input("Enter z: "))
res = 4 * x ** 4 + 3 * y ** 3 + 9 * z + 6 * [Link]
print("Result =", res)
Output
Enter x: 2
Enter y: 3
Enter z: 5
Result = 208.84955592153875
8) Wap to take year as input and check if it is leap year or not.

y = int(input("Enter year to check: "))

print(y % 4 and "Not a Leap Year" or "Leap Year")

Flow of Control

9) Wap to take three integers and print the largest of the three Make use of only if statement.
10) Wap to print whether a given character is an uppercase or a lowercase character or a digit or any other
character.
11) Wap to print table of a number, say 5.
12) Wap to calculate the factorial of a number.

13) Wap to illustrate the difference between break and continue statements.
14) Write a program to find the sum of the series : s=1+x+x ²+x ³+x ⁴…+x ⁿ .
15) Wap to input the value of x and n and print the sum of the series : 1 - x + x2 - x3 + x4 - …. xn .
16) Wap to check if a given number is a palindrome number or not.
17) Wap to print Fibonacci series.
18) Wap to input the value of x and n and print the sum of the following series: x + x2/2 + x3/3 + x4/4 + -------
- + xn/n.

19) Write a program in python that accepts marks(out of 100) in five subjects, calculate and display
percentage marks, Grade and Remarks (using table given below).
Percentage Range Grade Remarks
90% - 100% A Excellent
75% - 89% B Very Good
60% - 74% C Good
45% - 59% D Average
Below 45% E Need Improvement

sub1 = int(input("Enter marks of the first subject: "))


sub2 = int(input("Enter marks of the second subject: "))
sub3 = int(input("Enter marks of the third subject: "))
sub4 = int(input("Enter marks of the fourth subject: "))
sub5 = int(input("Enter marks of the fifth subject: "))
avg = (sub1 + sub2 + sub3 + sub4 + sub5) / 5

if avg >= 90:


print("Grade: A ")
print("Remarks : Excellent ")
elif avg >= 75 and avg < 90:
print("Grade: B")
print("Remarks : Very Good ")
elif avg >= 60 and avg < 75:
print("Grade: C")
print("Remarks : Good ")
elif avg >= 45 and avg < 60:
print("Grade: D")
print("Remarks : Average ")
else:
print("Grade: F")
print("Remarks : Need Improvement ")
output
Case 1:
Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93
Enter marks of the fifth subject: 100
Grade: A
Remarks : Excellent
Case 2:
Enter marks of the first subject: 81
Enter marks of the second subject: 72
Enter marks of the third subject: 94
Enter marks of the fourth subject: 85
Enter marks of the fifth subject: 80
Grade: B
Remarks : Very Good

20) Wap to print the following using a single loop(no nested loops):
1
11
111
1111
11111
21) Wap to print a pattern like: 4321
432
43
4

String Manipulation

22) Wap to read a string and display it in reverse order- display one character per line. Do not create a
reverse string, just display in reverse order.

s = input("Enter a string: ")


# Loop from the last character to the first
for i in range(len(s) - 1, -1, -1):
print(s[i])
23) Wap to input an integer and check if it contains any o in it.

num = input("Enter an integer: ")

if '0' in num:
print("The number contains 0")
else:
print("The number does not contain 0")
24) Wap to input a string and check if it is a palindrome string using a string slice.
s = input("Enter a string: ")

if s == s[ : :-1]:
print("The string is a palindrome")
else:
print("The string is not a palindrome")

25) Wap that reads a line and prints its statistics like:

Number of uppercase letters :


Number of lowercase letters :
Number of alphabets :
Number of symbols :
Number of digits :

line = input("Enter a line: ")


upper = lower = digits = symbols = 0

for ch in line:
if 'A' <= ch <= 'Z':
upper += 1
elif 'a' <= ch <= 'z':
lower += 1
elif '0' <= ch <= '9':
digits += 1
else:
symbols += 1

alphabets = upper + lower

print("Uppercase letters:", upper)


print("Lowercase letters:", lower)
print("Alphabets:", alphabets)
print("Digits:", digits)
print("Symbols:", symbols)

List Manipulation
26) Wap to print elements of a list [„q‟,‟w‟,‟e‟, „r‟,‟t‟,‟y‟] in separate lines along with element‟s both
indexes(positive and negative).

lst = ['q', 'w', 'e', 'r', 't', 'y']


length = len(lst)

for i in range(length):
print(lst[i], "Positive index:", i, "Negative index:", i - length)

27) Wap that asks the user to input a number a list to be appended to an existing list. Whether the user
enters a single number or list of numbers, the programs should append the list accordingly.

lst = [1, 2, 3, 4]
print("Existing list:", lst)
data = input("Enter a number or list of numbers: ")

if ',' in data:
items = [Link](',')
for i in items:
[Link](int(i))
else:
[Link](int(data))

print("Updated list:", lst)


28) Wap that displays options for inserting or deleting elements in a list. If the user chooses a deletion
option, display a submenu and ask if element is to be deleted with value or by using its position or a list
slice is to be deleted.

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


print("Initial list:", lst)

print("\nMenu")
print("1. Insert element")
print("2. Delete element")

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

if choice == 1:
num = int(input("Enter element to insert: "))
[Link](num)
print("Updated list:", lst)

elif choice == 2:
print("\nDelete Menu")
print("1. Delete by value")
print("2. Delete by position")
print("3. Delete by slice")

dchoice = int(input("Enter delete choice: "))

if dchoice == 1:
val = int(input("Enter value to delete: "))
[Link](val)

elif dchoice == 2:
pos = int(input("Enter position: "))
[Link](pos)

elif dchoice == 3:
start = int(input("Enter start index: "))
end = int(input("Enter end index: "))
del lst[start:end]

else:
print("Invalid delete choice")

print("Updated list:", lst)

else:

print("Invalid choice")
29) Wap that inputs a list, replicates it twice and then prints the sorted list in ascending and descending
orders.
# Input a list of numbers separated by spaces
lst = input("Enter elements of the list separated by space: ").split()

# Convert each element to integer


lst = [int(x) for x in lst]

# Replicate the list twice


lst = lst * 2
print("Replicated list:", lst)

# Sort in ascending order


asc = sorted(lst)
print("Sorted list in ascending order:", asc)

# Sort in descending order


desc = sorted(lst, reverse=True)
print("Sorted list in descending order:", desc)
30) Wap to search for an element in a given list of numbers.

L=[2,58,95,999,65,32,15,1,7,45]
n=int(input("Enter the number to be searched : "))
if n in L:
print("Item found at the Position : ",[Link](n)+1)
else:
print("Item not found in list")

or,
lst=eval(input(“Enter list:”))
length=len(lst)
element=int(input(“Enter element to be searched for:”))
for i in range(0,length):
if element==lst[i]:
print(element,”found at index”,i)
break

else:

print(element,”not found in given list”)

output: Enter the number to be searched : 6


Item not found in list
===============================

Enter the number to be searched : 15


Item found at the Position :Â 7

Tuples
31) A tuple t1 stores (11,21,31,42,51), where its second last element is mistyped. Wap to correct its second
last element as 41.

# Original tuple
t1 = (11, 21, 31, 42, 51)
print("Original tuple:", t1)

# Convert tuple to list


lst = list(t1)

# Correct the second last element


lst[-2] = 41

# Convert back to tuple


t1 = tuple(lst)
print("Corrected tuple:", t1)

32) A student‟s roll number, name and marks in 5 subjects are available in the form of a tuple as shown
here:
Student=(11,‟Ria‟,(67,77,78,82,80)) . Wap to print the minimum and maximum marks along with total
marks obtained by the student.

# Given tuple
Student = (11, 'Ria', (67, 77, 78, 82, 80))

# Extract marks tuple


marks = Student[2]

# Calculate total, min, and max


total = sum(marks)
minimum = min(marks)
maximum = max(marks)

# Display results
print("Total marks:", total)
print("Minimum marks:", minimum)
print("Maximum marks:", maximum)
33) Wap to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to
store only the usernames from the email IDs and second to store domain names from the email IDs.
Print all three tuples at the end of the program. [Hint: You may use the function split()]

# Input number of students


n = int(input("Enter number of students: "))

emails = () # Empty tuple for emails


usernames = () # Empty tuple for usernames
domains = () # Empty tuple for domains

# Read email IDs and create tuples


for i in range(n):
email = input(f"Enter email ID of student {i+1}: ")
emails += (email,) # Add email to emails tuple
parts = [Link]('@') # Split into username and domain
usernames += (parts[0],) # Add username
domains += (parts[1],) # Add domain

# Print all three tuples


print("Emails tuple:", emails)
print("Usernames tuple:", usernames)
print("Domains tuple:", domains)

output:
Enter number of students: 2
Enter email ID of student 1: ria@[Link]
Enter email ID of student 2: aman@[Link]

Emails tuple: ('ria@[Link]', 'aman@[Link]')


Usernames tuple: ('ria', 'aman')
Domains tuple: ('[Link]', '[Link]')
34) Wap to input names of n students and store them in a tuple. Also, input a name from the user and find if
this student is present in the tuple or not.
We can accomplish these by: (a) writing a user defined function (b) using the built-in function

# Input number of students


n = int(input("Enter number of students: "))

# Input names and store in a tuple


students = tuple(input(f"Enter name of student {i+1}: ") for i in range(n))

# Input name to search


search_name = input("Enter name to search: ")

# Check presence using 'in'


if search_name in students:
print(f"{search_name} is present in the tuple")
else:
print(f"{search_name} is not present in the tuple")

output:
Enter number of students: 3
Enter name of student 1: Ria
Enter name of student 2: Aman
Enter name of student 3: Neha
Enter name to search: Aman

Aman is present in the tuple


35) Wap to show the slicing of tuples.

data = (10, 20, 30, 1, 7, 9, 100, 51, 75, 80)


data2 = data[4:-4]
print(data2)
print(data[1:6])
print(data[4:-2])
print(data[-40:4])
print(data[::-1])
print(data[::-2])
print(data[2:10:2])

Dictionary

36) Wap to create dictionary for storing employee names and salary and access them

# Step 1: Create an empty dictionary


employees = {}

# Step 2: Input number of employees


n = int(input("Enter number of employees: "))

# Step 3: Input employee names and salaries


for i in range(n):
name = input("Enter employee name: ")
salary = float(input("Enter salary: "))
employees[name] = salary # Add to dictionary

# Step 4: Print the dictionary


print("Employee dictionary:", employees)

# Step 5: Access and display each employee's salary


for name in employees:
print(name, "has salary", employees[name])

37) Create a dictionary „ODD‟ of odd numbers between 1 and 10, where the key is the decimal number and
the value is the corresponding number in words. Perform the following operations on this dictionary:

(a) Display the keys


(b) Display the values
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9
Solution:
# Step 1: Create the dictionary of odd numbers between 1 and 10
ODD = {
1: "one",
3: "three",
5: "five",
7: "seven",
9: "nine"
}

# (a) Display the keys


print("Keys:", [Link]())

# (b) Display the values


print("Values:", [Link]())

# (c) Display the items


print("Items:", [Link]())

# (d) Find the length of the dictionary


print("Length of dictionary:", len(ODD))

# (e) Check if 7 is present


print("Is 7 present?", 7 in ODD)

# (f) Check if 2 is present


print("Is 2 present?", 2 in ODD)

# (g) Retrieve the value corresponding to the key 9


print("Value of key 9:", ODD[9])

# (h) Delete the item with key 9


del ODD[9]
print("Dictionary after deleting key 9:", ODD)

output:
Keys: dict_keys([1, 3, 5, 7, 9])
Values: dict_values(['one', 'three', 'five', 'seven', 'nine'])
Items: dict_items([(1, 'one'), (3, 'three'), (5, 'five'), (7, 'seven'), (9, 'nine')])
Length of dictionary: 5
Is 7 present? True
Is 2 present? False
Value of key 9: nine
Dictionary after deleting key 9: {1: 'one', 3: 'three', 5: 'five', 7: 'seven'}
38) Write a program to enter names of employees and their salaries as input and store them in a dictionary.

# Step 1: Create an empty dictionary


employees = {}

# Step 2: Input number of employees


n = int(input("Enter number of employees: "))

# Step 3: Input names and salaries


for i in range(n):
name = input(f"Enter name of employee {i+1}: ")
salary = float(input(f"Enter salary of {name}: "))
employees[name] = salary # Store in dictionary

# Step 4: Display the dictionary


print("\nEmployee Dictionary:")
print(employees)

output:
Enter number of employees: 3
Enter name of employee 1: Ria
Enter salary of Ria: 50000
Enter name of employee 2: Aman
Enter salary of Aman: 60000
Enter name of employee 3: Neha
Enter salary of Neha: 55000
Employee Dictionary:
{'Ria': 50000.0, 'Aman': 60000.0, 'Neha': 55000.0}
39) Write a program to count the number of times a character appears in a given string.

# Input a string
text = input("Enter a string: ")

# Input the character to count


char = input("Enter the character to count: ")

# Initialize counter
count = 0

# Loop through each character in the string


for c in text:
if c == char:
count = count+1

# Display the result


print(f"The character '{char}' appears {count} times in the string.")
output:
Enter a string: programming
Enter the character to count: g
The character 'g' appears 2 times in the string.

40) Write a function to convert a number entered by the user into its corresponding number in words. For
example, if the input is 876 then the output should be „Eight Seven Six‟.
def convert(num): # dictionary of digits and their names
numberNames = { 0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine' }

result = ' '


for ch in num:
key = int(ch) # convert character to integer
value = numberNames[key]
result = result + ' ' + value

return [Link]()

num = input("Enter any number: ") # number stored as string


result = convert(num)

print("The number is:", num)


print("The numberName is:", result)

Output:
Enter any number: 6512
The number is: 6512
The numberName is: Six Five One Two
41) Write a Python program to find the highest 2 values in a dictionary.

# Example dictionary
scores = {'Ria': 85, 'Aman': 92, 'Neha': 78, 'Vikram': 95, 'Sara': 88}

# Get all values and sort them in descending order


values = sorted([Link](), reverse=True)

# Get the highest 2 values


highest_two = values[:2]

print("The highest 2 values are:", highest_two)

The highest 2 values are: [95, 92]


42) Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string : 'w3resource'
Expected output : {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
# Input string
text = input("Enter a string: ")

# Create an empty dictionary


char_count = {}

# Loop through each character in the string


for ch in text:
if ch in char_count:
char_count[ch] += 1 # Increment count if already exists
else:
char_count[ch] = 1 # Initialize count to 1 if not exists

# Display the dictionary


print("Character count dictionary:", char_count)

43) Write a program to input your friends‟ names and their Phone Numbers and store them in the dictionary
as the key-value pair. Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names

# Step 1: Create an empty dictionary


friends = {}

# Step 2: Input number of friends


n = int(input("Enter number of friends: "))

# Step 3: Input friends' names and phone numbers


for i in range(n):
name = input("Enter friend's name: ")
phone = input("Enter phone number: ")
friends[name] = phone

# (a) Display all friends


print("\nFriends and phone numbers:")
for name in friends:
print(name, ":", friends[name])

# (b) Add a new friend


name = input("\nEnter name of new friend to add: ")
phone = input("Enter phone number: ")
friends[name] = phone
print("Dictionary after adding new friend:", friends)

# (c) Delete a friend


name = input("\nEnter name of friend to delete: ")
if name in friends:
del friends[name]
print("Dictionary after deletion:", friends)

# (d) Modify phone number


name = input("\nEnter name of friend to modify: ")
if name in friends:
phone = input("Enter new phone number: ")
friends[name] = phone
print("Dictionary after modification:", friends)

# (e) Check if a friend is present


name = input("\nEnter name of friend to check: ")
if name in friends:
print(name, "is present in the dictionary.")
else:
print(name, "is not present in the dictionary.")

# (f) Display dictionary sorted by names


print("\nDictionary in sorted order of names:")
for name in sorted(friends):
print(name, ":", friends[name])

You might also like