'Using a function to print an input one letter at a time
I am making a game/quiz in Python, but ran into a small issue. I made a function to print one letter at a time, but when I use that function for an input, it does not work and prints all at once. I've tried making a string for the input and multiple other things. To fix this temporarily, I have just been printing my question, and then using an input function to make an input, but I'm wondering if there is a better way. Here is my code:
import time
import sys
def input1():
input("")
def oneprint(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()
Solution 1:[1]
I think you may want to add the same for loop that requires c inside of your script in your input1 function, here is an example of how you could do such a thing:
import time
import sys
def oneprint(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
def input1():
inp = input("")
oneprint(inp)
oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()
if you try this it will print the desired color that was answered by the player by getting the input and getting each letter and writing it and flushing it through the oneprint function.
Solution 2:[2]
This will display the input and oneprint it:
import time
import sys
def oneprint(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
oneprint("\nLet's get started. What is my favorite color?")
oneprint(input("\n"))
This will hide the input, and oneprint it:
import time
import sys
from getpass import getpass
def oneprint(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
oneprint("\nLet's get started. What is my favorite color?")
oneprint(getpass("\n>"))
Where getpass is a password formatted input
Solution 3:[3]
I figured out the answer. If anyone else is having this issue you should just do:
input(oneprint(Blah Blah Blah Your Question Here))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Freddy Mcloughlan |
| Solution 3 | JE Krupat |
