Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"try" not passing after "def"

I'm just trying Python, and really like it! But I get stucked with try/except.

I have a code that checks raw_input for being integer, but i'd like to make it function, and it doesn't want to be it :)

here the code, I have this:

number_of_iterations = raw_input("What is your favorite number?")
try:
    int(number_of_iterations)
    is_number = True
except:
    is_number = False

while not is_number:
    print "Please put a number!"
    number_of_iterations = raw_input("What is your favorite number?")
    try:
        int(number_of_iterations)
        is_number = True
    except:
        is_number = False

I don't want to repeat myself here& So I think smth about to make function:

def check_input(input_number):
    try:
        int(input_number)
        return True
    except:
        return False

But it make an error if input a string, saying that int can't be used for strings. Looks like it does not see 'try' keyword. Can smone explain why it happens and how to prevent it in future?

like image 742
Pruntoff Avatar asked Apr 23 '26 12:04

Pruntoff


1 Answers

Try this, it avoids repeating yourself without needing a def

while True:
    try:
        number_of_iterations = int(raw_input("What is your favorite integer?"))
        break
    except ValueError:
        print "Please put an integer!"

EDIT: Per the suggestions of the commenters, I have added break to the try portion of the block to eliminate the else (the original remains as a reference below). Also, I changed "number" to "integer" because "3.14" would be invalid in the above code.

This was my original suggestion. The above is fewer lines (some may call this cleaner), but I prefer the below because to me the intent is clearer.

while True:
    try:
        number_of_iterations = int(raw_input("What is your favorite integer?"))
    except ValueError:
        print "Please put an integer!"
    else:
        break
like image 76
SethMMorton Avatar answered Apr 25 '26 01:04

SethMMorton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!