-1

Almost like an RPG game, I want to make text appear as if someone is typing them. I have an idea of how to do it with the print() function in python, something involving the sleep() and maybe with sys.stdout.flush?

How would I do it text coming before an input function?

For example, I want What is your name? to be typed out, and then the user would input his name.

Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54

2 Answers2

1

You can use this:

text = 'What is your name? '
for x in text:
   sys.stdout.write(x)
   sys.stdout.flush()
   time.sleep(0.00001)
name = input()

you can randomize the sleep time per loop as well to mimic typing even better like this:

import time,sys,random
text = 'What is your name? '
for x in text:
   sys.stdout.write(x)
   sys.stdout.flush()
   time.sleep(random.uniform(.000001, .000019))
name = input()

as Tomerikoo pointed out, some systems have faster/slow delays so you may need to use uniform(.01, .5) on another system. I use OS/X.

On windows this probably works better. Thanks Tomerikoo:

import time,sys,random
text = 'What is your name? '
for x in text:
   print(x, end="", flush=True)
   time.sleep(random.uniform(.000001, .000019))
   # or smaller sleep time, really depends on your system:
   # time.sleep(random.uniform(.01, .5))
name = input()
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
0

You can use the following code:

import time,sys

def getinput(question):
    text = input(question)
    for x in text:
        sys.stdout.write(x)
        sys.stdout.flush()
        time.sleep(0.00001) #Sets the speed of typing, depending on your system

Now everytime you call getinput("Sample Question"), you would get the user's input based on the question you passed to the function.

Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54
  • Thanks for answering. Does this input command work for other questions as well? Would I have to make a def every time asked a new question? – pythongames12 Dec 18 '19 at 23:56
  • I have updated my question. Now use `getinput("Question")`. Any question you pass when you call the function will be printed out – Ibraheem Ahmed Dec 19 '19 at 00:02