Question

In: Computer Science

Using Python 3 The primary objective of this assignment is to reinforce the concepts of string...

Using Python 3

The primary objective of this assignment is to reinforce the concepts of string processing.

Part A: Even or Odd

For this first part, write a function that will generate a random number within some range (say, 1 to 50), then prompt the user to answer if the number is even or odd. The user will then input a response and a message will be printed indicated whether it was correct or not. This process should be repeated 5 times, using a new random number for each play, regardless of whether the user was correct or not.

Notes

  • A correct response for an even number can be any of the following: “even”, “Even”, “EVEN”, “e”, “E”. “EiEiO”. The main criterion is that a correct response begins with the letter “e”, regardless of case. The same goes for an odd number – a correct response should begin with the letter “o”.
  • If the user enters an invalid response, they should be notified. However, an invalid response still counts as one of the 5 plays.
  • The solution should contain a loop (for or while) and a few if statements. An example execution is shown below:

>>> assign2PartA()
Is 41 odd or even? Odd
   Correct
Is 48 odd or even? Even
   Correct
Is 3 odd or even? e
   Incorrect
Is 20 odd or even? o
   Incorrect
Is 42 odd or even? xyz
   You did not enter a correct reply.
     Please answer using Odd or Even

Part B: Vowel Counting

The second task is to write a function that counts, and prints, the number of occurrences for each vowel (a, e, i, o and u) in a given phrase and outputs a (new) phrase with the vowels removed. The phrase should be accepted as a parameter to the function. If the (original) phrase is empty, you should output an appropriate error message, and obviously with no vowel counts. If the phrase contains no vowels, a message should be displayed, and the count can be omitted – since there is no point in displaying 0 for each vowel! A message should also be displayed if the phrase contains only vowels, but the counts should still be displayed.

Notes

  • Recall that you can use the tab escape character (“\t”) for spacing to align the text, or use a given width in the f-string (print(f"{count_a:4}, ……”), where the value of count_a here is right justified in 4 columns.)
  • Be sure to correctly handle both upper- and lower-case letters (e.g. both “a” and “A” should be counted as an instance of the letter “A”.) The new phrase (with vowels removed) should preserve the letter cases from the original phrase. Be sure to show output for all possible scenarios in your submitted output. A few example executions are shown below. In the first example, the escape sequence \" allows for inclusion of a " within a string delimited by two ", see slide 9 in “Working with Strings.”

>>> assign2PartB("Remember that context here defines \"+\" as 'Concatenate'")
   A    E    I    O    U
   4   10    1    2    0

The original phrase is: Remember that context here defines "+" as 'Concatenate'
The phrase without vowels is: Rmmbr tht cntxt hr dfns "+" s 'Cnctnt'

>>> assign2PartB("bcdfghjklmnpqrstvwxyz")

The phrase contains no vowels: bcdfghjklmnpqrstvwxyz

>>> assign2PartB("aeiouAEIOU")
   A    E    I    O    U
   2    2    2    2    2

The phrase contains only vowels: aeiouAEIOU

>>> assign2PartB("")

The input phrase is empty!

>>>

Solutions

Expert Solution

** Compiled in Spyder **

CODE:

import random

def assign2PartA():
    # Running a for loop for 5 iterations.
    for i in range(5):
        # Generating a random number between 1 and 50 using random.randint().
        num = random.randint(1, 50)
        # Creating a question by concatenating the random int and string.
        question = 'Is ' + str(num) + ' odd or even? '
        # Reading response from the user.
        response = input(question)
        # Converting the input to upper case, so that we can just check for capital letters.
        response = response.upper()
        # If the first letter is not 'E' or 'O', then it is an invalid input.
        if response[0] != 'E' and response[0] != 'O':
            print('  You did not enter a correct reply.\n   Please answer using Odd or Even')
        # If the random number generated is even and the response starts with 'E', 
        # then the answer is correct.
        elif num % 2 == 0 and response[0] == 'E':
            print('  Correct')
        # If the random number generated is odd and the response starts with 'O', 
        # then the answer is correct.
        elif num % 2 != 0 and response[0] == 'O':
            print('  Correct')
        # else the answer is incorrect.
        else:
            print('  Incorrect')

def assign2PartB(string):
    # Initializing a, e, i, o, u as 0.
    # To store the number of occurrence.
    a = e = i = o = u = 0
    
    # Traversing through the string letter by letter and incrementing the value of the variable
    # corresponding to vowels.
    for letter in string:
        if letter == 'A' or letter == 'a':
            a += 1
        elif letter == 'E' or letter == 'e':
            e += 1
        elif letter == 'I' or letter == 'i':
            i += 1
        elif letter == 'O' or letter == 'o':
            o += 1
        elif letter == 'U' or letter == 'u':
            u += 1
    # total -> total number of vowels present in the string.
    total = (a + e + i + o + u)
    
    # If the string is empty, print 'phrase is empty'.
    if string == "":
        print('The input phrase is empty!')
    # If there is no vowels, print 'no vowels'.
    elif total == 0:
        print('The phrase contains no vowels:', string)
    else:
        # else print the occurrences of each vowels.
        print('A \t E \t I \t O \t U')
        print(a, '\t', e, '\t', i, '\t', o, '\t', u)
        
        # If all the letters are vowels, print 'only vowels'.
        if len(string) == total:
            print('The phrase contains only vowels:', string)
        # else print the original string and another string wihtout vowels.
        else:
            print('The original phrase is:', string)
            # creating an empty string.
            new_string = ""
            # Appending all the consonant to new_string.
            for letter in string:
                if letter not in "aeiouAEIOU":
                    new_string += letter
            
            print('The phrase without vowels is:', new_string)

# calling assign2PartA()
assign2PartA()
print()

# calling assign2PartB() with different strings
string1 = "Remember that context here defines \"+\" as 'Concatenate'"
string2 = "bcdfghjklmnpqrstvwxyz"
string3 = "aeiouAEIOU"
string4 = ""

assign2PartB(string1)
print()
assign2PartB(string2)
print()
assign2PartB(string3)
print()
assign2PartB(string4)

Screenshots:

refer this to know the proper indentations.

Sample I/O:

Hope this Helps:)

Please consider giving this answer a thumbs up.

If this answer didn't satisfies your requirements or needs modifications, please let me know in the comment section before giving a thumbs down.

Thank you! Stay Safe!!!


Related Solutions

The primary objective of this assignment is to reinforce the concepts of string processing. Part A:...
The primary objective of this assignment is to reinforce the concepts of string processing. Part A: Even or Odd [10 marks] For this first part of the assignment, write a function that will generate a random number within some range (say, 1 to 50), then prompt the user to answer if the number is even or odd. The user will then input a response and a message will be printed indicated whether it was correct or not. This process should...
The purpose of this assignment is to reinforce Ada concepts. Define a Complex-numbers package includes the...
The purpose of this assignment is to reinforce Ada concepts. Define a Complex-numbers package includes the following operations: Addition Subtraction Multiplication Division A “main program” needs to create one or more complex numbers, perform the various arithmetic operations, and then display results. Develop the program in ADA code with several packages. Write a short report that documents all work done, including the overall design, explanation of the implementation, the input data used to run the program, the output of the...
The assignment is to build a program in Python that can take a string as input...
The assignment is to build a program in Python that can take a string as input and produce a “frequency list” of all of the wordsin the string (see the definition of a word below.)  For the purposes of this assignment, the input strings can be assumed not to contain escape characters (\n, \t, …) and to be readable with a single input() statement. When your program ends, it prints the list of words.  In the output, each line contains of a...
Objective This assignment aims to investigate the concepts in solving problems on the special theory of...
Objective This assignment aims to investigate the concepts in solving problems on the special theory of relativity, analyze the effects of relativity and evaluate the validity of results on the application of relativity. Problem Solving, Analysis and Evaluating of the Validity of Results Direction: Solve the given problem using systematic/logical solution. Make an analysis and evaluation of the results. Rubrics will be used in marking. (1) Determine Ƴ if v = 0.01c; 0.1c; 0.5c; 0.6c; 0.8c; 0.9c; 0.99c; 1.00c; and...
For these of string functions, write the code for it in C++ or Python (without using...
For these of string functions, write the code for it in C++ or Python (without using any of thatlanguage's built-in functions) You may assume there is a function to convert Small string into the language string type and a function to convert your language's string type back to Small string type. 1. int [] searchA,ll(string in...str, string sub): returns an array of positions of sub in in...str or an one element array with -1 if sub doesn't exist in in...str
Objective: The purpose of this programming assignment is to practice using STL containers. This problem is...
Objective: The purpose of this programming assignment is to practice using STL containers. This problem is selected from the online contest problem archive (Links to an external site.), which is used mostly by college students world wide to challenge their programming ability and to prepare themselves for attending programming contests such as the prestige ACM International Collegiate Programming Contest (Links to an external site.). For your convenience, I copied the description of the problem below with my note on the...
The purpose of this problem set is to reinforce your knowledge of some basic chemical concepts...
The purpose of this problem set is to reinforce your knowledge of some basic chemical concepts that are important for the origin of the elements. 1. Use the abundances of the stable isotopes of strontium and the masses of these nuclides (found at http://atom.kaeri.re.kr/nuchart/) to calculate the atomic weight of strontium. Compare the value that you get with the value shown in the periodic table found at http://www.rsc.org/periodic-table. Show your work. 2. Consult the chart of the nuclides (http://atom.kaeri.re.kr/nuchart/ )...
python 3 please Define a function voweliest that takes as input a string and returns as...
python 3 please Define a function voweliest that takes as input a string and returns as output a tuple where the string that has the most vowels in it is the first element and the second is the number of vowels in that string. Note: don't worry about ties or capital letters Hint: consider defining and using a separate function that counts the number of vowels in a given string
a summary explaining the basic understanding of the following programming concepts using a language of python:...
a summary explaining the basic understanding of the following programming concepts using a language of python: •Variables •Arithmetic and Logical operations •Sequential coding (Structured programming •Decision structure (If statements) •Repetition structure •Functions with some coding demos inside visual studio code python IDE which can be sent as screenshot. preferably a typed summary please which can be written into powerpoint pleaseeeee ???
Using python: Given a string x, write a program to check if its first character is...
Using python: Given a string x, write a program to check if its first character is the same as its last character. If yes, the code should output "True"
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT