I'm pretty new so sorry if this is a dumb question.
I watching some python learning videos and was trying to do some different things using the same concepts. In the video, they demonstrated making a grid using user inputed symbols like this:
rows = int(input("How many rows? "))
columns = int(input("How many columns? "))
symbols = input("Please put in a symbol: ")
for i in range(rows):
for j in range(columns):
print(symbol, end="")
print()
From this, I was thinking, "Hey can I make python draw a box using user inputed number of rows and columns?"
I tried making this code:
columns = int(input("How many columns? "))
for i in range(rows):
for j in range(columns)[0]:
print("|", end="")
for j in range(columns):
print("_", end="")
for j in range(columns)[-1]:
print("|", end="")
print()
This didn't run because it says int object is not iterable; however, I'm not sure why? Ranges are able to be used in for loops, but is it not possible to call on a specific value in the range to perform the for loop?
My reasoning for my code is that whenever a number in the range of the column is 0, then I want it to print "|" to make the sides of the box.
CodePudding user response:
When you call range, it essentially creates a list (not quite, but I think of it that way) that the for loop iterates through. When you index range(columns)
you get an integer. You can't iterate through an integer. If you want your first and last column to be a |
, try this code.
for i in range(rows):
print("|", end="")
for j in range(columns - 2):
print("_", end="")
print("|")
CodePudding user response:
You're getting that error because you're trying to do a for loop over an integer rather than something iterable like a list. range(columns)[0]
returns the first element in that range, which is the integer 0
, so your line of code:
for j in range(columns)[0]:
is really saying:
for j in 0:
which python won't like.
To get what you're looking for using a structure similar to the one you shared, you can try this:
for i in range(rows):
for j in range(columns):
if i == 0 or i == rows-1:
print("_", end="")
elif j == 0 or j == columns-1:
print("|", end="")
else:
print(" ", end="")
print()