In Python there is not implicit conversion between types, so language requires you to explicitly decide what exactly are you going to do. This helps to avoid many hard-to debug errors later and I consider it great advantage of Python.
You need to cast your numbers to strings, using built-in str(your_number)
. It would be also good to clear up your code a little...
numbers = range(1,10)
number1, number2, number3, \
number4, number5, number6, \
number7, number8, number9 = numbers
print ("+---+---+---+")
print ("| " + str(number1) + " | " + str(number2) + " | " + str(number3) + " |")
print ("+---+---+---+")
print ("| " + str(number4) + " | " + str(number5) + " | " + str(number6) + " |")
print ("+---+---+---+")
print ("| " + str(number7) + " | " + str(number8) + " | " + str(number9) + " |")
print ("+---+---+---+")
Also, it is not good idea to make variable for each number, better to use container like list. List of numbers from 1 to 10 you can make with range(1,10)
. You can later use it like array.
We can make your code even simpler with use of string substitution:
numbers = range(1,10)
horizontal_sep = "+---+---+---+"
print (horizontal_sep)
print ("| {} | {} | {} |".format(*numbers[0:3]))
print (horizontal_sep)
print ("| {} | {} | {} |".format(*numbers[3:6]))
print (horizontal_sep)
print ("| {} | {} | {} |".format(*numbers[6:9]))
print (horizontal_sep)
Here we mark with {}
places where we insert variables, that we pass inside format(). We put there slices of our number list. Slice is also a list, so we unpack it with *
operator, so each 3-elements long list gets upacked to 3 integers.
Finally, we can see that our slices have some common pattern in their indexes. We can generate it easily using zip()
and range()
builtins, and use it for loop:
numbers = range(1,10)
horizontal_sep = "+---+---+---+"
# zip(...) generates pairs (0, 3) (3, 6) (6, 9)
for start, end in zip(range(0, 10, 3), range(3, 10, 3)):
print (horizontal_sep)
print ("| {} | {} | {} |".format(*numbers[start:end]))
print (horizontal_sep)