Frage

Okay, well for my job I have always used C++, but now they are wanting me to switch to Python. So over the weekend I have been making very simple programs to get used to the new system. I'm having trouble though with this program:

demand = input('What do you want to do: ')

option = 'Yes'

while option == 'Yes':


    if demand == 'add':
        print('Enter your two numbers...')

        a = int(input('First Number= '))
        b = int(input('Second Number= '))

        c = a + b

        print('Answer= %s' % c)

        option = input('Do you want to run agian?: ')


    if demand == 'subtract':
        print('Enter your two numbers...')

        a = int(input('First Number= '))
        b = int(input('Second Number= '))

        c = a - b

        print('Answer= %s' %c)

        option = input('Do you want to run agian?: ')


    if demand == 'multiply':
        print('Enter your two numbers...')

        a = int(input('Frist Number= '))
        b = int(input('Second Number= '))

        c = a * b

        print('Answer= %s' %c)

        option = input('Do you want to run agian?: ')


    if demand == 'divide':
        print ('Enter your two numbers...')

        a = int(input('First Number= '))
        b = int(input('Second Number= '))

        c = a / b

        print('Answer= %s' %c)

        option = input('Do you want to run agian?: ')



while option == 'No':

I know it is a simple program but I have a problem- I can get it to loop around when the user says 'Yes' after running the task but it stays on that task (ie. 'add' it will only run 'add' again and I want it to run from the beginning (so ask you what task you would like to preform). Also, the program does not shut off by itself- you always have to manually quit it. Any suggestions? Thanks

War es hilfreich?

Lösung

OK:

option = 'Yes'

while True:
    demand = input('What do you want to do: ')
    print('Enter your two numbers...')
    a = int(input('First Number= '))
    b = int(input('Second Number= '))
    c = 0
    if demand == 'add':
        c = a + b
    elif demand == 'subtract':
        c = a - b
    elif demand == 'multiply':
        c = a * b
    elif demand == 'divide':
        c = a / b

    print('Answer= %s' %c)
    option = input('Do you want to run agian?: ')
    if option != 'Yes':
        break

If you are using a loop, this means you don't have to repeat statements in every branch of if. So we read the demand, followed by the two numbers (since all operations require two numbers, there are no special things)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top