为什么Python中的input()处代码会停止 - 这有什么好处?

2 投票
2 回答
599 浏览
提问于 2025-04-18 15:44

大家都知道,Python在遇到input()时会停下来或者暂停,这让我们在设置输入超时时变得很困难。不过,这种情况是可以解决的:

import tkinter as tk

class ExampleApp(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        def well():
            whatis = entrybox.get()
            if whatis == "": # Here you can check for what the input should be, e.g. letters only etc.
                print ("You didn't enter anything...")
            else:
                print ("AWESOME WORK DUDE")
            app.destroy()
        global label2
        label2 = tk.Button(text = "quick, enter something and click here (the countdown timer is below)", command = well)
        label2.pack()
        entrybox = tk.Entry()
        entrybox.pack()
        self.label = tk.Label(self, text="", width=10)
        self.label.pack()
        self.remaining = 0
        self.countdown(10)

    def countdown(self, remaining = None):
        if remaining is not None:
            self.remaining = remaining

        if self.remaining <= 0:
            app.destroy()
            print ("OUT OF TIME")


        else:
            self.label.configure(text="%d" % self.remaining)
            self.remaining = self.remaining - 1
            self.after(1000, self.countdown)

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

我真正想问的是,为什么代码在input时会暂停,主要这样做有什么好处呢?

如果我们可以绕过这个问题(我想几乎所有情况都可以),那么让代码这样停着不动不是很傻吗?欢迎大家发表意见,告诉我你的看法。

2 个回答

1

一个好处是什么呢?如果你的代码遇到了一个应该被设置的变量,但因为用户还没有输入值而不存在,这时就会出现错误。举个例子:

legal_age = 21
age = int(input("Your age: "))

if age >= legal_age:
    print("You can drink legally!")
else:
    print("You can't drink yet!")

这是一个简单的例子,但不管怎样——如果Python在没有值的情况下使用了年龄这个变量,会怎么样呢?因为它没有暂停等待输入。

不过,线程可以很容易地用于那些你希望在输入后进行的操作。

1

也许应该有一个内置的功能来禁用暂停。这会让多线程编程变得简单很多,但暂停在你需要测试一些通过输入创建的变量时是很有用的:

input1 = input("enter a big number")
if input1 >= 8:
    print("That is a big number")
else:
    print("That is tiny...")

如果没有暂停直接运行这个代码,你会遇到一个错误,提示input1没有定义,所以暂停是非常重要的。希望这对你有帮助。

撰写回答