在满足要求时撤消功能

时间:2013-03-13 17:37:25

标签: python python-2.7

我正在尝试做的是从变量“FGlasgow”中取出食物并将其添加到变量“食物”中,简单明了,但是我注意到即使当FGlasgow变为否定时剧本仍然需要更多,所以我告诉格拉斯哥的剧本< 0添加食物并取一个随机数,问题是这是否可以缩短,如果我的方法是正确的。

import random

def RandomNo():
    Random = random.randint(0,50)
    return Random

Food = 1
FGlasgow = 100


while True:
    Random = RandomNo()
    Food += Random
    FGlasgow -= Random
    while FGlasgow < 0:
        Food -= Random
        FGlasgow += Random
        Random = RandomNo()
        Food += Random
        FGlasgow -= Random
    print "You have found" , Random , "units of food"

感谢您的帮助:)任何建议都会很棒:)

3 个答案:

答案 0 :(得分:1)

你会看到我改变了变量名称。它们已根据PEP-8进行了更改。

至于你的代码,是的,它可以缩短。您不需要外部while循环。另外,如果您想确保f_glasgow不低于0,请执行以下操作:

import random

def randomNo(limit):
    return random.randint(0,min(50,limit))

food = 1
f_glasgow = 100

while f_glasgow >= 0:
    x = randomNo(f_glasgow)
    food += x
    f_glasgow -= x
print "You have found" , food , "units of food"

答案 1 :(得分:0)

为什么不跳过第一个while循环?另外,我很困惑你为什么要进行第二次随机计算。难道这不可能否定第一个吗?为什么不简单地做:

def RandomNo():
    Random = random.randint(0,FGlasgow)
    return Random

if (FGlasgow > 0):
    Random = RandomNo()
    Food += Random
    FGlasgow -= Random

答案 2 :(得分:0)

仅当FGlasgow大于Random时,

FGlasgow才会变为否定,因此如果您想要防止这种情况发生,只需修改您用于randint()的参数,以便你不能得到高于FGlasgow的任何东西:

import random

def RandomNo(upper=50):
    Random = random.randint(1, min(50, upper))
    return Random

Food = 1
FGlasgow = 100

while FGlasgow > 0:
    Random = RandomNo(FGlasgow)
    Food += Random
    FGlasgow -= Random
    print "You have found" , Random , "units of food"

请注意,在您的代码和我的代码中,最终FGlasgow将达到0,您的代码将停留在infinte循环中,这就是我将while条件更改为最终停止的原因。

相关问题