Pergunta

Atualmente, estou escrevendo um programa que resolverá o teorema de Pitágoras. No entanto, tenho um bug no programa. Sempre que eu coloco um número negativo para o comprimento A ou B, ele imprime "A não pode ser menor que zero", mas segue em frente e resolve C para C de qualquer maneira e imprime o comprimento de C, mesmo que o usuário ainda não tenha inserido B. Como posso fazer isso, quando o usuário inserir um número negativo, ele imprime a declaração "A não pode ser menor que zero" e depois faz um loop novamente para inserir um comprimento para o lado, em vez de como é agora onde ele imprime o A declaração é redirecionada até o fim?

Aqui está o meu 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 + "."
Foi útil?

Solução 2

Bem, para começar, se você deseja verificar constantemente suas entradas, precisará usar um loop. Como, o psuedocode para o algoritmo deve 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

Observe que o algoritmo tem para correr pelo menos uma vez.

É basicamente assim que o Psuedocode deve parece. Então, este é um caso em que você pode usar um do-while construção de loop. Em Python, não há algo assim, então nós emular, imitar isto:

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

Outras dicas

Você perdeu um nível de indentatino. Experimente assim:

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

Tente evitar o uso de aninhados if Ao projetar o fluxo do programa. Isso leva a esse tipo de bug (faltando um nível de indentação). Grandes pedaços de código dentro if blocos e muitos aninhados if Os blocos tornam o programa mais difícil de seguir e raciocinar.

Em vez disso, você pode perguntar novamente até que a entrada seja 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"

O conselho de Fred é bom, envolva -o em uma função para reutilização:

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

Em seguida, use:

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

Isenção de responsabilidade: estou usando uma versão diferente do Python, para que a milhagem possa 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)

Agora, se você olhar para o meu código A, B é 0 inicialmente para que você possa executar os loops enquanto receberá um erro, o intérprete não sabe sobre A, B até aquele momento). Em seguida, ele repete as declarações pedindo a, b, respectivamente, até que você obtenha entrada válida (válida em um sentido genérico, não fazemos erro de verificação, o que acontece se você usar uma string ??>. <) Agora a impressão é um pouco descolada, Definitivamente, eu olhava para os documentos do Python e veria o que são %d %s etc. Em seguida, passamos o retorno do método (consulte o def py_theorem em cima) para a string junto com uma unidade. Observe que a função leva dois argumentos A, B, respectivamente.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top