how can I use input validation to request a positive number and continue the program?

0

I would like an output like this: (I would prefer to use only while and Boolean expressions if possible.)

escribe un numero: -50
debes usar un numero positivo!

escribe un numero: -200
debes usar un numero positivo!

escribe un numero: 200
escribe un segundo numero: -2.5
debes usar un numero positivo!

escribe un segundo numero: 5
escribe un tercer numero: 0
debes usar un numero positivo!

escribe un tercer numero: 200

la suma de tus numeros es x

My code is this:

primer_numero=int(input('escribe un numero?'))

segundo_numero=int(input('escribe un segundo numero'))

tercer_numero=int(input('escribe un tercer numero'))

print('la suma de tus numeros es x')

if primer_numero < 0 or segundo_numero < 0 or tercero_numero < 0:
print('debes usar un numero positivo!!') 

The problem with my code is that it asks you the questions and if you put a negative the program continues. I would like you to ask the same question again and warn you to put positive and just continue with the following questions.

all help is welcome and thanks. (edit: change the code to make it easier to understand)

    
asked by juan 30.10.2018 в 01:47
source

4 answers

1
primer_numero = -1

while primer_numero < 0:
    primer_numero = int(input('cuanto quisieras pedir prestado?: '))
    if primer_numero < 0:
        print('Debe ser un numero positivo')

segundo_numero = -1

while segundo_numero < 0:
    segundo_numero = int(input('cual es el interes anual expresado en porcentaje?: '))
    if segundo_numero < 0:
       print('Debe ser un numero positivo')

tercer_numero= -1

while tercer_numero < 0:
    tercer_numero=int(input('cual va a ser tu pago mensual?'))
    if tercer_numero < 0:
       print('Debe ser un numero positivo')

print('primer_nuemro: ', primer_numero)
print('segundo_nuemro: ', segundo_numero)
print('tercer_nuemro: ', segundo_numero)

I hope it serves you, sure there are better ways but for now this will work

    
answered by 30.10.2018 в 03:16
1

It would be convenient that you write the reading of the data and its validation in a function, in this way instead of having to repeat the code it would be enough to call the function three times.

Once this is done, the validation can be generic, so that the function is passed as parameters the minimum and maximum values that must be accepted for the data. If we do not want  specify one of these values (for example the maximum) we can put None in that parameter to specify that there is no such limit. We will also see that what the user writes is really a valid integer and not anything else, for which we will capture if an exception occurs when trying to convert it to int .

This would be the function:

def input_entero(prompt, min=0, max=None):
    # Repetimos en bucle infinito la petición del dato
    # En realidad el bucle no será infinito pues al tener un dato válido
    # haremos un return y lo abandonaremos
    while True:
        dato = input(prompt)
        # Verificar que ha escrito un número
        try:
            dato = int(dato)
        except:
            print("El dato debe ser un número entero")
            continue  # Volver al bucle

        # Verificar que hay un mínimo especificado y que lo cumple
        if min is not None and dato<min:
            print("El dato debe ser mayor que {}".format(min))
            continue  # Volver al bucle

        # Verificar que hay un máximo especificado y que lo cumple
        if max is not None and dato>max:
            print("El dato debe ser menor que {}".format(max))
            continue  # Volver al bucle

        # Si todo ha ido bien, salir del bucle retornando el dato
        return dato

What could we use like this:

n = input_entero("Introduce un positivo: ")
n = input_entero("Introduce un número entre 1 y 10: ", min=1, max=10)
n = input_entero("Introduce un número negativo: ", min=None, max=0)
    
answered by 30.10.2018 в 09:04
0
def esNumeroPositivo(valor):
    try:
        valor = int(valor)
        if valor > 0:
            return valor
        print("'" + str(valor) + "', no es positivo, intente nuevamente.")
        return False
    except:
        print("'" + str(valor) + "', no es un número.")
        return False

def solicitarNumeros(pregunta):
    respuesta = False
    while respuesta is False:
        respuesta = esNumeroPositivo(input(pregunta))
    return int(respuesta)


numero_uno = solicitarNumeros("Ingrese el PRIMER número por favor: ")
numero_dos = solicitarNumeros("Ingrese el SEGUNDO número por favor: ")
numero_tres = solicitarNumeros("Ingrese el TERCER número por favor: ")
print(numero_uno)
print(numero_dos)
print(numero_tres)

print('La suma de tus números es: ' + str(numero_uno + numero_dos + numero_tres))
    
answered by 30.10.2018 в 17:04
0

Actually what you ask is very simple and can be addressed in several ways, one of which I propose:

First we define a function that checks if the number is integer (and in passing it is a number)

def entero(texto):
    while True:
        numero = input(texto)
        if str(numero).isnumeric() and int(numero) = 0:
             return int(numero)
        else:
             print('escribe un numero positivo')

Then we have several options, one of them add the three numbers consecutively and apply it to the print

resultado = entero('escribe el primer número') + entero('escribe el segundo número') + entero('escribe el tercer número')
print('La suma de tus números es', resultado)

As you can see the function saves us having to write extra code

    
answered by 30.10.2018 в 16:42