python – Input resulting in None

Question:

I was trying a new one of presenting the texts in a basic game I'm creating, which basically gives the feeling that the text is being written. The code is this below:

def print_slow(txt):
    for x in txt:                     
        print(x, end='', flush=True)
        time.sleep(0.02)
    print()
print_slow("Olá, o dia está belo hoje")

I don't understand a lot about functions, but whenever I try to put this function in an input like:

input(print_slow("Olá, como vai?:"))

it works as it should, except that a None appears where you would type:

Olá, como vai?:
None 

Does anyone know why this occurs, and if there is any way to put an input with this function that makes the text "slow"??

Answer:

That's because your function doesn't have a return and Python automatically returns None when calling the function.

Fixing the problem:

Do you want to write your code so that the user can type on the same line as the printout? Example:

Olá, como vai?: Vou bem.

If so, you must first remove the last print() from your function to prevent line wrapping. After that, separate the print_slow() and input() on different lines so that your function's return None is not passed as a parameter. Example:

import time

def print_slow(txt):
    for x in txt:                     
        print(x, end='', flush=True)
        time.sleep(0.02)

print_slow("Olá, como vai?")
answer = input(": ")

If for some reason you don't want to make all these changes to your code, you can do it in a way that I don't recommend very much, but it might also solve the problem. This way is basically to define an empty string in your function's return. Example:

def print_slow(txt):
    for x in txt:                     
        print(x, end='', flush=True)
        time.sleep(0.02)
    print()
    return ""

This fixes the problem, because when it returns an empty string, it will be passed as a parameter to the input() and the user won't see anything, because the string is empty.

And why don't I recommend it very much? Because it doesn't make sense for your function to return an empty string, even more so it's a function to print text.

Scroll to Top