[英]Python: How to print the output of a for loop?
I have this code我有这个代码
x = random.randint(0,1)
y = 100
for x in range(y):
What's now?现在做什么? How do I print the output?
如何打印 output? I tried printing x but it didn't work.
我尝试打印 x 但它没有用。
x = random.randint(0,1)
y = 100
for x in range(y):
print(x)
I'm not sure if it is what you wanted我不确定这是不是你想要的
Maybe this?也许这个? To print
y
random integer between 0 and 1.在 0 和 1 之间随机打印
y
integer。
y = 100
for i in range(y):
x = random.randint(0,1)
print(x)
@DragonPeti "Thx? Is there a way that I can print x into a single line or string because this way python prints just one number in a line?" @DragonPeti “Thx?有没有办法可以将 x 打印成单行或字符串,因为这样 python 在一行中只打印一个数字?”
y = 100
for a in range(y):
print(random.randint(0,1),end='')
OUTPUT OUTPUT
1100000000001101010100100011010100010000000101000111100011101101001011000100001100111000011111001000
# OR Changing end='' to end=' '
1 1 1 0 0 1 1 1 1 1 0 0 1 0 1 1 1 1 0 1 1 0 1 0 0 1 1 0 1 1 0 0 1 1 1 0 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 1 0 1 1 1 0 1 0 1 0 1 1 1 0 1 0 1 0 0 0 1 1 1 1 1 1 0 0 0 1 0 1 0 1 0 1 0
The reason you don't get a random number between 0
and 1
for each iteration of the for
loop is because对于
for
循环的每次迭代,您没有获得0
到1
之间的随机数的原因是因为
You have overwritten the value of x
at for x in
, and您已经
for x in
覆盖了x
at 的值,并且
You did not redefine x
to be a random number in the loop, so even if you were to remove the part that overwrites x
, it will remain the same number throughout the loop.您没有将
x
重新定义为循环中的随机数,因此即使您要删除覆盖x
的部分,它在整个循环中也会保持相同的数字。
This is what you want:这就是你想要的:
y = 100
for _ in range(y):
x = random.randint(0,1)
print(x)
With the above, you can replace the _
with x
and it will not be affected, but it's better practice to use _
when iterating though an iterable with ever using the values within the iterable.有了上面的内容,您可以将
_
替换为x
并且它不会受到影响,但是最好在迭代可迭代对象时使用_
并使用可迭代对象中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.