0

I want my function to keep asking the user for an input until it satisfies all criteria. My function is as follows:

def PromptNumber(Text, Positive, Integer):

    while True:                                                                 #Keep asking for value until input is valid

        Input = input(Text)

        try:                                                                    #Check if input is float
            Input = float(Input)
        except:
            print('You must enter a valid number.')
            continue

        if Positive:

            if Input < 0:                                                       #Check if input is negative      
                print('You must enter a valid number (positive).')
                continue

        else:
            print("Positive else")

        if Integer:

            try:                                                                #Check if input is integer
                Input = int(Input)
            except ValueError:
                print('You must enter a valid number (integer).')
                continue
            break

        else:
            print("Integer else")
            break

    return Input

Where the parameters are:

  • Text: a string for the question I will ask
  • Positive: a boolean to define whether the input must be positive
  • Integer: a boolean to define whether the input must be an integer

This works okay for most questions however when calling the function with 2 True booleans (positive integer) like so PromptNumber("hi", True, True), it will keep asking for an input if the value is negative - as intended. But it will still accept non-integer values as long as they are positive.

yash
  • 1,357
  • 2
  • 23
  • 34
Billy
  • 19
  • 3
  • 4
    You've converted an input of "1.2" into a float of 1.2 and, while int("1.2") throws a ValueError, int(1.2) doesn't. It results in 1. Retain the string and run int() against the string. – jarmod Feb 16 '20 at 16:36
  • Related: [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii Feb 16 '20 at 16:37
  • To format code - after pasting it into the question, select it and type `ctrl-k`. [Formatting help](https://stackoverflow.com/help/formatting) ... [more Formatting](https://stackoverflow.com/editing-help) ... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox) – wwii Feb 16 '20 at 16:39
  • You might be able to leverage, [`str.isdigit()`](https://docs.python.org/3/library/stdtypes.html#str.isdigit) and you can check the first character for a `-` sign - `Input[0] == '-'`. – wwii Feb 16 '20 at 16:50

0 Answers0