Python if语句问题

时间:2013-05-23 09:35:45

标签: python if-statement

我正在努力使if语句有效,但不是选择正确的语句,而是选择所有语句。那么,下面的代码:

money=100

if money==100:
    print('You buy a pair of headphones')
    money-=100
if money<50:
    print('You buy a movie')
        money-=25
if money<10:
    print('You buy a burger')
    money-=5

返回:

You buy a pair of headphones
You buy a movie
You buy a burger

请帮助!

4 个答案:

答案 0 :(得分:11)

使用elif

money=100

if money==100:
    print('You buy a pair of headphones')
    money-=100
elif money<50:
    print('You buy a movie')
    money-=25
elif money<10:
    print('You buy a burger')
    money-=5

现在每种可能性都是同一个区块的一部分,所以只做出一个决定,然后通过普通的if s进行顺序运行

答案 1 :(得分:1)

如果您有多个条件,并且只想符合条件,则只需执行一个条件,然后使用

  

“if elif keywords”

在您的情况下,代码将是

money = 100
if money == 100:
    print('You buy a pair of headphones')
    money -= 100
elif money <= 50 and money >=25:
    print('You buy a movie')
    money -= 25
elif money <= 10 and money >=5:
    print('You buy a burger')
    money -= 5

答案 2 :(得分:0)

或者做这样的事情:

prices = {'100':'headphones', '50':'movie', '10':'burger', 5}
money = 100
for price in prices: 
    if money >= price: 
        print 'You buy a ', prices[price]
        money -= price
        break

这封信不一样,但你可以看到它更紧凑。添加新案例更容易。逻辑是有道理的 - 我应该能够购买任何我有钱买的东西。

我也将它封装在一个方法中:

prices = {'100':'headphones', '50':'movie', '10':'burger', 5}
def buy(money):
    message = 'You could not afford anything'
    for price in prices: 
        if money >= price: 
            message = 'You buy a ' + prices[price]
            money -= price
            break
    return message

答案 3 :(得分:0)

这是因为所有条件都是真的,所以你得到了所有的输出。 代替

money = 100
if money == "100":
   print("You buy a pair of headphones.")
   money = 100
elif money <="50" and => "25":
    print("You buy a movie.")
    money = 25

elif money <= "25" and => "10":
     print("You buy a burger.")
     money = 5