Domanda

Attualmente sto scrivendo un programma che risolverà il teorema di Pitagora. Tuttavia, ho un bug nel programma. Ogni volta che inserisco un numero negativo per la lunghezza A o B, sta stampa "A non può essere inferiore a zero" ma va avanti e risolve comunque C e stampa la lunghezza di C anche se l'utente non ha ancora inserito B. Come posso farlo quando l'utente inserisce un numero negativo stampa l'istruzione "a non può essere inferiore a zero" e quindi si diffonde per inserire una lunghezza per il lato, anziché come è ora dove dopo aver stampato il Dichiarazione che reindirizza fino alla fine?

Ecco il mio codice:

 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 + "."
È stato utile?

Soluzione 2

Bene, per cominciare, se vuoi controllare costantemente i tuoi input, dovrai usare un ciclo. Come in, il psueDocode per l'algoritmo dovrebbe essere:

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

Si prega di notare che l'algoritmo ha correre almeno una volta.

Questo è fondamentalmente il modo in cui il PsueDocode dovrebbe assomigliare. Quindi, questo è un caso in cui puoi usare un do-while costrutto loop. In Python non c'è qualcosa di simile, quindi noi emulare esso:

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()

Altri suggerimenti

Ti sei perso un livello indentatino. Provalo in questo modo:

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 + "."

Cerca di evitare di usare nidificato if Quando si progetta il flusso del programma. Porta a questo tipo di bug (mancando un livello di rientranza). Grandi pezzi di codice all'interno if blocchi e molti nidificati if I blocchi rendono il programma più difficile da seguire e ragionare.

Invece, puoi chiedere di nuovo fino a quando l'input non è valido:

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"

Il consiglio di Fred è buono, avvolgilo in una funzione per il riutilizzo:

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

Quindi 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,
)

Disclaimer: sto usando una versione diversa di Python, quindi il chilometraggio può variare

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)

Ora, se guardi il mio codice A, B sono inizialmente 0 in modo da poter eseguire i loop di While (altrimenti si ottiene un errore, l'interprete non conosce A, B fino a quel momento). Quindi ripete le dichiarazioni che richiedono rispettivamente a, b fino a quando non si ottiene un input valido (valido in senso generico, non facciamo alcun controllo degli errori, cosa succede se si utilizza una stringa ??>. <) Ora la stampa è un po 'funky, Sicuramente esaminerei i documenti di Python e vedrei cosa sono %d %s ecc. Quindi passiamo il ritorno del metodo (vedere il def py_theorem in alto) nella stringa insieme a un'unità. Si noti che la funzione prende due argomenti A, B rispettivamente.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top