【问题标题】:How to know if a user has pressed the Enter key using Python如何知道用户是否使用 Python 按下了 Enter 键
【发布时间】:2014-06-01 11:04:09
【问题描述】:

如何知道用户是否使用 Python 按下了 Enter

例如:

user = raw_input("type in enter")
if user == "enter":
    print "you pressed enter"
else:
    print "you haven't pressed enter"

【问题讨论】:

  • 好吧,如果他们不按 Enter,raw_input 将不会返回,因此检查似乎是多余的。你想达到什么目的?你能检查一下你的语法和格式吗?就目前而言,这不是 python。
  • 嗨,对不起,我是一名学生,仍处于编程学习曲线的初期。我的任务是创建一个程序,该程序只有在用户按下回车键时才会执行任务。您能否详细说明格式和语法有什么问题。
  • julienc 已为您修复了格式和语法 - 您缺少冒号并使用 =(赋值)而不是 ==(比较)。 raw_input 将等到按下 Enter 键,因此不适合您尝试执行的操作。此外,"enter" 是一系列字符,不是 Enter 键。
  • 您应该使用 \n 作为输入。这意味着换行符。

标签: python


【解决方案1】:

正如@jonrsharpe 所说,正确退出input 函数的唯一方法是按回车键。因此,一个解决方案是检查结果是否包含某些内容:

text = input("type in enter")  # or raw_input in python2
if text == "":
    print("you pressed enter")
else:
    print("you typed some text before pressing enter")

我看到退出 input 函数的唯一其他方法会引发异常,例如:

  • EOFError 如果您键入 ^D
  • KeyboardInterrupt 如果你输入 ^C
  • ...

【讨论】:

  • 对于 Python 3.xx,必须使用 input 而不是 raw_input
  • @jeppoo1 你说得对,我是在 2014 年写的,当时 python2 还是一个东西 :) 我刚刚更新了我的答案以符合 python3!
【解决方案2】:
user_input=input("ENTER SOME POSITIVE INTEGER : ")
if((not user_input) or (int(user_input)<=0)):    
  print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
  import sys        #import
  sys.exit(0)       #exit program 
'''
#(not user_input) checks if user has pressed enter key without entering  
# number.
#(int(user_input)<=0) checks if user has entered any number less than or 
#equal to zero.
'''

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2015-12-12
    • 2013-05-24
    • 2016-11-28
    • 2020-11-05
    • 2019-01-07
    • 2021-07-25
    相关资源
    最近更新 更多