如何在Python的input命令中逐字符打印且避免出现None?
Got it, let's break down why that None is showing up and fix it quickly!
The problem here is that your delay_print function doesn't explicitly return anything—Python automatically returns None for functions without a return statement. When you pass delay_print("\nGET UP? Y/N: ") as an argument to input(), two things happen:
- First,
delay_printruns and prints your prompt character by character. - Then,
input()takes the return value ofdelay_print(which isNone), converts it to a string, and prints that right after your prompt. That's where the randomNonecomes from!
Two easy fixes:
1. Separate the print and input calls (recommended)
This is the cleanest approach—just print your prompt first, then get input without an extra prompt:
# Print your delayed prompt delay_print("\nGET UP? Y/N: ") # Grab user input (no extra prompt needed) GetUp = input()
This keeps your code straightforward and avoids any weird interactions between delay_print and input().
2. Modify delay_print to return an empty string
If you really want to keep the function call inside input(), update delay_print to return an empty string instead of None. This way, input() gets an empty prompt and won't print anything extra:
import time import sys def delay_print(s): for c in s: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.2) return "" # Add this line to return empty string GetUp = input(delay_print("\nGET UP? Y/N: "))
Either way, you'll get the delayed prompt you want without that annoying None popping up. Happy game development!
内容的提问来源于stack exchange,提问作者vanko003

