【问题标题】:Python input() for ENTER用于输入的 Python 输入()
【发布时间】:2021-08-29 08:48:36
【问题描述】:

ENTER 键的输入是什么?

tf_end=str(input("TF end: "))
tfend={"":7,'1':0,'2':1,'3':2,'5':3,'10':4,'15':5,'30':6,'1h':7}
while not any(x in tfend.keys() for x in tf_end):  
      tf_end=str(input("TF end: "))

因为我做了上面的逻辑,但“”不等于 ENTER(不能转义 while 循环)。 如何使用 ENTER 键转义这个 while 循环?

【问题讨论】:

  • 提示:list('') == [] 和 any([]) == False
  • 注意,str(input(...)) 是多余的。 input总是返回str
  • @juanpa.arrivillaga 可能是 Python 2 遗留下来的一个坏习惯。

标签: python input enter


【解决方案1】:

当您只按 Enter 时,input() 返回空字符串。您的代码不起作用,因为空迭代的any() 是False。另请注意,它仅适用于多字符键,因为它们的第一个字符也是键。

您似乎无意中使用了any()。请改用if not tf_end in tfend。

我也会做一些其他的改变:

tfend = {'': 7, '1': 0, '2': 1, '3': 2, '5': 3, '10': 4, '15': 5, '30': 6, '1h': 7}
tf_end = None  # Sentinel value instead of a duplicate `input()`
while not tf_end in tfend:  # `.keys()` is implied
    tf_end = input("TF end: ")  # `str()` is redundant

【讨论】:

  • 不能工作..如何将ENTER声明到列表中?
  • @uyin 什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 2018-05-28
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多