Reputation: 3
I am creating a game board, but the x axis(the columns) will only print 0 -9 if the number is divisable by 10.
I am able to get the multiples of ten printed(10, 20, ...etc.) and numbers less than ten(0-9). But any numbers between the tens won't print for the last multiple of ten. i.e. x= 15 prints 0123456789
import random
def getHSpace(xMax):
hspace = ' '*3
if xMax >= 10: # print 10+
print(hspace + ('0123456789' * int(xMax/10)))#<--is there a
better way
else: # print 0-9
for i in range(0, int(xMax)):
hspace+=str(i)
print(hspace)
getHSpace(15)
It should print all the numbers until the end of the board. i.e. x=15 should print 012345678901234
Upvotes: 0
Views: 231
Reputation: 12704
You can also do modulo (%).
def getHSpace(xMax):
hspace = ' '*3
num='0123456789'
if xMax >= 10: # print 10+
print(hspace + (num * int(xMax/10)) + num[:xMax%10])
else: # print 0-9
for i in range(0, int(xMax)):
hspace+=str(i)
print(hspace)
Upvotes: 0
Reputation: 542
According to this print:
print(hspace + ('0123456789' * int(xMax/10)))
when 10 <= xMax < 20, int(xMax/10)
will be equal to 1, that's why your print is showing '0123456789' once, when you try xMax >= 20, you will get what you want.
Upvotes: 0
Reputation: 24691
The modulo operator %
is useful for these situations - it stands for "remainder after division". So, 66 % 10 = 6
, or 73 % 12 = 1
, or 21 % 7 = 0
.
In your particular case, you can use it to make a bunch of row headers, individually, and then join them together:
def getHSpace(xMax):
return " " + ''.join(str(i % 10) for i in range(xMax))
This produces str(i % 10)
(that is, a one-digit number but as a string) for every number between 0
inclusive and xMax
exclusive. Then, it joins them together using the empty string as a delimiter.
Upvotes: 2