質問

私は現在、ピタゴラスの定理を解決するプログラムを書いています。しかし、私はプログラムにバグがあります。長さaまたはbに負の数を入力すると、「aはゼロ未満になることはできません」が印刷されますが、とにかく先に進んでCを解決し、ユーザーがまだBを入力していない場合でも、Cの長さを印刷します。ユーザーが負の数値を入力すると、「Aはゼロ未満にすることはできません」というステートメントを印刷してから、サイドの長さを再度入力するようにするにはどうすればよいですか。声明それは最後までリダイレクトしますか?

これが私のコードです:

 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 + "."
役に立ちましたか?

解決 2

まず、入力を常に確認する場合は、ループを使用する必要があります。同様に、アルゴリズムのpsuedocodeは次のとおりです。

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

アルゴリズムに注意してください もっている 走る 少なくとも 一度。

それは基本的にPsudeCodeの方法です したほうがいい のように見える。だから、これはあなたが使用できる場合です do-while ループコンストラクト。 Pythonでは、このようなものがないので、 エミュレート それ:

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

他のヒント

あなたは1つのインデンタチーノレベルを逃しました。このように試してみてください:

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

ネストされたものの使用を避けるようにしてください if プログラムフローを設計するとき。この種のバグにつながります(インデントの1つのレベルがありません)。内部の大きなコードのチャンク if ブロックと多くのネスト if ブロックは、プログラムを従うのを難しくし、推論します。

代わりに、入力が有効になるまで再度尋ねることができます。

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"

フレッドのアドバイスは良いです、それを再利用のための関数に包みます:

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

次に使用してください:

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

免責事項:私はPythonの別のバージョンを使用しているので、マイレージは異なる場合があります

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)

これで、私のコードAを見ると、Bは最初は0であるため、whileループを実行できます(そうでなければ、エラーが発生します。また、インタープリターはA、Bのことをその時点まで知りません)。次に、有効な入力を取得するまでそれぞれA、Bを求めるステートメントを繰り返します(一般的な意味で有効、エラーチェックはありません。文字列を使用するとどうなりますか??>。<)今、印刷は少しファンキーです、私は間違いなくPythonドキュメントを調べて、%d%sなどを確認します。次に、メソッドの返品(def py_theorem up topを参照)をユニットとともに文字列に渡します。関数はそれぞれ2つの引数A、Bを取ることに注意してください。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top