Python Python Basics Types and Branching If, Else and Elif

Mario Reyes
Mario Reyes
197 Points

What if I want a specific string to be given based on a number range?

How can I make this work?

1 number_of_items_wanted = input("How many items would you like to buy? ")

2 if number_of_items_wanted == This is my question, what if I want to say " any number of items that is equal to, or more than 20" :

3 print("Great!! You get a discount!!")

1 Answer

Oszkár Fehér
Oszkár Fehér
Treehouse Project Reviewer

Hi Mario. If I understand correctly what you want is to be sure that the input is a number, not a string. In your example, if the variable number_of_items_wanted you always get a string even if the user input is a number but there are some tricks go around but it requires more implementation

number_of_items_wanted = int(input("How many items would you like to buy? "))   -->to be sure that the input is a number 

but for this, you will need a try except block

try:
    number_of_items_wanted = int(nput("How many items would you like to buy? "))
except ValueError:
    print("Your input is not a number")

Now this will run only once, if you need to run the input multiple times then it should be added a while loop like this:

while True:  ---> CAUTION with this usage, you need a breakpoint to break the loop
    try:
        number_of_items_wanted = int(nput("How many items would you like to buy? "))
        if number_of_items_wanted >= 20:    --> a condition for the wanted items
            print("Great!! You get a discount!!")
            break    ---> if you don't add the break, it will run forever
    except ValueError:
        print("Your input is not a number")

I hope this is what you are looking for. Happy coding