1
def validnumber():
    notValid=True
    while(notValid==True):
        number=input('Enter number between 0 and 9->')
        if number=='':
            print('Empty input!')
        else:
            try:
                number=int(number)

            except ValueError:
                print('Number not an int value!Try Again!')
            else:
                if number>=0 and number<=9:
                    notvalid=False
    return number

def main():
    myvalidnumber=validnumber()
    print(myvalidnumber)

main()      

Hey guys. I wrote this program and just had 1 question.

-> the program does not end even if i enter a number between 0 and 9. Could anyone explain why is this happening?.

Thanks in advance :)

4
  • there is one orphan else: in your code after except Commented Mar 20, 2014 at 11:48
  • Actually, you can have an else with try-except. Commented Mar 20, 2014 at 11:50
  • orphan else: ? So it wouldn't work if there was an else inside an else? Commented Mar 20, 2014 at 11:50
  • Check the second else with wrong variable notvalid that would be notValid Commented Mar 20, 2014 at 11:50

2 Answers 2

2

Python's variables are case sensitive. notvalid is not the same as notValid. So, when you say

notvalid=False

you are creating a new variable. Just change it to

notValid = False

and you are fine.

Sign up to request clarification or add additional context in comments.

7 Comments

Fantastic. You are absolutely right. I make sure to remember this but miss here and there. Thank you!
@vishal use a good editor like Sublime text or something. They autocomplete the variable names.
@thefourtheye: let's not start an editor war here :)
@JayanthKoushik That was just a suggestion, I am not trying to sell sublime ;)
@thefourtheye will definitely look into it. New to python. THANK YOU!
|
0

You already got the solution from thefourtheye. Just for the record: the canonical way to implement such a function in Python is to use an infinite loop and either a break statement or an early return (as in the example below). Also proper use of the continue statement can simplify the flow:

def validnumber():
    while True:
        number=input('Enter number between 0 and 9->')
        if number=='':
            print('Empty input!')
            continue

        try:
            number=int(number)
        except ValueError:
            print('Number not an int value! Try Again!')
            continue

        if number < 0 or number > 9:
           print('Number not between 0 and 9! Try Again!')
           continue

        return number

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.