【问题标题】:How to get program I made to loop back to another part?如何让我制作的程序循环回另一部分?
【发布时间】:2016-04-18 01:21:48
【问题描述】:

很抱歉,如果这个问题被认为是“重复”,但我找不到与我所问问题相关的任何答案。所以,我的问题听起来很复杂,所以我将向您展示我编写的代码以及我想要它做什么。代码如下:

    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 语句,我将如何做到这一点,以便程序将用户带回它所说的部分“找出不同形状的区域!输入圆形、正方形或矩形!”。对所有的话感到抱歉,感谢花时间阅读本文的人!

【问题讨论】:

  • 非常感谢它现在工作得更好了,也感谢指出错误!我肯定会做更多关于控制流的研究!

标签: python-2.7 loops


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2021-12-17
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多