0

I'm trying to build my first text-based game in Python 2.7. However, I'm having some trouble with getting input. I want to use sys.stdout.write() to make it look more retro, but I want it to wait for input after it finished printing. When I try to do the raw_input() thing, it prints fine, but in the place where it should wait for input, it prints None instead.

import sys
import time

def print_slow(str):
    for letter in str:
        sys.stdout.write(letter)
        time.sleep(.04)

answer = raw_input(print_slow("Do you wish to begin? (Y/n)"))
martineau
  • 119,623
  • 25
  • 170
  • 301
Owen Strand
  • 77
  • 1
  • 1
  • 6
  • 2
    `raw_input` takes a string as a prompt. Your slowprinting function doesn't return a string, it returns nothing so you get `None` as a prompt. – pvg Nov 12 '17 at 22:21
  • You probably want to call `print_slow(my_string)` *and then* call `raw_input`. – juanpa.arrivillaga Nov 12 '17 at 22:22
  • `print_slow("Do you wish to begin? (Y/n)"); raw_input()` basically. – cs95 Nov 12 '17 at 22:24
  • Does this answer your question? [Random None when printing from raw\_input](https://stackoverflow.com/questions/26922537/random-none-when-printing-from-raw-input) – Georgy Oct 27 '20 at 11:19

1 Answers1

1

There are two challenges you are facing

  1. raw_input accepts a string to print, but your function returns None.
  2. Your output is likely line-buffered so you probably would not see any output anyway.

The solution to the first issue was mentioned in the comments to the question. The solution to the second is simply to flush your output between writing each letter.

import sys
import time

def print_slow(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()  # Force writing to screen even though newline has not been reached.
        time.sleep(.04)

print_slow("Do you wish to begin? (Y/n)")
answer = raw_input()
SethMMorton
  • 45,752
  • 12
  • 65
  • 86