2016-04-18 3 views
0

申し訳ありません。この質問が「重複」とみなされても、私が求めていることに関連する回答は見つかりませんでした。だから、私の質問は非常に複雑に聞こえるので、私が書いたコードと私がそれをやりたいことをあなたに示します。ここでは、コードは次のようになります。プログラムを取得する方法別の部分にループバックしましたか?

def area_of_circle(c): 
    if float(c) > 0 and type(float(c)) == int or float: 
     return float(c) ** 2 * 3.14 
    else: 
     return "Needs to be positive" 

def length(l): 
    if float(l) > 0 and float(l) == float or int: 
     return l 

def height(h): 
    if float(h) > 0 and float(h) == float or int: 
     return h 

def area_of_rectangle(length, height): 
    if float(l) > 0 and float(l) == int or float and float(h) > 0 and float(h) == float or int: 
     return float(l) * float(h) 
    else: 
     return "Needs to be positive" 

def area_of_square(a): 
    if float(a) > 0 and type(float(a)) == int or float: 
     return float(a) ** 2 
    else: 
     return "Needs to be positive" 

user_reply = raw_input("Find the area of different shapes! Type circle, square, or rectangle!") 
if user_reply == 'circle' or user_reply == 'Circle': 
    c = raw_input('You chose circle! What is the radius?') 
    print "The area of the cirlce would be", area_of_circle(c) 
elif user_reply == 'Square' or user_reply == 'square': 
    a = raw_input('You chose square! What is the length of one side?') 
    print "The area of the square would be", area_of_square(a) 
elif user_reply == 'Rectangle' or user_reply == 'rectangle': 
    l = raw_input('You chose rectangle! What is the length?') 
    h = raw_input('What is the height?') 
    print "The area of the rectangle would be", area_of_rectangle(l, h) 
else: 
    print 'That is not a valid response!' 
    user_reply = raw_input("Cirlce, square, or rectangle?") 

[OK]を、私は基本的にあなたにそれを受け取る入力に基づいて、正方形、長方形、または円のいずれかのエリアを教えて作られたので、明らかに、このコード。それは正しく行われるはずのすべてを行いますが、コードの最後に「さまざまな形の領域を見つける!円、四角、または四角形をタイプしてください!その人が別の言葉を入力して、それが "それは有効な応答ではありません"と表示するelseステートメントに移動した場合、プログラムを使用してユーザーが "さまざまな形の領域を見つけてください。円、四角、または長方形をタイプしてください! "すべての言葉を残念にして、これを読む時間を取った人に感謝します!

+0

ありがとうございました。今、バグを指摘していただきありがとうございます。私は間違いなくコントロールフローに関するより多くの研究をするつもりです! – Eli

答えて

1

あなたは、制御フローhereWhile Loop(またはFor Loop

while True: 
    user_reply = raw_input("Find the area of different shapes! Type circle, square, or rectangle!") 
    if user_reply == 'circle' or user_reply == 'Circle': 
     ... 
    elif user_reply == 'exit': 
     break 
    else: 
     print 'That is not a valid response!' 
     user_reply = raw_input("Cirlce, square, or rectangle?") 

もっと必要です。

はまた、多くのバグがあなたのコードである

  • float(c) > 0が、そこに、TrueまたはFalseかもしれないが、cは、文字列
  • type(float(c)) == int or floatある場合に例外を投げることができるので、float(c) > 0 and type(float(c)) == int or float:は常にtrueを返しますあなたはfloatとしてそれをキャストし、あなたがint
  • に比較しているので、常に、 Falseになります2文
    • type(float(c)) == intであり、
    • floatあなたは変数があなたのif文で機能isinstance(obj, class)を使用する必要があるタイプのインスタンスであるかどうかを確認したい場合は、これは常にTrue

になります。

関連する問題