一个不断变化的整数的最高设定值

时间:2016-03-07 16:41:40

标签: python

我有一个程序不断更改变量的值,我愿意找出在此过程中生成的最高值。我在下面发布了一段简单的代码,可以让你更好地了解我想要实现的目标。如果滚动的数字大于maxGen,我打算将maxGen变量设置为滚动的数字,但我认为这不是一种有效的编码方式。

looped = 0
numbergen = 0
while looped > 3: #how many times a number's supposed to be re-generated
    x = randint(1,1001)
    print(x)
    looped = looped + 1

2 个答案:

答案 0 :(得分:1)

我不确定该代码段的相关性,但执行此操作的一般方法是使用max

max_gen = 0
...
max_gen = max(max_gen, generated_variable)

答案 1 :(得分:1)

您的代码永远不会进入循环,因为循环初始化为0,然后您执行while looped > 3(它不是)。它应该是while looped < 3

你建议的方式很好。

looped = 0
numbergen = 0
max_num = None
while looped < 3: #how many times a number's supposed to be re-generated
    x = randint(1,1001)
    max_num = x if max_num is None else max(x, max_num)
    print(x)
    looped = looped + 1
print('max num: {0}'.format(max_num))