How to accept input without the need to press enter Python 3 [duplicate]

空扰寡人 提交于 2019-12-12 19:23:16

问题


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):

for instance consider the code:

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): ')

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.

ok so this is the new code:

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()

but msvcrt still doesn't work


回答1:


If you are using windows, msvcrt is the answer:

import msvcrt

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

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


来源:https://stackoverflow.com/questions/20831773/how-to-accept-input-without-the-need-to-press-enter-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!