Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Practice question

The document contains a series of Python programming tasks that include sorting a list of integers, removing the smallest score from a list of baseball player scores, counting lines in a text file, replacing words in a file, managing student grades in a dictionary, calculating average marks for students, reversing a dictionary, counting word frequencies, converting tuples to lists, and finding unique elements in a list. Each task is accompanied by sample code demonstrating the implementation. The tasks cover basic data structures, file handling, and functions in Python.

Uploaded by

civar11801
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Practice question

The document contains a series of Python programming tasks that include sorting a list of integers, removing the smallest score from a list of baseball player scores, counting lines in a text file, replacing words in a file, managing student grades in a dictionary, calculating average marks for students, reversing a dictionary, counting word frequencies, converting tuples to lists, and finding unique elements in a list. Each task is accompanied by sample code demonstrating the implementation. The tasks cover basic data structures, file handling, and functions in Python.

Uploaded by

civar11801
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Python Practice question

1.​ Write a Python program that asks the user to input a list of integers separated by
spaces. Your program should then sort the list in ascending order and print the sorted
list.

def ascending_order(nums):
nums.sort()
return nums

num_list = input("Enter a list of numbers separated by spaces: ")


num_list = num_list.split()
num_list = [int(num) for num in num_list]

sorted_list = ascending_order(num_list)

print("The numbers in ascending order are:", sorted_list)


# sorted_list = sorted(num_list)

2.​ Write a Python program that takes a list of baseball player scores, removes the smallest
score, and prints the remaining scores in their original order.

Example:

Input: [15 28 9 22 35], Output: [15, 28, 22, 35]

def remove_smallest_score(scores):
# Manually find the smallest score
smallest_score = scores[0]
for score in scores:
if score < smallest_score:
smallest_score = score

# Remove the first occurrence of the smallest score by shifting elements


for i in range(len(scores)):
if scores[i] == smallest_score:
for j in range(i, len(scores)-1): # Shift elements to the left
scores[j] = scores[j + 1]
scores.pop() # Remove the last element (since it's now a duplicate after
shifting)
break # Exit the loop after removing the first occurrence

return scores
# Get user input as a list
score_list = input("Enter the scores of baseball players as a list (e.g., [15, 28, 9]):
")

# Convert the input string into a list manually (without using advanced functions)
score_list = score_list[1:-1] # Remove the square brackets
score_list = score_list.split(',') # Split by comma

# Convert each element into an integer manually (without list comprehension)


for i in range(len(score_list)):
score_list[i] = int(score_list[i]) # Convert each element to an integer

# Remove the smallest score and print the result


updated_scores = remove_smallest_score(score_list)
print("The scores after removing the smallest score are:", updated_scores)

3.​ Write a Python program that reads a text file named data_file.txt and prints the total
number of lines in the file. Handle the case where data_file.txt does not exist by printing
an error message.
def count_lines(file_path):
try:
with open(file_path, "r") as file:
lines = file.readlines()
print(f"Total lines: {len(lines)}")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError as e:
print(f"Error: {e}")

count_lines("data_file.txt")
4.​ Write a Python program that reads a text file named config.txt, finds all occurrences of
the word "old" and replaces them with the word "new". The modified content should be
saved back into the config.txt. Handle any potential FileNotFoundError.

def find_and_replace(file_path, old_word, new_word):


try:
with open(file_path, "r") as file:
content = file.read()
modified_content = content.replace(old_word, new_word)
with open(file_path, "w") as file:
file.write(modified_content)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError as e:
print(f"Error: {e}")
find_and_replace("config.txt", "old", "new")
5.​ Create a Python program that stores student names as keys and their grades as values in a
dictionary. Initially, the dictionary should be empty. Allow the user to add names and grades
to the dictionary. Calculate and print the average grade. Handle if dictionary is empty.
grades = {}

while True:
action = input("add or display or end? ")
if action == "add":
name = input("Enter student name: ")
grade = float(input("Enter grade: "))
grades[name] = grade
elif action == "display":
if not grades:
print("No grades are available")
else:
total = sum(grades.values())
average = total / len(grades)
print(f"Average grade: {average:.2f}")
elif action == "end":
break
6.​ Create a nested dictionary that represents the students and their marks in different subjects.
The outer dictionary should have student names as keys, and the inner dictionaries should
have subject names as keys and their corresponding marks as value. Print the average of
each student.
students = {
"Alice": {"Math": 90, "Science": 85, "English": 92},
"Bob": {"Math": 78, "Science": 88, "English": 80},
"Charlie": {"Math": 92, "Science": 95, "English": 88},
}

for student, marks in students.items():


total_marks = sum(marks.values())
average_marks = total_marks/ len(marks)
print(f"{student}'s average marks {average_marks:.2f}")
7.​ Write a Python program that takes a dictionary as input and returns a new dictionary with the
keys and values reversed. Assume each value is unique.

def reverse_dictionary(original_dict):
reversed_dict = {}
for key, value in original_dict.items():
reversed_dict[value] = key
return reversed_dict
original_dict = {"a": 1, "b": 2, "c": 3}
reversed = reverse_dictionary(original_dict)
print(reversed)
8.​ Create a function called count_words that takes a sentence as input and returns a
dictionary where keys are the words (lowercase) and values are their frequencies.

def count_words(sentence):
word_counts = {}
words = sentence.lower().split()
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return word_counts

# Example Usage:
word_counts = count_words("This is a test Sentence This is")
print(word_counts)
9.​ Write a function called tuple_to_list that takes a tuple as input and returns a new list
containing the same elements as the input tuple.

def tuple_to_list(input_tuple):
new_list = []
for item in input_tuple:
new_list.append(item)
return new_list

# Example Usage:
my_tuple = (10, 20, 30)
my_list = tuple_to_list(my_tuple)
print(my_list)

10.​Write a function called find_unique that takes a list as input and returns a new list
containing only the unique elements from the input list, maintaining the original order of
appearance.

def find_unique(input_list):
unique_list = []
for item in input_list:
if item not in unique_list:
unique_list.append(item)
return unique_list

# Example Usage:
my_list = [1, 2, 2, 3, 4, 4, 5]
unique = find_unique(my_list)
print(unique)

You might also like