Python 3.3 if / else / elif
我对if、else和elif语句有一些问题。问题是我不知道如何让代码在代码之后打印语句。
1 2 3 4 | if profit > 0: print('After the transaction, you lost ' ,profit, ' dollars.') elif profit < 0: print('After the transaction, you gained ' ,profit, ' dollars.') |
这是迄今为止我所知道的代码。
1 2 3 4 5 6 7 | >>> 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打印,它给了我
但是我不知道我在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
你需要一个正确的缩进和一个else语句
1 2 3 4 5 6 | if profit > 0: print('After the transaction, you gained ', profit, ' dollars.') elif profit < 0: [code...] else: [code...] |
或者如果你只想要两个箱子:
1 2 3 4 | if profit > 0: print('After the transaction, you gained ', profit, ' dollars.') else: print('After the transaction, you lost ', -profit, 'dollars.') |
号
PS:更正了打印