-3

I'm attempting to create a function that allows you to set the maximum height and width in blocks. I need to adjust the max height to &MaxHeight= or none, and the width accordingly so they work with the API I'll be using later.

I've tried adding and removing str() and int() to the input and maxh/maxw, but the error remained. I've also read ValueError: invalid literal for int() with base 10: '', but it seems like the thread creator is experiencing a different issue with the same error message.

This is the code that is causing this error:

print("What is your desired max height and width in blocks? (Enter 0 for none)")
print("")
maxh = str(input("Height: "))
maxw = str(input("Width: "))
print("")

while maxh or maxw is not None:
  if int(maxh) == 0:
    maxh = None
  elif int(maxw) == 0:
    maxw = None
  elif int(maxh) > 0:
    maxh = "&MaxHeight=" + str(maxh)
  elif int(maxw) > 0:
    maxw = "&MaxWidth=" + str(maxw)
  else:
    print(Fore.RED + "The max height or width can not be less than 0. Please enter your desired max height and width in blocks? (Enter 0 for none)" + Fore.WHITE)
    print("")
    maxh = str(input("Height: "))
    maxw = str(input("Width: "))
    print("")

Error with 24 as maxh and maxw:

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    if int(maxh) == 0:
ValueError: invalid literal for int() with base 10: '&MaxHeight=24'
petezurich
  • 9,280
  • 9
  • 43
  • 57
Hadi
  • 17
  • 7

1 Answers1

2

Keeping your ints and strs from getting mixed up is easier if you convert the inputs to int up front and then format them into strings only after you've validated them:

while True:
    print("What is your desired max height and width in blocks? (Enter 0 for none)")
    try:
        h = int(input("Height: "))
        w = int(input("Weight: "))
        if h < 0 or w < 0:
            raise ValueError("The max height or width can't be less than 0.")
        maxh = f"&MaxHeight={h}" if h else None
        maxw = f"&MaxWidth={w}" if w else None
        # We got valid values, so now we can exit the loop.
        break  
    except ValueError as e:
        # We'll jump here if the input is invalid for any reason.
        # Print the error and then implicitly continue the loop.
        print(e)

# maxh and maxw are each now either valid strings or None
print(maxh, maxw)
What is your desired max height and width in blocks? (Enter 0 for none)
Height: asdf
invalid literal for int() with base 10: 'asdf'
What is your desired max height and width in blocks? (Enter 0 for none)
Height: -1
Weight: 4
The max height or width can't be less than 0.
What is your desired max height and width in blocks? (Enter 0 for none)
Height: 20
Weight: 30
&MaxHeight=20 &MaxWidth=30
Samwise
  • 68,105
  • 3
  • 30
  • 44