如何使ifstatements循环出现,直到用户键入“quit”?

2024-03-29 14:02:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写代码。你知道吗

假设程序启动时,会提示用户以下内容:

Press 1) to check what the temperature is outside.
Press 2) to find out how many miles are on your car.
Press 3) to see how full your gas tank is.
Press 4) to find out how much money you made last week.

无论用户键入什么,都会执行if语句。我希望这个程序继续运行,直到用户退出。尽管如此,作为一个用户,我希望能够不断地按1)或2)的次数。你知道吗

以下是迄今为止我的代码:

x = raw_input("Enter number here: ")

if x == '1':
    weather = 46
    print "%s degrees" % (weather)

if x == '2':
    milesoncar = '30,000'
    print "%s miles" % (milesoncar)

if x == '3':
    gasintank = 247.65
    print "%s miles left in gas tank" % (gasintank)

if x == '4':
    money = '$439'
    print "You made %s last week." % (money)

if x == 'quit':
    print 'Goodbye

我唯一想让这个程序停止的是如果用户键入“quit”

我该怎么做呢?我需要由if语句组成的while循环吗?如果是的话,我该怎么做呢?你知道吗


Tags: to代码用户程序yourifisfind
1条回答
网友
1楼 · 发布于 2024-03-29 14:02:29

只需将所有内容放入while True循环中,然后在用户输入quit时使用break

while True:
    x = raw_input("Enter number here (or 'quit' to end): ")
    if x == 'quit':
        break

    # ...

相关问题 更多 >