Dark Mode

Class 12 Computer Science - Python Questions

Welcome to the Python practice questions and solutions for Class 12 Computer Science.

PYTHON PRACTICE QUESTIONS

Q.1) Read a text file line by line and display each word separated by a #

def read_and_display_words(filename):
    try:
        with open(filename, 'r') as file:
            for line in file:
                words = line.strip().split()
                print("#".join(words))
    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found.")

file_name = 'sample.txt'
read_and_display_words(file_name)

Q.2) Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the file.

def analyze_text_file(filename):
    vowels = "aeiouAEIOU"
    consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"

    vowel_count = 0
    consonant_count = 0
    uppercase_count = 0
    lowercase_count = 0

    try:
        with open(filename, 'r') as file:
            for line in file:
                for char in line:
                    if char.isalpha():
                        if char.isupper():
                            uppercase_count += 1
                        elif char.islower():
                            lowercase_count += 1

                        if char in vowels:
                            vowel_count += 1
                        elif char in consonants:
                            consonant_count += 1

        print(f"--- Analysis of '{filename}' ---")
        print(f"Number of Vowels: {vowel_count}")
        print(f"Number of Consonants: {consonant_count}")
        print(f"Number of Uppercase Characters: {uppercase_count}")
        print(f"Number of Lowercase Characters: {lowercase_count}")

    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found.")
file_name = 'sample.txt'
analyze_text_file(file_name)
        

Q.3) Remove all the lines that contain the character 'a' in a file and write it to another file.

def remove_lines_with_char(input_filename, output_filename, char_to_remove='a'):
    try:
        with open(input_filename, 'r') as infile:
            lines_to_write = []
            for line in infile:
                if char_to_remove.lower() not in line.lower():
                    lines_to_write.append(line)

        with open(output_filename, 'w') as outfile:
            outfile.writelines(lines_to_write)

        print(f"Successfully processed '{input_filename}'.")
        print(f"Lines not containing '{char_to_remove}' written to '{output_filename}'.")

    except FileNotFoundError:
        print(f"Error: The file '{input_filename}' was not found.")

input_file = 'input.txt'
output_file = 'output.txt'

remove_lines_with_char(input_file, output_file, 'a')