Mad Libs are activities that have a person provide various words

Mad Libs are activities that have a person provide various words, which are then used to complete a short story in unexpec hopefully funny) ways.

Write a program that takes a string and an integer as input, and outputs a sentence using the input values as shown in the The program repeats until the input string is quit and disregards the integer input that follows.
Ex. If the input is:
apples 5
shoes 2
quit 0
the output is:
Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.

The Correct Answer and Explanation is :

Below is the Python program for your described task, followed by an explanation:

Explanation

  1. Continuous Loop:
    The program uses a while True loop to repeatedly take input until the user decides to quit by entering “quit 0”.
  2. Input Handling:
    The input is split into two parts:
  • The first part is assumed to be a word (word).
  • The second part is expected to be a number (num).
  1. Validation:
  • The program checks if the input format is correct by ensuring there are exactly two parts. If not, it prompts the user to re-enter a valid input.
  • The program converts the second part (num) into an integer. If the conversion fails, it prints an error message and asks for valid input again.
  1. Exit Condition:
    If the word is “quit” and the number is “0”, the program exits the loop using the break statement.
  2. Output:
    For valid inputs, the program generates the sentence:
  • "Eating {num} {word} a day keeps the doctor away."
    where {num} and {word} are replaced by the respective inputs.
  1. Error Handling:
    The program gracefully handles errors in input format or when the number is not an integer.

Example Execution

Input:

apples 5
shoes 2
quit 0

Output:

Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.

This ensures the program is robust, user-friendly, and meets the requirements.

Scroll to Top