Python Practice question
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
sorted_list = ascending_order(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:
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
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
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.
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},
}
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)