【问题标题】:Is it possible to implement a break statement using a user input in python是否可以在 python 中使用用户输入来实现中断语句
【发布时间】:2015-11-08 19:23:10
【问题描述】:
time=0
stop=input()

while time<1000000000000000000000000000000000000000000000000000:
    if stop==input("999"):
        break
    print (time)
    time= time+1
print("time taken is",time) 

这是一个用于平均速度相机的程序。我想知道当用户输入“999”时while循环是否可能停止。代码被破坏的值将是时间变量的新内容。

【问题讨论】:

标签: while-loop user-input break python-3.5


【解决方案1】:

有点不清楚您要完成什么,但根据您提供的代码和您的问题,听起来您想衡量某人输入特定值需要多长时间。可以修改:Python - Infinite while loop, break on user input:

#guess_999.py
import sys
import os
import fcntl
import time

fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)

time_started = time.time()
while True:
    try:
        stdin = sys.stdin.read()
        if "999" in stdin:
            print "It took %f seconds" % (time.time() - time_started)
            break
    except IOError:
        pass

然后运行它:

$ python guess_999.py
$ 6
$ 999
$ It took 2.765054 seconds

【讨论】:

  • 感谢 Brock,这正是我想要完成的。当我在空闲时运行代码时出现语法错误我有 python 3.5
【解决方案2】:

编辑: PO 想做一些完全不同的事情。我参考马克的回答。

你有点搞砸了;)

做:

answer = input("type something")
if  answer == "999":
    break

说明: - input() 将返回用户在控制台中输入的字符串。你写在括号里的内容是当你被要求输入一些东西时将写在行上的内容。这通常是一个诸如“你叫什么名字?”之类的问题。 - 如果答案是“999”,将执行命令中断 => 循环停止

【讨论】:

  • 谢谢你,xXliolauXx,但是当我在我的代码中包含你的答案时,每次我输入一些东西时循环都会重复,因为我希望循环连续执行 time+1 直到输入“999”跨度>
  • @HELP 哦,我从 Brock 的回答中看到了你现在想要完成的工作......我认为你的描述可能更清楚一点;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 2012-10-10
  • 2014-09-10
  • 1970-01-01
相关资源
最近更新 更多