1

I'm new to Python - creating a program which adds up how many animals someone has.

If a user enters a string (e.g. types 'five' or anything else) the program breaks).

What do I need to do to stop the program from breaking & also return the user to the question options?

I have created a loop & an else statement which covers the integers.

loop = 1
while loop == 1:
    a = int(input(
    "Select A Question:"
    "Dog Question: '1'"
    "Cat Question: '2'"
    "Rabbit Question: '3'"
    "Calculate Total Animals: '4'"
    "Enter one of the above options 1-4:"))

if a == 1:
    f = int(input("How many doggos do you have?: "))
elif a == 2:
    h = int(input("How many cats do you have?: "))
elif a == 3:
    s = int(input("How many rabbits do you have?: "))
elif a == 4:
    loop = 0

else:
        print("Please enter a valid value e.g. '1', '2', '3'"
          "To add up your animals '4'")
DeepBlue
  • 45
  • 1
  • 5

4 Answers4

1

First, you don't need to assign loop = 1; while True will do just fine.

Next, the reason is that you are attempting to convert the result of input() to int regardless of whether that is possible. Instead of doing that, you should perform some checks on it and break out of the loop only if those checks are satisfied, for example:

input_prompt = ("Select A Question:"
                "Dog Question: '1'"
                "Cat Question: '2'"
                "Rabbit Question: '3'"
                "Calculate Total Animals: '4'"
                "Enter one of the above options 1-4:")

while True:
    a = input(input_prompt)
    if a.isdigit() and 1 <= int(a) <= 4:
        a = int(a)
        break

    else:
        print("Please enter a valid value e.g. '1', '2', '3'"
              "To add up your animals '4'")
gmds
  • 19,325
  • 4
  • 32
  • 58
  • Ok, and then once I've entered '1' how do I go the actual questions? e.g. where do I put the below questions in the code? f = int(input("How many doggos do you have?: ")) h = int(input("How many cats do you have?: ")) – DeepBlue Mar 31 '19 at 02:36
  • It depends on how you want to structure your program. You could put it after the `while` loop, or replace the `break`. The former would mean that you can only ask one question, which I think is not what you want, so you should probably do the latter. – gmds Mar 31 '19 at 03:15
0

If you want to prevent your program from breaking, the fix is simple. You just need to change you input code to input() instead of int(input()). Surrounding the input with int() forces the user input to be an integer.

If you want to return it back to the user input, you do the following to check if it is not a integer.

if a == 1:
    f = input("How many doggos do you have?: ")
    if not f.isdigit():
        pass

Hope this helps!

programmerskillz
  • 168
  • 1
  • 12
0

Try to use code:

loop = 1
while loop == 1:
    try:
        a = int(input(
        "Select A Question:"
        "Dog Question: '1'"
        "Cat Question: '2'"
        "Rabbit Question: '3'"
        "Calculate Total Animals: '4'"
        "Enter one of the above options 1-4:"))
        loop = 0
    except:
        pass

if a == 1:
    f = int(input("How many doggos do you have?: "))
elif a == 2:
    h = int(input("How many cats do you have?: "))
elif a == 3:
    s = int(input("How many rabbits do you have?: "))
elif a == 4:
    loop = 0

else:
    print("Please enter a valid value e.g. '1', '2', '3'"
          "To add up your animals '4'")
SdahlSean
  • 573
  • 3
  • 13
  • This works for the first menu, but if I enter e.g. 'eight' in any of the below questions I get a 'ValueError: invalid literal for int() with base 10: 'eight' f = int(input("How many doggos do you have?: ")) h = int(input("How many cats do you have?: ")) s = int(input("How many rabbits do you have?: ")) – DeepBlue Mar 31 '19 at 02:47
0

Its best, if you just take in the string at first, then try to get the integer. This way your code won't fail so fast. you can solve your example like this:

# you need to initialise the variables in order to avoid an error when 
# summing them up
number_of_dogs = 0
number_of_cats = 0
number_of_rabbits = 0

while True:
    # Ask for the desired mode after each 'secondary entry'
    a = input(
    "Select A Question:*' \n\
    Dog Question: '1' \n\
    Cat Question: '2' \n\
    Rabbit Question: '3' \n\
    Calculate Total Animals: '4' \n\
    Enter one of the above options 1-4:")

    if a is '1':
        # get the user input as a string
        dogs = input("How many doggos do you have?: ")
        try:
            # try to convert it (you can also combine this with the prior 
            # input(...) but then you're more likely to catch exceptions
            # you don't want to catch)
            number_of_dogs = int(dogs)
        except:
            print("please just enter a digit")
    elif a is '2':
        cats = input("How many cats do you have?: ")
        try:
            number_of_cats = int(cats)
        except:
            print("please just enter a digit")
    elif a is '3':
        rabits = input("How many rabbits do you have?: ")
        try:
            number_of_rabbits = int(rabits)
        except:
            print("please just enter a digit")
    elif a is '4':
        print("You have " 
            + str(number_of_dogs
                + number_of_cats
                + number_of_rabbits)
            + " animals")
        break

    else:
            print("Please enter a valid value e.g. '1', '2', '3'"
            "To add up your animals '4'")

And a small tip still, try to use more explanatory variable names, it makes the code more readable. And you can also use more logical selections at the first input statement: 'Dogs', 'Cats' etc. rather then 1, 2, 3...

Lucas
  • 395
  • 1
  • 11
  • Ok this works well, however the program breaks by entering a string in the first menu (e.g. options 1-4) so if I write 'chicken' it outputs: ValueError: invalid literal for int() with base 10: 'chicken' – DeepBlue Mar 31 '19 at 02:43
  • I fixed that ;) – Lucas Mar 31 '19 at 02:44
  • That works perfect!!! Thanks very much :) One last thing - if I want to force the person to answer the question even if they enter 0, how would I do that? e.g. So the program restricts someone from calculating their total animals until each variable has a value.. – DeepBlue Mar 31 '19 at 03:02
  • Then just skip asking the first question (selecting the mode) and force an answer for each of the three questions then just calculate the result – Lucas Mar 31 '19 at 03:06
  • Oh and @DeepBlue, if you're happy with my answer, would you mind accepting it? I'm trying to build some reputation :D – Lucas Mar 31 '19 at 03:10
  • Hey! Yes, absolutely I can accept it, but how do I do that? haha I was looking for a 'best answer' button or something but I cannot find it :/ – DeepBlue Mar 31 '19 at 03:43
  • @DeepBlue Thanks, at https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work it says: 'To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green' – Lucas Mar 31 '19 at 10:32
  • Done - sorry about the delay :) – DeepBlue Apr 14 '19 at 04:09