用用户输入结束Python程序

-5 投票
1 回答
3994 浏览
提问于 2025-04-20 02:05

我想用用户输入来结束一个程序。我希望他们在需要退出的时候只需按一下 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 个回答

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.

撰写回答