想知道为什么这两者的结果不同?

时间:2018-06-06 00:56:38

标签: python for-loop random range

我想知道为什么这两者的结果不同?

import random
secretNumber = random.randint(1, 20)
for i in range(7):
  print(secretNumber)

import random
for i in range(7):
  print(random.randint(1, 20))

但另一方面这两者的结果是一样的:

number = range(1,7)
for i in number: print(i)

for i in range(1,7): print(i)

2 个答案:

答案 0 :(得分:1)

第一个设置为变量,意味着值将是常量/相同。第二个在每个循环上获得不同的值,因为您在每个循环上生成不同的随机数。

import random
secretNumber = random.randint(1, 20)
for i in range(7):
  print(secretNumber) # secretNumber will always be the same

import random
for i in range(7):
  print(random.randint(1, 20)) # will generate random number every loop

答案 1 :(得分:0)

我在代码中添加了一些注释,以便您可以解读正在发生的事情。

import random

# run random.randint(1,20) method 1 time and store the value in variable secretNumber
secretNumber = random.randint(1, 20)

for i in range(7):
  # Print the variable secretNumber 7 times (value is some integer)
  print(secretNumber) 

# Do whatever is in this loop 7 times
for i in range(7):
  # Print the value returned by random.randint(1,20)
  print(random.randint(1, 20))

# store range object (which is merely an iterator) in variable number
number = range(1,7)

# for loop will iterate the object stored in variable number
for i in number:
    print(i)

# range(1,7) will always return the same object so number === range(1,7)
for i in range(1,7):
    print(i)

有关范围如何在Python 3与2 Assign a range to a variable (Python)

中工作的更多信息