Python 3.3 если/иначе/элиф

У меня возникли проблемы с операторами if, else и elif. Проблема в том, что я не могу понять, как заставить код печатать оператор после кода.

if profit > 0:
    print('After the transaction, you lost ' ,profit, ' dollars.')
elif profit < 0:
    print('After the transaction, you gained ' ,profit, ' dollars.')

Вот код, который, как я знаю, работает до сих пор.

>>> shares=float(input("Enter number of shares:"))
Enter number of shares:2000
>>> price1=float(input("Enter purchase price:"))
Enter purchase price:40
>>> price2=float(input("Enter sale price:"))
Enter sale price:42.75
>>> profit= 0.97 * (price2 * shares) - 1.03 * (price1 * shares)

Насколько я могу судить, приведенный выше код верен, потому что я могу попросить Python напечатать, и он выдает мне 535.00.

Однако я не могу понять, где я ошибаюсь с командой if, else или elif.

if profit > 0:
    print('After the transaction, you lost ' ,profit, 'dollars.')
    else profit < 0:

SyntaxError: invalid syntax

if profit > 0:
    print('After the transaction, you lost ' ,profit, 'dollars.')
    else profit < 0:

SyntaxError: invalid syntax

if profit > 0:
    print('After the transaction, you lost' ,profit, 'dollars.')
    elif profit < 0:

SyntaxError: invalid syntax

person Michael F    schedule 31.08.2017    source источник
comment
Почему вы делаете отступы else и elif? Вам нужно поддерживать этот уровень с помощью оператора if.   -  person Martijn Pieters    schedule 31.08.2017
comment
Кроме того, else не проходит тест, а только elif. Итак, else: допустим, else profit < 0: нет.   -  person Martijn Pieters    schedule 31.08.2017
comment
Помог ли ответ ниже?   -  person kenfire    schedule 21.09.2017


Ответы (1)


Вам нужен правильный отступ и оператор else

if profit > 0:
    print('After the transaction, you gained ', profit, ' dollars.')
elif profit < 0:
    [code...]
else:
    [code...]

Или, если вы просто хотите 2 случая:

if profit > 0:
    print('After the transaction, you gained ', profit, ' dollars.')
else:
    print('After the transaction, you lost ', -profit, 'dollars.')

PS: поправил печать.

person kenfire    schedule 31.08.2017