some_user_3
some_user_3

Reputation: 423

How to use time.sleep() within a function correctly?

Long story short i am making an rpg game (text based) in python and need a little help. I am using the time library to give a delay between certain ASCII banners popping up in the console. However, i dont want to have to write out 'time.sleep()' or copy and paste it every time i want to use it. Therefore, i made a function which I would use to shorten the time it would take me to right out 'time.sleep()':

def wait(time):

    time.sleep(time)

wait(1)

Whilst in theory i thought this would work (im new to python, i have much to learn yet), it gives me this error:

    time.sleep(time)

AttributeError: 'int' object has no attribute 'sleep'

I was wondering if anyone could help/point me in the right direction on how to go about this problem. Thanks in advance!

Upvotes: 0

Views: 1061

Answers (2)

Fred Larson
Fred Larson

Reputation: 62113

You could use a different name for your parameter, so it doesn't hide the namespace within your function:

def wait(period):
    time.sleep(period)

Or you could eliminate your function altogether by importing sleep under a different name:

from time import sleep as wait

Upvotes: 1

chepner
chepner

Reputation: 532303

You are using the same name for the module and the function parameter, so the parameter (a local variable) is shadowing the module (a global variable). Change the parameter:

def wait(how_long):
     time.sleep(how_long)

Upvotes: 3

Related Questions