用户按 ENTER 键退出 while 循环

发布于 2024-12-02 06:56:32 字数 487 浏览 0 评论 0 原文

我是一个 python 新手,被要求进行一个练习:让程序循环,直到用户仅点击 请求退出。到目前为止,我已经:

User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
    ...  # Run my program
    if User == # Not sure what to put here
        break

我已经尝试过:(按照练习中的指示)

if User == <Carriage return>

,但这

if User == <Return>

只会导致无效的语法。

我如何以最简单的方式做到这一点?

I am a python newbie and have been asked to carry out an exercise: make a program loop until exit is requested by the user hitting <Return> only. So far I have:

User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
    ...  # Run my program
    if User == # Not sure what to put here
        break

I have tried: (as instructed in the exercise)

if User == <Carriage return>

and also

if User == <Return>

but this only results in invalid syntax.

How do I do this in the simplest way possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

情痴 2024-12-09 06:56:32

我在(没有双关语)寻找其他东西时遇到了这个页面。这是我使用的:

while True:
    i = input("Enter text (or Enter to quit): ")
    if not i:
        break
    print("Your input:", i)
print("While loop has exited")

I ran into this page while (no pun) looking for something else. Here is what I use:

while True:
    i = input("Enter text (or Enter to quit): ")
    if not i:
        break
    print("Your input:", i)
print("While loop has exited")
最单纯的乌龟 2024-12-09 06:56:32

正是您想要的东西;)

来自 答案 /limasxgoesto0">limasxgoesto0 关于“按 Enter 键退出 while 循环而不阻塞”。

导入 sys, select, os

我=0
而真实:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "我正在做事。按 Enter 来阻止我!"
    打印我
    如果 select.select([sys.stdin], [], [], 0)[0] 中的 sys.stdin:
        行=原始输入()
        休息
    我 += 1

The exact thing you want ;)

from answer by limasxgoesto0 on "Exiting while loop by pressing enter without blocking. How can I improve this method?"

import sys, select, os

i = 0
while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "I'm doing stuff. Press Enter to stop me!"
    print i
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line = raw_input()
        break
    i += 1
○愚か者の日 2024-12-09 06:56:32

实际上,我想您正在寻找一个运行循环直到从键盘上按下某个键的代码。当然,程序不应该一直等待用户输入。

  1. 如果您在 python 2.7 中使用 raw_input() 或在 python 3.0 中使用 input(),程序将等待用户按键。
  2. 如果您不希望程序等待用户按下按键但仍想运行代码,那么您需要做一些更复杂的事情,需要使用 kbhit() msvcrt 模块中的函数。

实际上,ActiveState 中有一个解决这个问题的方法。请点击此链接

我认为以下链接也将帮助您更好地理解。

  1. python 跨平台监听按键

  2. 如何获取一次按下一个按键

  3. MS VC++ 运行时的有用例程

我希望这可以帮助您完成工作。

Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.

  1. If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
  2. If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.

Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link

I think the following links would also help you to understand in much better way.

  1. python cross platform listening for keypresses

  2. How do I get a single keypress at a time

  3. Useful routines from the MS VC++ runtime

I hope this helps you to get your job done.

So要识趣 2024-12-09 06:56:32

这适用于使用并行线程的 python 3.5。您可以轻松地调整它,使其仅对特定的击键敏感。

import time
import threading


# set global variable flag
flag = 1

def normal():
    global flag
    while flag==1:
        print('normal stuff')
        time.sleep(2)
        if flag==False:
            print('The while loop is now closing')

def get_input():
    global flag
    keystrk=input('Press a key \n')
    # thread doesn't continue until key is pressed
    print('You pressed: ', keystrk)
    flag=False
    print('flag is now:', flag)

n=threading.Thread(target=normal)
i=threading.Thread(target=get_input)
n.start()
i.start()

This works for python 3.5 using parallel threading. You could easily adapt this to be sensitive to only a specific keystroke.

import time
import threading


# set global variable flag
flag = 1

def normal():
    global flag
    while flag==1:
        print('normal stuff')
        time.sleep(2)
        if flag==False:
            print('The while loop is now closing')

def get_input():
    global flag
    keystrk=input('Press a key \n')
    # thread doesn't continue until key is pressed
    print('You pressed: ', keystrk)
    flag=False
    print('flag is now:', flag)

n=threading.Thread(target=normal)
i=threading.Thread(target=get_input)
n.start()
i.start()
丢了幸福的猪 2024-12-09 06:56:32

使用 print 语句查看当您按 enterraw_input 返回什么。然后改变你的测试来与之比较。

Use a print statement to see what raw_input returns when you hit enter. Then change your test to compare to that.

坦然微笑 2024-12-09 06:56:32

您需要找出当您按下 Enter 键时变量 User 会是什么样子。我不会给你完整的答案,但会给你一个提示:解雇一名口译员并尝试一下。这并不难;) 请注意,默认情况下 print 的 sep 是 '\n' (是不是太多了 :o)

You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)

带刺的爱情 2024-12-09 06:56:32

你快到了。完成此操作的最简单方法是搜索一个空变量,这就是在输入请求中按 Enter 时得到的结果。我下面的代码是3.5

running = 1
while running == 1:

    user = input(str('Enter <Carriage return> only to exit: '))

    if user == '':
        running = 0
    else:
        print('You had one job...')

You are nearly there. the easiest way to get this done would be to search for an empty variable, which is what you get when pressing enter at an input request. My code below is 3.5

running = 1
while running == 1:

    user = input(str('Enter <Carriage return> only to exit: '))

    if user == '':
        running = 0
    else:
        print('You had one job...')
水晶透心 2024-12-09 06:56:32

我建议使用 u\000D。它是 unicode 中的 CR。

I recommend to use u\000D. It is the CR in unicode.

梦里南柯 2024-12-09 06:56:32
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 检查用户是否按下了 Enter 键而没有输入数字。

int(user_input) <= 0 检查用户是否输入了小于或等于零的数字。

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.

情话墙 2024-12-09 06:56:32

这是一个有效的解决方案(类似于原始问题):

User = raw_input('Enter <Carriage return> only to exit: ')
while True:
    #Run my program
    print 'In the loop, User=%r' % (User, )

    # Check if the user asked to terminate the loop.
    if User == '':
        break

    # Give the user another chance to exit.
    User = raw_input('Enter <Carriage return> only to exit: ')

请注意,原始问题中的代码有几个问题:

  1. if/else 位于 while 循环之外,因此循环将永远运行。
  2. else 缺少冒号。
  3. 在 else 子句中,有一个双等于而不是等于。这不执行赋值,它是一个无用的比较表达式。
  4. 它不需要运行变量,因为 if 子句执行 break

Here's a solution (resembling the original) that works:

User = raw_input('Enter <Carriage return> only to exit: ')
while True:
    #Run my program
    print 'In the loop, User=%r' % (User, )

    # Check if the user asked to terminate the loop.
    if User == '':
        break

    # Give the user another chance to exit.
    User = raw_input('Enter <Carriage return> only to exit: ')

Note that the code in the original question has several issues:

  1. The if/else is outside the while loop, so the loop will run forever.
  2. The else is missing a colon.
  3. In the else clause, there's a double-equal instead of equal. This doesn't perform an assignment, it is a useless comparison expression.
  4. It doesn't need the running variable, since the if clause performs a break.
々眼睛长脚气 2024-12-09 06:56:32
if repr(User) == repr(''):
    break
if repr(User) == repr(''):
    break
摘星┃星的人 2024-12-09 06:56:32

一个非常简单的解决方案是,我看到你说过你
希望看到最简单的解决方案。
停止循环后提示用户继续等等。

raw_input("Press<enter> to continue")

a very simple solution would be, and I see you have said that you
would like to see the simplest solution possible.
A prompt for the user to continue after halting a loop Etc.

raw_input("Press<enter> to continue")
孤檠 2024-12-09 06:56:32

这是最好和最简单的答案。使用 try 和 except 调用。

x = randint(1,9)
guess = -1

print "Guess the number below 10:"
while guess != x:
    try:
        guess = int(raw_input("Guess: "))

        if guess < x:
            print "Guess higher."
        elif guess > x:
            print "Guess lower."
        else:
            print "Correct."
    except:
        print "You did not put any number."

Here is the best and simplest answer. Use try and except calls.

x = randint(1,9)
guess = -1

print "Guess the number below 10:"
while guess != x:
    try:
        guess = int(raw_input("Guess: "))

        if guess < x:
            print "Guess higher."
        elif guess > x:
            print "Guess lower."
        else:
            print "Correct."
    except:
        print "You did not put any number."
一萌ing 2024-12-09 06:56:32

如果您希望用户按 Enter 键,则 raw_input() 将返回 "",因此请将 User"" 进行比较

User = raw_input('Press enter to exit...')
running = 1
while running == 1:
    ...  # Run your program
    if User == "":
        break

If you want your user to press enter, then the raw_input() will return "", so compare the User with "":

User = raw_input('Press enter to exit...')
running = 1
while running == 1:
    ...  # Run your program
    if User == "":
        break
失与倦" 2024-12-09 06:56:32

以下是我的作品:

i = '0'
while len(i) != 0:
    i = list(map(int, input(),split()))

The following works from me:

i = '0'
while len(i) != 0:
    i = list(map(int, input(),split()))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文