### Thread: Need A Grid To Line Up

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
15
Rep Power
0

#### Need A Grid To Line Up

I have this exercise from the Programming in Python 3 book which requires us to create a grid based on random numbers. The user sets the rows, columns, and the minimum and maximum numbers in which the random numbers are pulled out. I completed the code, but when the grid prints out, if any of the numbers are not the same in character length then it throws the whole grid out of whack and does not line up. I know why it's doing this, but I don't know how to get it to line up

Code:
```# ask user for input to create a grid of random numbers

import random

def get_int(msg, mini, default):
while True:
try:
n = input(msg)
if not n and default is not None:
return default
elif int(n) < mini:
print('must be greater than', mini, 'please try again')
else:
return n
except ValueError as err:
print(err)

def create_grid(row, col, minimum, maximum):
rows = ''
for num in range(0, row):
x = random.randint(minimum, maximum)
y = str(x)
rows += y + (' ' * 5)
#print(rows)
return rows

row = get_int('enter row or leave blank for 10: ', 1, 10)
print('row is', row)
row_int = int(row)
col = get_int('enter col or leave blank for 3: ', 1, 3)
col_int = int(col)
print('col is', col)
minimum = get_int('start minimum number or leave blank for 0: ', -1000000, 0)
print('minimum is', minimum)
min_int = int(minimum)
default = 10000
if default < min_int:
default = min_int * 2
maximum = get_int('enter max number or leave blank for ' + str(default) + ': ', min_int, default)
max_int = int(maximum)
print('maximum is', maximum)

grid = []
c = 0
for cols in range(col_int):
numbers = create_grid(row_int, col_int, min_int, max_int)
grid.append(numbers)
c += 1
#print('c is', c)

for bubba in grid:
print(bubba)```
Any ideas?

Any help is much appreciated

Thanks
2. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
May 2013
Location
/dev/null
Posts
163
Rep Power
19
A crude and small modification to your existing script. Used string formatting expression.

Code:
```def create_grid(row, col, minimum, maximum):
max_len = len(str(maximum)) + 2
rows = ''
for num in range(0, row):
x = random.randint(minimum, maximum)
y = str(x)
rows += '%-*s' % (max_len, y)
# rows += '%*s' % (max_len, y) # for right justification of numbers
return rows```
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
15
Rep Power
0
Originally Posted by noobie1000
A crude and small modification to your existing script. Used string formatting expression.

Code:
```def create_grid(row, col, minimum, maximum):
max_len = len(str(maximum)) + 2
rows = ''
for num in range(0, row):
x = random.randint(minimum, maximum)
y = str(x)
rows += '%-*s' % (max_len, y)
# rows += '%*s' % (max_len, y) # for right justification of numbers
return rows```
Awesome, thanks for the help