使用用户输入结束python程序

时间:2014-09-05 19:11:22

标签: python

我正在尝试使用用户输入来结束程序。我希望他们在需要退出时点击 Enter 。我做错了什么?

# 1)Pace.py
# Converts miles per hour to minutes per mile.

print ("Hello! This program will convert the miles per hour you got on your treadmill to >minutes per mile.") # Greeting

def main() :    # Defines the function main

    while True :    # The loop can repeat infinitely for multiple calculations.
        mph = eval (input ("Please enter your speed in miles per hour. ") )    # Asks for >user input and assigns it to mph.
        mpm = 1 / (mph / 60)    # The user input is divided by 60, and that is divided by 1. >This is assigned to mpm.
        print ("Your speed was", mpm, "minutes per mile!")    # Prints out the miles per >minute.
        if mph == input ("") :    # If the user entered nothing...
            break    # ...The program stops
main()    # Runs main.

1 个答案:

答案 0 :(得分:1)

if not mph将捕获一个空字符串作为输入并结束循环。

在检查空字符串作为输入后,不要将eval强制转换为int

 def main() :    # Defines the function main
    while True :    # The loop can repeat infinitely for multiple calculations.
        mph = (input ("Please enter your speed in miles per hour or hit enter to exit. ") )    # Asks for >user input and assigns it to mph.
        if not mph:    # If the user entered nothing...
            break    # ...The program stops
        mpm = 1 / (int(mph) / 60)    # The user input is divided by 60, and that is divided by 1. >This is assigned to mpm.
        print ("Your speed was", mpm, "minutes per mile!")    # Prints out the miles per >minute.
main()    # Runs main.

您应该使用try/except来捕获错误的输入以避免ValueError并检查mph是否为> 0以避免ZeroDivisionError

def main() :    # Defines the function main
    while True :    # The loop can repeat infinitely for multiple calculations.
        mph = (raw_input ("Please enter your speed in miles per hour. ") )    # Asks for >user input and assigns it to mph.
        if not mph:    # If the user entered nothing...
            break    # ...The program stops
        try:
            mpm = 1 / (int(mph) / 60.)    # The user input is divided by 60, and that is divided by 1. >This is assigned to mpm.
        except (ZeroDivisionError,ValueError):
            print("Input must be an integer and > 0")
            continue
        print ("Your speed was", mpm,
        "minutes per mile!")    # Prints out the miles per >minute.
main()    # Runs main.