I'm trying to print a rectangle according to user input that is given for height, width, border mark, and inner mark. I can't figure out how to do this when it is optional for the user to give an input for the marks, and if the user doesn't give inputs for them they should be # and " ". Is there a way to get border_mark = input() or "#"
to work here, or is this simply wrong?
def print_box(height, width):
for i in range(height):
border_mark = input() or "#"
inner_mark = input() or " "
if i == 0 or i == height - 1:
print(border_mark*(width 2))
else:
print(border_mark inner_mark*width border_mark)
print()
def main():
height = int(input())
width = int(input())
print_box(height,width)
if __name__ == "__main__":
main()
I get ValueError: invalid literal for int() with base 10 when trying to run my code.
CodePudding user response:
Your only mistake is that you put the border_mark = input() or "#"
inside the the for loop.
Do this instead.
def print_box(height, width):
border_mark = input() or "#"
inner_mark = input() or " "
for i in range(height):
if i == 0 or i == height - 1:
print(border_mark*(width 2))
else:
print(border_mark inner_mark*width border_mark)
print()
def main():
height = int(input())
width = int(input())
print_box(height,width)
if __name__ == "__main__":
main()
Output:
5
5
#######
# #
# #
# #
#######
CodePudding user response:
You just have to refactor the input outside the for-loop:
def print_box(height, width):
border_mark = input("border_mark: ") or "#"
inner_mark = input("inner_mark: ") or " "
for i in range(height):
if i == 0 or i == height - 1:
print(border_mark*(width 2))
else:
print(border_mark inner_mark*width border_mark)
print()
def main():
height = int(input("height: "))
width = int(input("width: "))
print_box(height, width)
if __name__ == "__main__":
main()
I added some strings to the inputs, so you can see what you are required to type in next. You could also put the border-input inside the main-function and give it as a parameter to the print_box-function.
The syntax of border_mark = input() or "#"
is totally fine, pythonic and readable in my opinion.
The problem with the ValueError probably comes from you not giving a string that can be cast to an integer as an input. You could add some validation syntax maybe using an infinite while-loop that repeats asking for input until a valid input is given and then leaves the while-loop. You could do this too for the marks given by input as right now you allow any length of mark, try out giving it a border_mark like "xxxxxxxx"
.