Search code examples
pythonloopsconditional-statementsbreak

The program repeats until the input string is quit and disregards the integer input that follows


Write a program that takes a string and an integer as input, and outputs a sentence using the input values as shown in the example below. 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.

This is what I've got so far:

string = input().split()
string2 = input().split()
string3 = input().split()

all_input = (string + string2 + string3)

for word in all_input:
    while word != 'quit':
        print('Eating {} {} a day keeps the doctor away.'.format(string[1] , string[0]))
        print('Eating {} {} a day keeps the doctor away.'.format(string2[1], string2[0]))
        string = input().split()
        string2 = input().split()
        string3 = input().split()
        all_input = (string + string2 + string3)

I get the correct output but also receive this error:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    string = input().split()
EOFError: EOF when reading a line

And when it tests with the inputs:

cars 99
quit 0

Then I get no output. I feel like I need to use a break statement somewhere but nowhere I put it seems to work.


Solution

  • you are using input() multiple times where you can use it once inside a loop and if the input_string contains 'quit' it will be terminated. try the following code, it will continue taking input till the user enters quit

    while True:
        input_string = input()
        if 'quit' in input_string:
            break
        else:
            a,b = input_string.split(' ')
            print(f'Eating {b} {a} a day keeps the doctor away.')
    

    OR

    if you want to take all inputs at once, then find the code below, it will work as you expected

    input_string = []
    while True:
        line = input()
        if 'quit' in line:
            break
        else:
            input_string.append(line)
    
    for line in input_string:
        a,b = line.split(' ')
        print(f'Eating {b} {a} a day keeps the doctor away.')