python – How to randomly get 0 or 1 every time?
python – How to randomly get 0 or 1 every time?
The problem is that your code generates a single value and then prints it repeatedly. A simplified version of the problem would be this:
k = random.randint(0, 1) # decide on k once
for _ in range(n):
print(k) # print k over and over again
This will generate k
, then print it n
times, but what you want is to generate a new value to print each time
for _ in range(n):
k = random.randint(0, 1) # decide on a k each time the loop runs
print(k)
You can generate the matrix itself using a nested list comprehension (which may be more than you want to know at this point, but worth showing)
[[random.randint(0, 1) for _ in range(n)] for _ in range(n)]
the inner part [random.randint(0, 1) for _ in range(n)]
will give you n
values in the range 0-1. nesting that in another comprehension gives you n
of those.
from random import randint
n = int(input (Enter an interger number:))
matrix = (
[str(randint(0, 1)) for _ in range(0, n)] for _ in range(0, n)
)
for row in matrix:
print .join(row)
FYI. check this documentation about list comprehension
python – How to randomly get 0 or 1 every time?
def printMatrix(n):
return n + 0
def main():
n = int(input (Enter an interger number:))
matrix = ([str(randint(0, 1)) for _ in range(0, n)] for _ in range(0, n))
for row in matrix:
print( .join(row))
main()