最后模拟和添加总数

时间:2015-02-09 02:08:29

标签: python while-loop global simulation

这是我的代码:

import random, time
def example():
    var = random.randint(1,100)
    if var <= 99:
        var = 'a', 'b', 'c', 'd'
    if var == 100 :
        var = 'b', 'c', 'd'
    noACount = 0
    someVariable = 0
    if 'a' in var:
        someVariable = someVariable + 1
    if 'a' in var:
        someVariable = someVariable + 12
    else:
        print('Item a not present')
        noACount = noACount + 1
        time.sleep(1)
    print('The amount of someVariable you have is ' + str(someVariable) + '.')
    print('The amount of times A was not present was' + str(noACount) + '.')

到目前为止,我已经完成了这个,但我试图让它像模拟一样。我试图让它问你想执行这个脚本多少次,最后告诉你someVariable总数和nACount的总和。例如,如果我的变量some​​Variable是poptarts,并且noACount是苹果,那么在做x次结束时,它会告诉你你购买的poptart的数量是x,你买苹果的次数是x。我尝试用while循环来做这件事,但这根本不起作用,所以知道我一直试图解决这个问题。

1 个答案:

答案 0 :(得分:0)

在进入循环之前,您需要定义someVariable。然后它在函数范围内,而不仅仅在循环范围内。

示例1:

while True:
    someVariable = 0 #The variable is initiated to 0 => bad
    someVariable +=1
print someVariable #outputs 1

示例2:

someVariable = 0
while True:
    ...doSomeMagic...
    someVariable +=1
print someVariable #someVariable now holds whatever we counted up to

请注意&#34;而True&#34;启动一个无限循环,必须通过调用&#34; break&#34;来打破它。当你的病情满意时。