0

Currently using 3.8.1.

I was wondering how I could make a while True: loop like in the example below, but using a number that the user inputted instead of a word (for example any number equal to or lower then 100 would print something different. I've looked on this website, but I couldn't understand the answers for questions similar to mine.

while True:
    question = input("Would you like to save?")
    if question.lower() in ('yes'):
        print("Saved!")
        print("Select another option to continue.")
        break
    if question.lower() in ('no'):
        print ("Select another option to continue.")
        break
    else:
        print("Invalid answer. Please try yes or no.")
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 4
    `('yes')` is not a tuple with one element; it's just a parenthesized string expression. `... in ('yes',)` would do you want you expect, but there's no reason to use `in` with a hard-coded single-element container: just use `question.lower() == 'yes'`. – chepner Feb 03 '20 at 20:38
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo Feb 03 '20 at 20:48

4 Answers4

1

How about including less than / great than clauses in your if statements?

while True:

    # get user input:
    user_input = input("Would you like to save? ")

    # convert to int:
    number = int(user_input)

    if number <= 100:
        print("Saved!")
        print("Select another option to continue.")
        break
    elif number > 100:
        print ("Select another option to continue.")
        break
    else:
        print("Invalid answer. Please try yes or no.")
Daniel
  • 3,228
  • 1
  • 7
  • 23
1

you need to extract the number from the input and then run your conditional evaluation of the inputed value.

while True:
        input_val = input("Enter a #?")
        try:
            num=int(input_val)
        except ValueError:
            print("You have entered an invalid number. please try again")
            continue

        if num == 1:
            print("bla bla")
        elif num ==2:
            print("bla bla 2")
        else:
            ...
Cryptoharf84
  • 371
  • 1
  • 12
0

input takes the user's input and outputs a string. To do something with numbers, check if the string is numeric, cast it to an int and do whatever you want

while True:
    answer = input("How many dogs do you have?")
    if answer.isnumeric():
        num_dogs = int(answer)
    else:
        print("Please input a valid number")

snnguyen
  • 334
  • 1
  • 12
0

I think you maybe want a list instead of a tuple.

Could this work:

while True:
    number = input("Enter a number?")
    if int(number) in list(n for n in range(100)):
            print("lower!")
    elif int(number) in [100]:
            print ("exact")
    else:
            print("higher")