Page 526 - ComputerScience_Class_11
P. 526

Program 7: Write a program to reverse a string and count the vowels using a function.
                   Program 7.py

               File  Edit  Format    Run   Options   Window    Help

                def reverse_and_count_vowels(my_string):
                    reversed_string = my_string[::-1]
                    vowels = 'aeiouAEIOU'
                    count = sum(1 for char in my_string if char in vowels)
                    return reversed_string, count
                text = "Hello, how many vowels?"
                reversed_text, vowel_count = reverse_and_count_vowels(text)
                print("Reversed string:", reversed_text)
                print("Number of vowels:", vowel_count)




                   Output

                Reversed string: ?slewov ynam woh ,olleH
                Number of vowels: 6


              Program 8: Write a program to count the occurrences of a specific character in a string using a function.

                   Program 8.py

               File  Edit  Format    Run   Options   Window    Help

                def count_char_occurrences(my_string, char_to_count):
                    count = 0
                    for char in my_string:
                        if char == char_to_count:
                            count += 1
                    return count
                input_string = "hello world, welcome to Python programming!"
                char_to_find = 'o'

                occurrences = count_char_occurrences(input_string, char_to_find)
                print(f"The character '{char_to_find}' appears {occurrences} times in the string.")




                   Output
                The character 'o' appears 6 times in the string.
















                  524  Touchpad Computer Science (Ver. 3.0)-XI
   521   522   523   524   525   526   527   528   529   530   531