2

I've just started learning python a month ago and I've been wanting to create a choose your story prompt as one.

It looks like this

while True:
    try:
        party = int(input("How many people joined the party "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue

A few things I noticed and don't know how to fix is this

  1. I can't set a maximum number of people to join the party and without that, it loops constantly with message input no matter what.
  2. I can't stop a negative input
  3. I can't enter a "Please enter a number below that" Sorry if this is dumb, I just came to a website that usually fixed my issues in python and couldn't find something that fixed my issues exactly.
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

1 Answers1

1
while True:
    try:
        party = int(input("How many people joined the party (1-5)?:"))
    except ValueError:
        print("\nSorry, I didn't understand that.")
        continue

    if 0 < party <= 5:
        print(f"{party} people joined") 
        break

    print(f"\nInvalid answer, please insert a number between 1 and 5")

Explanation

The validation of numbers is something you have to do outside the int(input(...)). In my case I verify if the final answer is between 0 and including 5. If it is, I will break the while loop. If the answer is not in that range, I print a message that they have to insert a value in the right range.

Example

How many people joined the party (1-5)?: 0

Invalid answer, please insert a number between 1 and 5
How many people joined the party (1-5)?: I and my best friend

Sorry, I didn't understand that.
How many people joined the party (1-5)?: 3
3 people joined
Thymen
  • 2,089
  • 1
  • 9
  • 13