如何让程序我循环回到另一个部分?

时间:2016-04-18 01:21:49

标签: python-2.7 loops

很抱歉,如果这个问题被视为“重复”,但我找不到任何与我要求相关的答案。所以,我的问题听起来很复杂,所以我只会告诉你我写的代码以及我想要它做的事情。这是代码:

    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?")

好的很明显,我所做的代码基本上会根据收到的输入告诉你方形,矩形或圆形的区域。它完成了它应该正确的一切,但我想知道我是如何做到的,以便在我的代码的末尾,它说“找到不同形状的区域!键入圆形,方形或矩形!”如果这个人恰好输入了一个不同的单词并且它将它们带到了打印出“那不是一个有效的响应”的else语句,我将如何制作它以便程序将用户带回到它所说的部分“找到不同形状的区域!键入圆形,方形或矩形!“。对所有的话感到抱歉,感谢花时间阅读本文的人!

1 个答案:

答案 0 :(得分:1)

您需要While 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?")

有关控制流程的更多信息here

您的代码中还有很多错误,float(c) > 0 and type(float(c)) == int or float:将始终返回true,因为

  • float(c) > 0,可以是True或False,但如果c是字符串则可以抛出异常
  • type(float(c)) == int or float,有2个陈述
    • type(float(c)) == int,始终为False,因为您将其转换为浮动并且您正在与int进行比较
    • float,这将永远是True

如果要检查变量是否是类型的实例,则应在if语句中使用函数isinstance(obj, class)