-3

I'm new to python. I wonder if there any way to make countdown program in python without using any external library and time.sleep method? Please give me an example with code. thanks in advance.

3 Answers3

0

You could use the Unix Timestamp, which gives you a precise value of the seconds wich have passed since the first day of 1970. By substracting a startvalue of this from the actual time each checking time, you can calculate the time that has passed since your desired time. You can get the Unixseconds in python with

time.time()

Of course, this would require importing the time module, but this is a builtin library hence why I wouldnt classify it as additional library.

ductTapeIsMagic
  • 113
  • 1
  • 8
0

Simple answer:
No, it is not directly possible to wait without any imports. The Python modules do this very efficiently, you should use them.

But there's a dirty option for UNIX/Linux:
Without any imports you could read the time (and the progressing of time) from /proc/uptime and build a wait function on your own.

Note that this is not in any way the best practice and very inefficient. But, if you really can't use modules in your program it could look something like this:

def wait(seconds):
    uptime_start = getUptime()
    uptime = uptime_start
    while(uptime != uptime_start + seconds):
        uptime = getUptime()
    
def getUptime():
    with open("/proc/uptime", "r") as f:
        uptime = f.read().split(" ")[0].strip()
    return int(float(uptime))

print("Hello, let's wait 5 seconds")
wait(5)
print("Time passed quickly.")

This does not work for Windows. There are no alternatives, as none of Python 3.9.6 built-in functions (see https://docs.python.org/3/library/functions.html) allow for the measuring of time.

If you want your Python code to stop at some point without freezing other parts of your program, you won't get around using modules.

It would work like this:

import threading

def waitForThis():
    print("now the time has passed")

# after 5 seconds, 'waitForThis' gets executed
timer = threading.Timer(5.0, waitForThis)
timer.start()

print("I can write this while it's running")
MK2112
  • 13
  • 1
  • 5
0
number = 5
print("Countdown!")
while True:
 print(number)
 number = number - 1
 if number <= 0:
  break

print("Now!")

ez pz