Page 282 - Computer Science Class 11 Without Functions
P. 282

Case Based Questions


           1.  Shilpi finds programs on strings interesting. Her most recent programming challenge requires her to take a string that may
              contain several words (possibly zero) and print a new string with the first letter of each word in the original text capitalized.
              Assist Shilpi in finishing the job.
         Ans.  To develop the desired program, Shilpi should follow the following approach:
              a.  Split the input text into a list of individual words. Use the method split().
              b.  Capitalise the first letter of each word in the list and append it to an initially empty list. Use the method capitalize().
              c.  Join the capitalised words back into a single string. Use the method join() with a space as the separator.
              Now the program can be developed as follows:
              '''
              Objective: To capitalise the first letter of each word in text.
              Input Parameters: text - string
              Output: capitalisedText - string
              '''
              text = input("Enter a string of alphabets: ")


              words = text.split()
              capitalisedWords= []
              for word in words:
                  capitalisedWords.append(word.capitalize())
              capitalisedText = ' '.join(capitalisedWords)


              print("The new sentence is ", capitalisedText)
              Sample execution of the program:
              Enter a string: honesty is the best policy
              Modified string: Honesty Is The Best Policy
           2.  Thomas is working on a word processor. He finds the toggle case feature very interesting. Along similar lines, he wants to
              create a program in Python that will accept a string in lowercase as input and capitalize every alternate character of the
              string. Help him complete the task.
         Ans:  To develop the desired program, Thomas needs to create a new string using the following approach:
              a.  Find length of the given word using the function len().
              b.  Intialise the desired toggle word (toggleWord) as null string.
              c.  for each character in the original string,
                 i.  if it is placed at even index:
                   *append it as it to toggleWord
                 ii.  else:
                   *Capitalize the character and append to toggleWord
              Now the program can be developed as follows:
              '''
              Objective: To capitalize every alternate alphabet of a word
              Input Parameters: word - string
              Output: alternateCaseWord - string
              '''
              word = input("Enter a word : ")

         280   Touchpad Computer Science-XI
   277   278   279   280   281   282   283   284   285   286   287