limiting invalid input in python 3

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

limiting invalid input in python 3

Post by krona64 on Sat Mar 08, 2014 3:34 pm
([msg=79777]see limiting invalid input in python 3[/msg])

in python 3

I need to limit the number of invalid inputs allowed so that after the given amount of tries the program exits.
invalid is defined by the input being less than zero.
the number of attempts let say is 3

so for instance

Code: Select all
def number():
   
    number = float(input('please enter a number (must be greater thatn zero): '))

    if number >= 0 :

        print ('you choose number:', number)

    else:
        print ('invalid input')

        return


number()


how would I limit the number of invalid input attempts and make it
so that the code would return to asking the question again and prompt for input
but still keep track of previous attempts?
krona64
New User
New User
 
Posts: 18
Joined: Thu Mar 21, 2013 12:20 am
Blog: View Blog (0)


Re: limiting invalid input in python 3

Post by centip3de on Sat Mar 08, 2014 5:04 pm
([msg=79778]see Re: limiting invalid input in python 3[/msg])

First off, please post in the correct subforum next time. Secondly, in order to do this, you'll have to keep a counter and have an input loop. Something like this:

Code: Select all
def number():
    counter = 0
    while(counter != some_number):
        number = float(input('please enter a number (must be greater than zero): '))
        if number >= 0 :
            print ('you choose number:', number)
            break
        else:
            print ('invalid input')
            counter += 1

number()
Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. -Rick Cook
User avatar
centip3de
Moderator
Moderator
 
Posts: 1412
Joined: Fri Aug 20, 2010 5:46 pm
Blog: View Blog (0)



Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests

cron