简体   繁体   中英

Testing Valid Input Python

So I have a finished program that accepts an input file with bank account information and parses it up and allows for a few different utilities.

One such utility is adding a transaction to the "database" (just a log file).

The program prompts the user to enter 'w' or 'd' and then an amount (float). This represents a deposit or withdrawal of X amount of money.

I was wondering how to go about making sure that the user entered either 'w' or 'd' AND a correct amount (number).

So, I decided that a while loop with the above condition would work, however I am having trouble getting it work 100%

I initially had:

while input1 is not ("w" or "d")

where input1 would be the first input (w or d) the user enters

However, I also want to check that a number exists.

I had the idea of casting the string input to a float, then checking that but I wouldn't know how to checking if that is right since casting and checking the type wouldn't tell me much.

How would I also check that the user entered in some sort of number.

So to reiterate, I would like the program to re-prompt for input if the user did not enter either:

A) A w or d B) A number (int/float)

Thanks

the expression ("w" or "d") will always evaluate to "w" . Generally, here you want an in :

while input1 not in ("w", "d"):
    ...

As far as handling the case where the input is a number, this is a job for a helper function:

def string_is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Now you can use that with the above to put the whole thing together:

while (not string_is_number(input1)) and (input1 not in ("w", "d")): ...

Which can actually be simplified a little more:

while not (string_is_number(input1) or (input1 in ("w", "d"))): ...

And now a completely different approach, You can actually use a recursive function for this sort of thing. Combine that with python's exception handling and we could probably put together a pretty elegant solution in just a few lines:

def prog_loop():
    # prompt for user's input here:
    input1 = raw_input("Enter a number, or 'w' or 'd':")
    # See if we got a number
    try:
        number = float(input1)
    except ValueError:
        # Nope, wasn't a number.  Check to see if it was in our
        # whitelisted strings.  If so, break early.
        if input1 in ('w', 'd'):
            return function_handle_w_d(input1)
    else:
        # Yes, we got a number.  Use the number and exit early
        return function_handle_number(number)
    # haven't exited yet, so we didn't get a whitelisted string or a number
    # I guess we need to try again...
    return prog_loop()

This will work as long as your user doesn't enter bad input 1000 times.

Try this:

while True:
    if input1 == 'w':
        withdraw()
    elif input1 == 'd':
        deposite()
    else:
        continue()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM