【问题标题】:How do I get my small python program to quit when the user enters 'q' or 'quit'?当用户输入“q”或“退出”时,如何让我的小型 python 程序退出?
【发布时间】:2012-01-02 23:40:19
【问题描述】:

我尝试使用 sys.stdout.flush() 刷新标准输出,但它仍然无法正常工作。在用户只输入破坏代码的 C 或 F 之前,它工作正常。后缀是第一个调用的函数 所以我确保如果用户只输入一个字符,则返回错误。但是一旦返回错误,用户就不能再输入“quit”或“q”。

#!/usr/local/bin/python
#Converts between Celsius and Fahrenheit
import random, sys

def check_version():
    """
    Make sure user is using Python 3k
    """
    if(sys.version_info[0] != 3):
        print("Stop peddling with your feet Fred!")
        print("Only Py3k supported")
        sys.exit()
    else:
        pass

def random_insult():
    """
    Returns a list of random insults with the sole purpose of insulting the user
    """
    insults = ["Kel", "stimpy", "knucklehead"]
    return insults[random.randrange(3)]

def suffix(temp):
    """
    Accepts the input temperature value which should be a string suffixed by C(c) or F(f)
    Returns the last element of the input string(C or F)
    """
    if(len(temp) >= 2):
        return temp[len(temp)-1]
    else:
        temperature("Input String TOO Small")

def temp_value(temp):
     """
     Accepts the input temperature value which should be a string suffixed by C(c) or F(f)
     Returns the actual temperature value
     """
     if(len(temp) >= 2):
         return temp[0:len(temp)-1]
     else:
         temperature("Input String TOO Small")

def cel_to_far(temp):
    """
    Accepts the input temperature value as Celsius and returns it in Fahrenheit
    """
    try:
        return ((temp * (9/5.0)) + 32)
    except TypeError:
        return "Has to be a number"

def far_to_cel(temp):
    """
    Accepts the input temperature value as Fahrenheit and returns it in Celsius
    """
    try:
        return ((temp - 32) * (5/9.0))
    except TypeError:
        return "Has to be a number"

def temperature(error=None):
    """
    Loops until the user enters quit or q. Allows the user to enter the temperature suffixed by either C(c) or F(f). 
    If suffixed with C then the temperature is taken as Celsius and converted to Fahrenheit.
    If suffixed with F then the temperature is taken as Fahrenheit and converted to Celsius.
    If the user enters anything else be sure to belittle him/her.
    """
    prompt1 = "Enter value suffixed by C or F *\n"
    prompt2 = "Type 'quit' or 'q' to quit     *\n"
    error1 = "What in the world are you doing "+ random_insult() + "?\n"
    error2 = "Did you forget to add C or F to the end of the value?\n"
    example = "Here's an example of input: 30F\n"
    stars = ("*" * 32) + "\n"
    temp = None
    if(error != None):
        print(error)
        print(example)
        temperature()        
    else:
        while(True):
            sys.stdout.flush()
            try:
                temp = input("\n"+ stars + prompt1 + prompt2 + stars + ">>") 
                if( (temp == 'quit') or (temp == 'q')):
                    return

                elif( (suffix(temp) == 'C') or (suffix(temp) == 'c') ):
                    print("Celsius:", temp_value(temp))
                    print("Fahrenheit: {0:.1f}".format(cel_to_far(float(temp_value(temp)))))

                elif( (suffix(temp) == 'F') or (suffix(temp) == 'f') ):
                    print("Fahrenheit:", temp_value(temp))
                    print("Celsius: {0:.1f}".format(far_to_cel(float(temp_value(temp)))))

                else:
                    print(error1 + error2 + example)

            except:
               print("Something went wrong and I don't care to fix it.\n")
               return

if(__name__  == '__main__'):
    check_version()
    temperature()

【问题讨论】:

  • 你不必马上出来透露你将在文档字符串中侮辱用户。这部分代码被认为是self-documenting
  • 嗯,我想我想更好地记录我的代码,并做了一点。

标签: python python-3.x


【解决方案1】:

问题是temperature 会在发生错误时在不同的地方被递归调用,并且要退出程序,用户必须输入q/quit 的次数与调用temperature 的次数相同。

为了解决这个问题,我建议删除所有递归调用并以不同的方式处理错误。例如,temp 可能会被检查以确保它是来自用户的正确输入,如果不是这种情况,则打印错误消息和continue 无限循环直到break 在输入为@ 时被调用987654328@或quit

【讨论】:

  • 谢谢,这也解释了为什么按q这么多次后它最终会退出
【解决方案2】:

您的程序是递归的,即使您没有执行任何递归操作。

比如温度函数中,有这个位:

if(error != None):
    print(error)
    print(example)
    temperature()     

所以温度函数调用温度函数。相反,你应该做一个

while temperature():
     pass

在主函数中,让温度函数在有人退出时返回 false,永远不要从其他任何地方调用温度函数。

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多