Home > Software engineering >  How can I request the user to use a value that is not negative?
How can I request the user to use a value that is not negative?

Time:08-29

I was wanting to make a homework assignment that determines the highest user inputted value but I wanted the user to ONLY input positive intergers. Is there a way to make it so that if the user decides to do 'A = -5' for example the code will then say 'please enter a positive value?'

Thanks!

Current Code

CodePudding user response:

Just use another if condition-- if input is less than 0 then display this message.For example, you could put:

if user_input < 0:
    print("please enter a positive value?")

You could also use a while loop to keep prompting the user until they put a positive value. For example:

while user_input < 0:
   print('This is NOT a positive value')
   user_input = int(input("Please enter a positive value"))

CodePudding user response:

Below is the code you can use, working:

  1. Asks user to input a value Please input value for A: -1
  2. Checks if a negative value entered, asks user again Please input a positive value for A: -1
  3. Correct input Please input a positive value for A: 1

it works.

def requestInput(inputLabel):
    val = int(input(f"Please input value for {inputLabel}: "))
    while val < 0:
        val = int(input(f'Please input a positive value for {inputLabel}: '))
    return val

aValue = requestInput("A")
  • Related