如何接受输入而无需按 Enter Python 3 [英] How to accept input without the need to press enter Python 3

查看:24
本文介绍了如何接受输入而无需按 Enter Python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在不需要按回车键的情况下接受输入.我在网上搜索,我得到了一些关于 raw_input 的信息,但我认为在 python 3.0 到来后它变得过时了.有时,我会在整个程序上运行一个 while 循环,因为我想询问用户:继续?(是/否):

i'm wondering how to accept input without the need to press enter. i searched online, and i get something regarding raw_input, but i think that became obsolete after the arrival of python 3.0. sometimes, i run a while loop on a whole program since i want to ask the user: continue? (y/n):

例如考虑代码:

import random

d = input('Toss coin? (y/n): ')

while d != 'n' and d!= 'N':
    c = random.randint(1,2)
    if c == 1:
        print('HEADS!')
    else:
        print('TAILS!')

    d = input('Toss coin? (y/n): ')

但我只想通过不让用户每次都按 Enter 来为我的程序添加更多光晕.只需按 y 或 n,程序就会相应地循环或中断.

but i just want to add more flare to my program by just not having the user press enter everytime. just press y or n and the program loops or breaks accordingly.

好的,这是新代码:

import random
import msvcrt

d = input('Toss coin? (y/n): ')

while d != 'n' and d!= 'N':
    c = random.randint(1,2)
    if c == 1:
        print('HEADS!')
    else:
        print('TAILS!')

    print('Toss coin? (y/n): ')
    d = msvcrt.getwch()

但是 msvcrt 仍然不起作用

but msvcrt still doesn't work

推荐答案

如果您使用的是 Windows,msvcrt 就是答案:

If you are using windows, msvcrt is the answer:

import msvcrt

print ("Please enter a value.")
char = msvcrt.getch()
print char

如果您不使用 Windows,请查看此来源:

If you are not using windows, take a look at the following snippet at this source:

getch = _Getch()
print ("Please enter something: ")
x = getch()
print x

这篇关于如何接受输入而无需按 Enter Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆