Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Logic in Python The Exception to the Rule

Loop back to input if input is not number.

As the title states, how do i make function loop back to input if the input is not number?

try: count = int(input("Give me a number: ")) except ValueError: print("That's not a number!") else: print("Hi " * count)

2 Answers

andren
andren
28,558 Points

You would have to create a loop manually using a while or for loop. try/except/else statements have no built in looping features.

A simple example would be something like this:

while True: # True is always True so the loop will go indefinitely unless you stop it manually
    try:
        count = int(input("Give me a number: "))
    except ValueError:
        print("That's not a number!") 
    else: 
        print("Hi " * count)
        break # break will stop the loop

My bad, I tried the same thing just moments ago, but my indentation was off. Thanks a lot :D