Pregunta

Actualmente estoy escribiendo un programa que resolverá el teorema de Pitágoras. Sin embargo, tengo un error en el programa. Cada vez que pongo un número negativo para la longitud A o B, imprime "A no puede ser menos de cero", pero continúa y se resuelve para C de todos modos e imprime la longitud de C a pesar de que el usuario aún no ha ingresado B. ¿Cómo puedo hacerlo, así que cuando el usuario ingresa un número negativo, imprime la afirmación "A no puede ser menos de cero" y luego vuelve a ingresar una longitud para el lado, en lugar de cómo es ahora donde después de imprimir el ¿Declaración, redirige al final?

Aquí está mi código:

 import math
    print"This program will solve the pythagorean theorem for you"
    unit=raw_input('Enter the unit you will be using')
    a=float(raw_input('Enter the length of side a'))
    if a<=0:
      print"A cannot be less than zero"
    else:
        b=float(raw_input('Enter the length of side b'))
    if b<=0:
      print"B cannot be less than zero"
    else:
        c2=(a**2)+(b**2)
        c=math.sqrt(c2)
        c=str(c)
        print "The length of side C is: "+ c + " " + unit + "."
¿Fue útil?

Solución 2

Bueno, para empezar, si desea verificar constantemente sus entradas, tendrá que usar un bucle. Como en, el PsuedoCode para el algoritmo debería ser:

Loop Begin
Check the value of a and b
If a or b is less than 0 then ask for input again
Otherwise, continue

Tenga en cuenta que el algoritmo posee correr al menos una vez.

Así es básicamente como el psuidocódigo debería parece. Entonces, este es un caso en el que puedes usar un do-while construcción de bucle. En Python, no hay algo como esto, así que nosotros emular eso:

import math


def take_in():
    a = raw_input("Enter the value of side a -> ")
    b = raw_input("Enter the value of side b -> ")

    # Trying to convert to a float
    try:
        a, b = float(a), float(b)
        # If successfully converted, then we return
        if a > 0 and b > 0:
            return a, b
    except ValueError:
        pass
    # If we cannot return, then we return false, with a nice comment

    print "Invalid input"
    return False


def main():
    # Calling the function at least once
    valid = take_in()

    # While we are not getting valid input, we keep calling the function
    while not valid:
        # Assigning the value to valid
        valid = take_in()

    # Breaking the return tuple into a and b
    a, b = valid
    print math.sqrt(a ** 2 + b ** 2)


if __name__ == '__main__':
    main()

Otros consejos

Te perdiste un nivel de sangrado. Pruébelo así:

if a<0:
  print"A cannot be less than zero"
else:
    b=raw_input('Enter the length of side b')
    b=float(b)
    if b<0:
        print"B cannot be less than zero"
    else:
        c2=(a**2)+(b**2)
        c=math.sqrt(c2)
        c=str(c)
        print "The length of side C is: "+ c + " " + unit + "."

Intenta evitar usar anidadas if Al diseñar el flujo del programa. Conduce a este tipo de error (falta un nivel de sangría). Grandes trozos de código en el interior if bloques y muchos anidados if Los bloques hacen que el programa sea más difícil de seguir y razonar.

En su lugar, puede volver a preguntar hasta que la entrada sea válida:

a = -1
while a < 0:
    try:
        a=float(raw_input('Enter the length of side a'))
    except ValueError:
        pass
    if a<0:
        print "A cannot be less than zero"

El consejo de Fred es bueno, envuélvalo en una función para reutilizar:

def validate(initial, prompt, test, message, typecast=str):
    value = initial
    while not test(value):
        try:
            value = typecast(raw_input(prompt))
        except ValueError:
            print "Invalid value"
            continue

        if not test(value):
            print message
            continue

        return value

Entonces usa:

a = validate(
    initial = -1, 
    prompt = 'Enter the length of side A', 
    test = lambda x: x >= 0,
    message = "A cannot be less than zero",
    typecast = float
)
b = validate(
    initial = -1, 
    prompt = 'Enter the length of side B', 
    test = lambda x: x >= 0,
    message = "B cannot be less than zero",
    typecast = float,
)

Descargo de responsabilidad: estoy usando una versión diferente de Python, por lo que el kilometraje puede variar

import math

a = 0
b = 0

def py_theorem(a, b):
    return(a**2 + b**2)


unit = raw_input('Enter the unit you will be using: ')

while a <= 0:
a = float(raw_input('Enter the length of side A: '))
if a <= 0:
    print('A cannot be less than 0.')

while b <= 0:
b = float(raw_input('Enter the length of side B: '))
if b <= 0:
    print('B cannot be less than 0.')

print('The length of the 3rd side C is %d %s') % (py_theorem(a,b), unit)

Ahora, si mira mi código A, B son 0 inicialmente, por lo que puede ejecutar los bucles mientras recibe un error, el intérprete no sabe sobre A, B hasta ese punto). Luego repite las declaraciones que solicitan A, B respectivamente hasta que obtenga una entrada válida (válida en un sentido genérico, no hacemos verificación de errores, ¿qué sucede si usa una cadena? Definitivamente miraría los documentos de Python y vería qué %d %s, etc. Luego pasamos el retorno del método (vea el def py_theorem arriba) a la cadena junto con una unidad. Tenga en cuenta que la función toma dos argumentos A, B respectivamente.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top