Python的新手(大于但不到;返回

时间:2017-11-22 07:03:44

标签: python python-3.x

cookiedict = {'banana':5, 'blueberries':5, 'jerky':5}

def cookies():
    return input('Which of the cookies do you want to eat?')
def number():
    return int(input('How many cookies do you want to eat?'))

cookies = cookies ()
number = number ()

while True:
    if cookiedict[cookies] >0 <=5:
        cookiedict[cookies] -= number
        print ('You ate {} of the {} cookies'.format(number,cookies))
    elif cookiedict[cookies] >=6:
        print ('Game Over!!! You ate too much!!!')
        break
    else:
        print ('Incorrect Input. Try again...')

这是我的第二天。我正在使用udemy课程和youtube视频的组合。您可能通过查看代码知道我想要完成的任务。如果你吃的东西超过你丢失的可用饼干。每个只有5个。

if cookiedict[cookies] >0 <=5:
       cookiedict[cookies] -= number
        print ('You ate {} of the {} cookies'.format(number,cookies))

我不知道为什么这不起作用。无论我输入什么数字,它都会不断输出打印件,即使我认为我只是在大于0且等于或小于5时才打印。

另外,我正在做这个部分吗?似乎它不应该因某种原因而起作用,但它接受了输入。

def cookies():
    return input('Which of the cookies do you want to eat?')
def number():
    return int(input('How many cookies do you want to eat?'))

cookies = cookies ()
number = number ()

感谢您的帮助。我花了最后几个小时玩这个并且无法让它发挥作用!!

2 个答案:

答案 0 :(得分:1)

x >0 <=5x > 0 and 0 <= 5的缩写。由于0始终小于5,因此第二部分始终为真,您最终只会比较>0

你想要的是:0 < x <= 5,意思是0 < x and x <= 5

答案 1 :(得分:0)

始终打印是因为您没有比较输入的数字,而是可用的Cookie数量。如果输入的数字是<=5 and >0,您需要比较输入数字并打印。 这样做: -

while True:
    if 0 < number <= 5:
        cookiedict[cookies] -= number
        print ('You ate {} of the {} cookies'.format(number,cookies))
    elif number >= 6:
        print ('Game Over!!! You ate too much!!!')
        break
    else:
        print ('Incorrect Input. Try again...')