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
- Continuous Loop:
The program uses awhile Trueloop to repeatedly take input until the user decides to quit by entering “quit 0”. - 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).
- 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.
- Exit Condition:
If the word is “quit” and the number is “0”, the program exits the loop using thebreakstatement. - 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.
- 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.