-1

Hi I am just starting to learn python and it is so exciting!

I am reading this book : https://automatetheboringstuff.com

And if I follow the instructions everything works out, but I have tried to modify things on my own and can't seem to find the logic to it sometimes.

On chapter 2 there is this exercise:

name = ''
while not name:
    print('Enter your name:')
    name = input()
print('How many guests will you have?')
numOfGuests = int(input())
if numOfGuests:
    print('Be sure to have enough room for all your guests.')
print('Done')

And it works fine, however if numOfGuests is not a number I get this error:

ValueError: invalid literal for int() with base 10: ''

My logical thinking was that I can also include that block into a loop with the while command, and tell the program that if the numOfGuests != int it should continue and go back to the print('How many guests will you have?') section.

Can someone help me understand how to make it work?

Thanks!

IkarosKun
  • 463
  • 3
  • 15
  • Look into exception handling. `int(...)` raised the error, you catch it and continue. https://docs.python.org/3/tutorial/errors.html#exceptions. You've bumped into an important part of python programming and it will likely be covered in Automate The Boring Stuff. My suggestion is to table this problem for a bit and continue with the tutorial you are already using. Come back to this later when you have learned more of python. – tdelaney Apr 10 '20 at 03:12

1 Answers1

0

this is something you could implement to make sure your user enters a valid number:

numOfGuests = -1
while(True):
   try:
       numOfGuests = int(input("Please enter number of guests: "))
       break
    except ValueError:
       print("Please enter a valid number")

As mentioned by tdelaney, you can learn more about dealing with multiple types of error at https://docs.python.org/3/tutorial/errors.html.