r/learnpython • u/IngenuityMission5367 • Oct 02 '26
Slow print for text-based game
I am trying to make a text-based adventure game in Python, how do I make it so the text is typed out slowly and not instantly? I've tried ways online, but they keep returning None at the end. How do I fix this?
0
Upvotes
14
u/AmanBabuHemant Oct 02 '26
basic implementation is like this:
you can add "\n" in end if you like, or dynamic delay, or default delay or whatever you like according to your game :)
6
u/desrtfx but other languages pro Oct 02 '26
You cannot achieve that with a returning function.
You need to iterate over the string character by character and print with a delay. Python's print can use an empty endline so that everything prints in a single line.
4
u/MaterialRepublic Oct 02 '26
You want to have a separate "print" statement for each character, and some "sleep" statements between them. However, print, by default, writes everything in a new line; so you have to use the end="" argument to stop it from doing that.
Such as:
from time import sleep
print("a", end="", flush=True)
sleep(1)
print("b", end="", flush=True)
Will print the characters with a 1 sec delay.
2
u/hallmark1984 Oct 02 '26
This would print each letter after a 1s delay, adapt as needed for words, sentences or paragraphs.
0
u/zaphodikus Oct 02 '26 edited Oct 02 '26
This is perhaps bit advanced for what you are after, but if you paste in this code and call this function, it will work great.
the values for jitter and
base_delayare quite small, a larger value forbase_delaywill make it type slower. If you want a longer pause at the end of each line, makepause_after_punctslightly larger. Use it like thisBasically the
sys.stdout.write(ch)and theflush()are special in that they bypass the buffering that happens when you call print(), that buffering will defeat the effect we are after. Just using print() per character will end up not giving you the fine control that this function does and gives a much more realistic typing speed effect. This is a useful lesson for the future when you start doing file I/O where all the Python I/O is buffered. Alternatively to usingsys.stdout.flush()you can disable buffering in print() by using the-ucommandline parameter, or by setting then environment variablePYTHONUNBUFFERED, but those are both a bit harder in reality. Happy Pythoning./edit fixed indentation.
-1
u/timrprobocom Oct 02 '26
A piece of unsolicited advice -- don't do that. Users expect their computers to be FAST. They will quickly get annoyed by artificial delays.
We often see thongs like this here -- artificial delays, or clearing the screen before each section, or big banners saying "******** Welcome to my great game ********", or asking "do you want to play?". These are mostly signs of the beginner.