Как написать таймер на python

У нас когда-то был мини-проект: сделать свой таймер-напоминалку, который спрашивает, про что вам напомнить, а потом выдаёт сообщение через нужное время. В прошлый раз мы его сделали на JavaScript, теперь напишем на Python. Потому что Python — это модно, красиво и приятно.

Отличия и особенности

JavaScript прекрасен тем, что его можно запустить в консоли любого современного браузера. Это для него родная среда, и JS легко работает со страницами, объектами на ней, вкладками браузера и всем, что с ним связано.

Python — более универсальный язык, который работает не только с браузерами, поэтому для него нужен отдельный интерпретатор. Интерпретатор — это программа, которая берёт исходный код и выполняет команду за командой. Вы можете написать отличный код, но чтобы его исполнить, вам всегда нужен будет интерпретатор.

Есть два способа запустить Python-код:

1. Поставить Python себе на компьютер — этот способ хорош, если вы решили основательно изучить язык или просто любите, когда всё быстро и под контролем. Скачать Python можно с официального сайта — есть версии для всех основных операционных систем.

Из минусов — нужно разбираться в параметрах установки и настройки и уметь работать с командной строкой. Плюсы — полный контроль и быстродействие.

2. Использовать онлайн-сервисы, например, этот: onlinegdb.com/online_python_compiler. Работает точно так же — пишете код, нажимаете кнопку Run и смотрите на результат.

Минусы: так как это онлайн-сервис, им пользуется одновременно много человек, поэтому быстродействия от него ждать не стоит. С подключением внешних модулей тоже могут возникнуть проблемы, но с этим можно разобраться, если потратить немного времени.

Плюс: не нужно ничего настраивать и устанавливать, всё работает сразу из браузера. Есть подсветка синтаксиса, сообщения об ошибках и возможность сохранения кода.

Сейчас мы напишем таймер с оглядкой на онлайновый сервис. А отдельно ещё расскажем об установке.

Исходный код на JavaScript

// Спрашиваем текст напоминания, который нужно потом показать пользователю
var text = prompt('О чём вам напомнить?');
// Тут будем хранить время, через которое нужно показать напоминание
var time = prompt('Через сколько минут?');
// Чтобы работать со временем в JavaScript, нам нужно перевести его в миллисекунды. Для этого число минут умножаем на 60 тысяч:
time = time * 60 * 1000;
// Ставим таймер на нужное время с помощью функции setTimeout
setTimeout(function () {
  // Выводим на экран текст напоминания, который хранится в переменной text
  alert(text);
  // Привлекаем внимание к окну мигающим заголовком
  titleAlert();
  // В самом конце функции указываем время, через которое она должна сработать
}, time);

Что мы здесь сделали:

  • спросили текст напоминания;
  • выяснили, через сколько минут нужно напомнить;
  • поставили таймер на нужное время;
  • в нём написали, что когда время выйдет, надо вывести сообщение и помигать заголовком страницы.

Особенность Python в том, что в нём нет встроенных средств работы с браузером и его вкладками, поэтому помигать заголовком пока не получится. С другой стороны, Python не зависит от браузера, поэтому будем использовать штатные средства ввода и вывода сообщений.

Простая реализация на Python

Самое простое, что можно сделать — поставить программу на паузу на нужное время, а потом вывести сообщение. Для этого подключаем стандартный модуль time — он отвечает за работу со временем.

Модуль в Python — это уже готовый python-файл, где собраны запчасти, которые помогают решать какую-то узкую задачу: функции и классы. Например, замерять время, работать с математическими функциями или календарём.

Чтобы сделать паузу, используют команду time.sleep(). Time — это название модуля, который мы подключили, а sleep — функция, которая находится внутри модуля. Её задача — подождать нужное количество секунд, а потом продолжить выполнение программы.

# Подключаем нужный модуль
import time
# Спрашиваем текст напоминания, который нужно потом показать пользователю
print("О чём вам напомнить?")
# Ждём ответа пользователя и результат помещаем в строковую переменную text
text = str(input())
# Спрашиваем про время
print("Через сколько минут?")
# Тут будем хранить время, через которое нужно показать напоминание
local_time = float(input())
# Переводим минуты в секунды
local_time = local_time * 60
# Ждём нужное количество секунд, программа в это время ничего не делает
time.sleep(local_time)
# Показываем текст напоминания
print(text)

Делаем свой таймер на Python

Что дальше: многозадачность и оптимизация

Наша программа уже работает как нужно, но её можно улучшить. Дело в том, что ставить весь код на паузу — не самое удачное решение с точки зрения производительности. Представьте, что вам нужно поставить себе несколько напоминаний на разное время. С таким подходом нам придётся выяснять, какое сработает раньше, потом корректировать время паузы для следующего напоминания и так далее.

Можно сделать так: выносить напоминания в отдельные потоки. Это как подпрограмма, которая работает параллельно с нашей программой и не сильно зависит от неё. Это позволит не ждать первого события, а запускать их одновременно. Но про всё это — в следующем материале.

Python – язык программирования, который можно отнести к общему назначению. С его помощью пишут как бизнес-софт, так и развлекательный (игровой) контент. Это отличное решение для новичков в разработке. Относится к объектно-ориентированному типу.

В данной статье будет рассказано о том, что собой представляет задержка в Python, как использовать time (таймер), для чего все это нужно. Информация пригодится даже опытным разработчикам, которые планируют работу со временем в будущей утилите.

Ключевые термины

Пытаясь освоить Python, программеру потребуется выучить немало теории. Вот базовые термины, без которых время и остальные компоненты кодификаций применять на деле не получится:

  1. Ключевое слово – зарезервированное системой слово или фраза. Обозначает действие, операцию, функцию. Ключевики не могут выступать в виде имен переменных.
  2. Переменная – именованная ячейка памяти, которую можно изменять, сохранять и считывать.
  3. Алгоритм – последовательность действий, набор правил, помогающих решать те или иные задачи.
  4. Класс – набор связанных между собой объектов, которые имеют общие свойства.
  5. Объект – комбинация переменных, констант и иных структурных единиц. Они выбираются совместно и аналогичным образом проходят обработку.
  6. Константа – значение, которое не будет меняться на протяжении всего выполнения утилиты.
  7. Тип данных – классификация информации определенного вида.
  8. Массив – множество данных. Они предварительно группируются.

Огромную роль в Python играют ключевые слова. Их необходимо либо запоминать, либо заучивать, либо держать где-то поблизости справочник с соответствующими данными. Иначе при объявлении переменных не исключены проблемы.

Задержка – это…

Задержка – термин, который применим ко времени. Он встречается и в обыденной жизни. Это – ситуация, когда что-то происходит или должно осуществиться не сразу. Пример – после наступления каких-то обстоятельств.

В программировании задержка «откладывает» выполнение кода на определенное время. Часто такая потребность возникает тогда, когда нужно дождаться завершения иного процесса, чтобы задействовать далее полученный результат.

При рассмотрении многопоточных утилит, использовать таймер (timer) и время (time) нужно, чтобы дождаться завершения операции и функций из других потоков.

Класс Timer

Класс Timer () в Python отвечает за время и работу с ним «от начала по конца». Модуль, метод, используемый для задержки и всего, что с ней связано. Перед использованием оного требуется произвести импорт компонента.

Для этого подойдет запись типа import time в Python. Класс относится к модулю threading. Он создает таймер, который запускает функцию с аргументами и ключевыми значениями (kwargs). Происходит это за счет time, установленного как interval. Этот параметр указывается в секундах.

Программеру предстоит запомнить следующее:

  • Запись функции с классом, отвечающего за таймаут (timeout) –

  • Если args равен None (этот показатель устанавливается изначально), Python использует пустой список.
  • Когда ключевое слово kwargs равен None, применяется пустой словарь.
  • Класс «Таймер» представлен действием, которое нужно запускать только по прошествии конкретного промежутка времени.
  • Таймер выступает в виде подкласса threading.Thread().

Все это требуется запомнить. А еще – учесть, что в процессе коддинга предстоит использовать суперкласс (super class), а также мета данные.

Функции

Рассматривая methods time, программисту требуется изучить разнообразные функции, связанные со временем. Это поможет лучше разобраться в потоках и задержках. Не стоит забывать, что при тестинге важно использовать print. Эта операция выводит результат на экран.

Time.Time

Функция Time() будет возвращать число секунд, которые прошли с начала эпохи. Для Unix-систем это – 1.01.1970. Отсчет с 12 часов ночи ровно.

Ctime()

Компонент, который будет в виде аргумента в Python принимать количество секунд, прошедших с самого начала эпохи. Результат – возврат строки по местному time.

Sleep

Отвечает за непосредственную задержку. Откладывает исполнение нынешнего потока на заданное количество секунд.

Класс struct_time

Изучая, какой метод подойдет для работы с таймерами и super class, стоит обратить внимание на struct_time. Этот объект может быть принят некоторыми функциями в упомянутом ранее модуле. При обработке оного происходит возврат.

Выше – наглядный пример.

Реализация Sleep

Когда нужный метод для работы с задержкой изучен, можно рассмотреть то, как сделать таймаут. Для этого используют super class, а также sleep. Он проходит реализацию несколькими способами:

  • Через time.sleep(). Это – встроенная возможность Python. Отвечает за таймаут через модуль time. Откладывает выполнение потока на установленное количество секунд.

  • Вызов с декораторами. Активируют, когда одно неудачно выполненное действие требуется запустить снова.

  • В потоках. Такие ситуации требуют, чтобы приложение избегало простоя. Для этого применяют или time.sleep(), или Event.wait() из модуля threading.
  • Из Async IO. Асинхронные возможности появились в Питоне, начиная с 3.4 версии. Это – тип параллельного программирования.

  • В Tkinter и wxPython. Отсрочки возможны при создании пользовательских интерфейсов. При применении sleep() внутри GUI кода блокируется цикл обработки событий.
  • After(). Это – метод, который погружает в сон для Tkinter. Часть стандартной библиотеки.

  • CallLater. Метод для wxPython. Имеет больше виджетов и хорошо годится для нативной разработки.

А вот видео, где можно наглядно увидеть работу с таймером в Python. Лучше разобраться с этой темой, как и с языком программирования, помогут дистанционные компьютерные курсы. Программы рассчитаны на срок до года. В конце будет выдан электронный сертификат. В процессе пользователи получат не только хорошо поданный учебный материал, но и новые полезные связи. А еще – соберут портфолио для трудоустройства.

Time tracking is critical to managing your projects. If you’re programming in Python, you’re in luck: The language gives you tools to build your own timers. A timer program can be useful for not only monitoring your own time, but measuring how long your Python program takes to run.

In this article, we’ll present two simple Python timers before looking at the modules you’ll need to create a timer program. We’ll then use these modules to build a stopwatch and a countdown timer, and show you how to measure a Python program’s execution time.

Understanding Timers in Python

A timer in Python is a time-tracking program. Python developers can create timers with the help of Python’s time modules. There are two basic types of timers: timers that count up and those that count down.

Stopwatches

Timers that count up from zero are frequently called stopwatches. We can use these to record the amount of time it takes to complete a task.

Runners often use stopwatch timers to record how long it takes them to complete a lap around a course or finish an entire run. You can use a stopwatch to track how long it takes to complete any task, such as coding a simple program.

Programmers often use stopwatch timers to compare the performance of various Python solutions. By seeing how long each solution takes to execute, you can choose the program that runs the fastest. Over time, this will allow you to better understand computational complexity and build intuition for choosing efficient solutions. These skills go a long way towards becoming a proficient programmer.

Countdown Timers

There are also countdown timers, set with a specific amount of time that depletes until the timer reaches zero. You can use Python to build countdown timers that serve different purposes.

For instance, you can build a cooking countdown timer to ensure you don’t leave food in the oven for too long. Countdown timers can also work to display the time remaining in a sporting event or during an exam. They are also used to count down the hours and minutes to a movie release or big event. The possibilities are endless!

Modules in Python

To create a simple timer in Python, you’ll need to call upon Python’s time and datetime modules.

Modules in Python are files that contain classes, functions, variables, and runnable code. By importing a module into your program, you can make use of each component inside the module.

The Python programming language has over 200 predefined modules within its standard library. You can even create your own modules to use in future programs.

The Python Time Module

One of the 200 modules in Python’s standard library is the time module. This module contains the functions we’ll need to build a simple timer in Python.

To use the time module in Python, we first import it into our program:

Listing modules at the beginning of a Python program makes the functions within the module available for use in our program. The time module holds more functions than we’ll cover here, but here are the most important ones:

The time.time() function

We call the time() function, located in the time module, as time.time(). The first time references the module, whereas the second is the function itself. The time() function returns the number of seconds that have passed since the epoch.

In the computing context, we refer to an “epoch” as the time according to which a computer calculates its timestamp values. Windows and most UNIX devices set the epoch as January 1, 1970 at 00:00:00.

When we use time.time(), we can see the amount of time that has passed since the epoch. We can even use time.ctime() to convert this number of seconds to the current local time. Take a look at this example:

import time

seconds = time.time()
print("Time in seconds since the epoch:", seconds)
local_time = time.ctime(seconds)
print("Local time:", local_time)

In this example, we use time.time() to see how many seconds have elapsed since the epoch. We then convert this length of time to our current local time with time.ctime(). This program outputs the following information:

Time in seconds since the epoch: 1630593076.1314547
Local time: Thu Sep  2 10:31:16 2021

It has been over 1.5 billion seconds since the epoch.

The time.sleep() Function

The other function that we’ll need to build our timer is time.sleep(). This function creates a delay in a program that we can use to count time. time.sleep() takes a float argument representing the number of seconds that the program will pause for. Plug the example below into your Python integrated development environment (IDE) to see how time.delay() works:

import time

print("This is the start of the program.")
time.sleep(5)
print("This prints five seconds later.")

Since we set time.sleep() to five seconds, the program idles for that length of time between outputs.

The Python Datetime Module

datetime is intended for manipulating dates. We’ll use this module to convert different timestamps into a common format that allows us to compare them. 

The datetime.timedelta() Function

We can use timedelta() to express the difference between two dates and/or two times. In the example below, we use timedelta() to show the date one year from now:

import datetime

current = datetime.datetime.now()
print ("Current date:", str(current))
one_year = current + datetime.timedelta(days = 365)
print("The date in one year:", str(one_year))


timedelta() adds 365 days to the current date and outputs the date and time one year from now, down to the microsecond:

Current date: 2021-09-02 14:44:19.429447
The date in one year: 2022-09-02 14:44:19.429447

A Simple Lap Timer (Stopwatch)

Let’s use what we’ve learned to build a stopwatch. Our stopwatch is a lap timer that displays the time to complete a lap as well as total time. Check out the code below:

import time
 
# Timer starts
starttime = time.time()
lasttime = starttime
lapnum = 1
value = ""
 
print("Press ENTER for each lap.nType Q and press ENTER to stop.")
 
while value.lower() != "q":
             
    # Input for the ENTER key press
    value = input()
 
    # The current lap-time
    laptime = round((time.time() - lasttime), 2)
 
    # Total time elapsed since the timer started
    totaltime = round((time.time() - starttime), 2)
 
    # Printing the lap number, lap-time, and total time
    print("Lap No. "+str(lapnum))
    print("Total Time: "+str(totaltime))
    print("Lap Time: "+str(laptime))
           
    print("*"*20)
 
    # Updating the previous total time and lap number
    lasttime = time.time()
    lapnum += 1
 
print("Exercise complete!")

After importing the time module, we set time.time() to the start time of our timer. The stopwatch will count forward from this time. We use the variable lasttime to catalog each lap, whereas totaltime holds the value for the entire time the stopwatch runs. lapnum counts the number of laps we run. Finally, we set the value variable so the user can type “Q” or “q” to end the program.

Time increments in the background while we run the program. Each time the user presses the Enter key, the program displays their lap number, lap time, and total time. Even if you don’t need to record laps, you can still use this timer to track the total time you’re performing a task.

A Simple Countdown Timer

Let’s now build a countdown timer. This example incorporates both the datetime module and the time.sleep() function. Take a look at the program below:

import time
import datetime

# Create class that acts as a countdown
def countdown(h, m, s):

    # Calculate the total number of seconds
    total_seconds = h * 3600 + m * 60 + s

    # While loop that checks if total_seconds reaches zero
    # If not zero, decrement total time by one second
    while total_seconds > 0:

        # Timer represents time left on countdown
        timer = datetime.timedelta(seconds = total_seconds)
       
        # Prints the time left on the timer
        print(timer, end="r")

        # Delays the program one second
        time.sleep(1)

        # Reduces total time by one second
        total_seconds -= 1

    print("Bzzzt! The countdown is at zero seconds!")

# Inputs for hours, minutes, seconds on timer
h = input("Enter the time in hours: ")
m = input("Enter the time in minutes: ")
s = input("Enter the time in seconds: ")
countdown(int(h), int(m), int(s))

Our countdown timer works by having a user input the number of hours, minutes, and seconds for the timer. You can find the code for these inputs at the bottom of the program below the countdown class.

The countdown class itself takes those inputs and converts them into a total number of seconds. As long as total_seconds is greater than zero, the while loop runs. Within the loop, we use the timedelta() function to calculate the time left on the timer.

The program prints the time left in hours:minutes:seconds format for the user to see. Immediately after, the program pauses for one second, reduces total_seconds by one second, and repeats the while loop. The loop continues until total_seconds reaches zero, at which point the program leaves the while loop and prints “Bzzzt! The countdown is at zero seconds!”

Measure Program Execution Time

You can use Python to measure the time it takes for a program to finish execution. This is not very different from what we’ve already done before: We define a starting point, run the program whose time we want to measure, and specify the time at which the program finishes execution. We get the program’s execution time by subtracting the start time point from the end time point.

Let’s compare a few solutions for finding an element within a list. We’ll create a list of 10,000,000 elements and see how long it takes each solution to find the number 700,000.

First, we’ll build a program that makes random guesses until it finds the answer.

v​​import time
import random

our_list = list(range(10000000))
element = 7000000

start = time.time()

random_choice = random.choice(our_list)
while random_choice != element:
    random_choice = random.choice(our_list)

end = time.time()

print(end - start)

The program took 16 seconds to find the element; that’s clearly no good.

Let’s try a better approach. This time, instead of making random guesses, the program will make one pass through the list to look for the element.

import time

our_list = list(range(10000000))
element = 7000000

start = time.time()

for el in our_list:
    if el == element:
        break

end = time.time()

print(end - start)

This program took only 0.6 seconds. That’s a lot better.

Let’s see if we can beat this time with a more sophisticated algorithm called “binary search.” We borrow the code for the algorithm from this GitHub page.

import time

our_list = list(range(10000000))
element = 700000

start = time.time()

binary_search(our_list, element)

end = time.time()

print(end - start)

With only 0.1 seconds required to find the element, we’ve found the winning solution! 

These examples show the importance of time-tracking if you’re looking to build scalable programs. When you build a program that ends up being used by many people, every fraction of a second saved on computation time helps.

Start Your Python Journey With Udacity

In this article, we explored the time and datetime modules to understand how time works in Python. We used this knowledge to create a lap timer, a countdown timer, and showed you how to measure the execution time of Python programs. 

Want to go beyond building timers and dive into fields like app development, machine learning, and data science?

Take your first step by enrolling in Udacity’s Introduction to Programming Nanodegree.

Создайте таймер обратного отсчета в Python

В этом руководстве рассказывается, как создать таймер обратного отсчета в Python.

Код принимает ввод того, как долго должен быть обратный отсчет, и начинает обратный отсчет сразу после ввода ввода.

Использование модуля time и функции sleep() для создания таймера обратного отсчета в Python

Модуль time — это общий модуль Python, содержащий вспомогательные функции и переменные, связанные со временем. Основная функция, используемая в этом руководстве, — это функция sleep(), которая представляет собой асинхронную функцию, которая приостанавливает выполнение одного потока на n секунд.

Если ваша программа однопоточная, как в этом руководстве, то функция sleep() остановит выполнение всей программы до тех пор, пока не будет достигнуто заданное время. Благодаря этому, наряду с подтвержденным пользовательским вводом, мы можем создать простой таймер обратного отсчета в Python.

Первое, что нужно сделать, это импортировать модуль time для использования функции sleep().

Затем объявите функцию, которая будет работать как таймер обратного отсчета. Назовем эту функцию countdown(). Функция принимает единственный параметр: количество секунд (num_of_secs), до которого будет отсчитывать таймер.

Переменная num_of_secs будет непрерывно уменьшаться в цикле, пока не достигнет 0 (что переводится в False и завершает цикл без каких-либо дополнительных условий).

Внутри цикла отформатируйте входную переменную num_of_secs в формат MM:SS и распечатайте ее каждый раз, когда она уменьшается. Для этого используйте встроенную функцию Python divmod(), которая принимает два числа и возвращает произведение и остаток от двух чисел соответственно. Затем отформатируйте результат кортежа divmod() в формат MM:SS с помощью встроенной строковой функции format().

def countdown(num_of_secs):
    while num_of_secs:
        m, s = divmod(num_of_secs, 60)
        min_sec_format = '{:02d}:{:02d}'.format(m, s)

{:02d} форматирует аргумент в 2-значное целое число (из-за символа 02d). Если целое число меньше двух цифр, к нему добавляются ведущие 0.

Затем при каждой итерации цикла вызывайте time.sleep(1), что означает, что каждая итерация откладывается на 1 секунду и будет продолжаться по истечении.

Перед вызовом функции sleep() распечатайте отформатированную строку, напоминающую формат MM:SS текущего значения входной переменной num_of_secs.

Кроме того, добавьте еще один аргумент в функцию print() со свойством end и значением /r, который представляет собой новую строку для имитации поведения реального таймера. Этот аргумент перезаписывает предыдущий вывод print() каждый раз при выполнении цикла, перезаписывая все до того, как возврат каретки обозначен символом /r.

def countdown(num_of_secs):
    while num_of_secs:
        m, s = divmod(num_of_secs, 60)
        min_sec_format = '{:02d}:{:02d}'.format(m, s)
        print(min_sec_format, end='/r')
        time.sleep(1)
        num_of_secs -= 1
        
    print('Countdown finished.')
        

После этого уменьшите входную переменную min_sec_format на 1 после выполнения всех предыдущих строк.

Наконец, распечатайте заключительный оператор вне цикла, который означает, что таймер завершил выполнение. Он завершает метод countdown() и будет работать как таймер обратного отсчета.

Следующее, что нужно сделать, — предоставить пользователю возможность ввести количество секунд для запуска обратного отсчета. Для этого мы можем использовать встроенную функцию input() для приема пользовательского ввода.

Перехватите ввод в переменную и используйте его в качестве аргумента для функции обратного отсчета. Обязательно приведите входную переменную к int для проверки.

inp = input('Input number of seconds to countdown: ')
countdown(int(inp))

Весь код должен выглядеть так:

import time

def countdown(num_of_secs):
    while num_of_secs:
        m, s = divmod(num_of_secs, 60)
        min_sec_format = '{:02d}:{:02d}'.format(m, s)
        print(min_sec_format, end='/r')
        time.sleep(1)
        num_of_secs -= 1
        
    print('Countdown finished.')

inp = input('Input number of seconds to countdown: ')
countdown(inp)

Выход:

Окончательный результат будет отображать Countdown Finished, но будет имитировать работу таймера и очищать каждую строку print(), пока не достигнет 00:00.

Итак, если вы введете 5 секунд, трассировка стека будет выглядеть так:

00:05
00:04
00:03
00:02
00:01
Countdown finished.

Вот и все. Теперь вы успешно создали простой таймер обратного отсчета в Python, используя только встроенные функции и функцию sleep() из модуля time.


Download Article


Download Article

If you’re just getting started with Python, making a countdown time is a great way to exercise your programming skills. We’ll show you how to write a Python 3 program that counts down from any number, all the way down to zero.

Steps

  1. Image titled 4582307 1

    1

    Open your text editor or IDE. On Windows, the easiest option is to use IDLE, which is installed together with Python.

  2. Image titled 4582307 2

    2

    Open a new file. In many text editors, you can do this by going to the file menu and click on New Window or by just pressing Ctrl+N.

    Advertisement

  3. Image titled 4582307 3

    3

    Import the time module. The time contains many Python functions related to time, for example getting the current time or waiting a specified amount of time (the latter is what you will need for this program). To import the module, type:

  4. Image titled 4582307 4

    4

    Define a countdown function. You can give the function any name you want, but usually you should use something descriptive. In this case, you could name it countdown(). Add the following code:

  5. Image titled 4582307 5

    5

    Write a while-loop. A while-loop repeats the code inside it as long as its condition is true. In this case, you want the countdown to continue until the number reaches 0. So, you need to write:

    • Notice the spaces at the beginning of the line. These tell Python that this line of code is part of the definition of the countdown function, and not just some code below it. You can use any number of spaces, but you need to use the same amount before any line that you want to indent once.
    • You will need to indent the next code lines twice, because they are both part of the function definition and part of the while-loop. This is done by using twice as many spaces.
  6. Image titled 4582307 6

    6

    Print the current number. This does not mean using a printer to get it on paper, «printing» is a word that means «displaying on the screen». This will let you see how far the countdown has progressed.

  7. Image titled 4582307 7

    7

    Count down the number. Make it 1 less. This is done with the following code:

    Alternatively, if you don’t want to type so much, you can instead write:

  8. Image titled 4582307 8

    8

    Make the program wait a second. Otherwise, it would be counting down the numbers way too fast and the countdown would be finished before you could even read it. For waiting a second, use the sleep function of the time module that you had previously imported:

  9. Image titled 4582307 9

    9

    Do something when the countdown reaches zero. To print out «BLAST OFF!» when the countdown reaches zero, add this line:

    • Note that this line is only indented once. This is because it is no longer part of the while-loop. This code is only run after the while-loop finishes.
  10. Image titled 4582307 10

    10

    Ask the user from which number to start the countdown. This will give your program some flexibility, instead of always counting from the same number.

    • Print the question to the user. They need to know what they are supposed to enter.
      print("How many seconds to count down? Enter an integer:")
      
    • Get the answer. Store the answer in a variable so that you can do something with it later.
    • While the user’s answer is not an integer, ask the user for another integer. You can do this with a while-loop. If the first answer is already an integer, the program will not enter the loop and just proceed with the next code.
      while not seconds.isdigit():
          print("That wasn't an integer! Enter an integer:")
          seconds = input()
      
    • Now you can be sure that the user entered an integer. However, it is still stored inside a string (input() always returns a string, because it can’t know whether the user will enter text or numbers). You need to convert it to an integer:

      If you would have tried to convert a string whose content isn’t an integer into an integer, you would get an error. This is the reason while the program checked whether the answer was actually an integer first.

  11. Image titled 4582307 11

    11

    Call the countdown() function. You had previously defined it, but defining a function doesn’t do what is written inside it. To actually run the countdown code, call the countdown() function with the number of seconds that the user inputted:

  12. Image titled 4582307 12

    12

    Check your finished code. It should look like this:

    import time
    def countdown(t):
        while t > 0:
            print(t)
            t -= 1
            time.sleep(1)
        print("BLAST OFF!")
    
    print("How many seconds to count down? Enter an integer:")
    seconds = input()
    while not seconds.isdigit():
        print("That wasn't an integer! Enter an integer:")
        seconds = input()
    seconds = int(seconds)
    countdown(seconds)
    
    • The empty lines are only there to make the code easier to read. They are not required, and Python actually ignores them.
    • You can write t = t - 1 instead of t -= 1 if you prefer.
  13. Advertisement

Add New Question

  • Question

    How do I get it to print at each second rather than having it all print at once?

    Community Answer

    Use the time.sleep(x) function. It allows for the program to pause for x seconds. After every print statement, insert time.sleep(1).

  • Question

    How do I make the font larger in Python on a Mac?

    Community Answer

    In the Python shell, click Options, Configure, Idle. From there, you can change the font size.

  • Question

    Why have the ‘time’ module if it is never used?

    Community Answer

    If you write a program for, say, a robot and have the servo controls in milliseconds, then it will use the time module to send the electrical signal for the right amount of time.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Thanks to all authors for creating a page that has been read 185,542 times.

Is this article up to date?


Download Article


Download Article

If you’re just getting started with Python, making a countdown time is a great way to exercise your programming skills. We’ll show you how to write a Python 3 program that counts down from any number, all the way down to zero.

Steps

  1. Image titled 4582307 1

    1

    Open your text editor or IDE. On Windows, the easiest option is to use IDLE, which is installed together with Python.

  2. Image titled 4582307 2

    2

    Open a new file. In many text editors, you can do this by going to the file menu and click on New Window or by just pressing Ctrl+N.

    Advertisement

  3. Image titled 4582307 3

    3

    Import the time module. The time contains many Python functions related to time, for example getting the current time or waiting a specified amount of time (the latter is what you will need for this program). To import the module, type:

  4. Image titled 4582307 4

    4

    Define a countdown function. You can give the function any name you want, but usually you should use something descriptive. In this case, you could name it countdown(). Add the following code:

  5. Image titled 4582307 5

    5

    Write a while-loop. A while-loop repeats the code inside it as long as its condition is true. In this case, you want the countdown to continue until the number reaches 0. So, you need to write:

    • Notice the spaces at the beginning of the line. These tell Python that this line of code is part of the definition of the countdown function, and not just some code below it. You can use any number of spaces, but you need to use the same amount before any line that you want to indent once.
    • You will need to indent the next code lines twice, because they are both part of the function definition and part of the while-loop. This is done by using twice as many spaces.
  6. Image titled 4582307 6

    6

    Print the current number. This does not mean using a printer to get it on paper, «printing» is a word that means «displaying on the screen». This will let you see how far the countdown has progressed.

  7. Image titled 4582307 7

    7

    Count down the number. Make it 1 less. This is done with the following code:

    Alternatively, if you don’t want to type so much, you can instead write:

  8. Image titled 4582307 8

    8

    Make the program wait a second. Otherwise, it would be counting down the numbers way too fast and the countdown would be finished before you could even read it. For waiting a second, use the sleep function of the time module that you had previously imported:

  9. Image titled 4582307 9

    9

    Do something when the countdown reaches zero. To print out «BLAST OFF!» when the countdown reaches zero, add this line:

    • Note that this line is only indented once. This is because it is no longer part of the while-loop. This code is only run after the while-loop finishes.
  10. Image titled 4582307 10

    10

    Ask the user from which number to start the countdown. This will give your program some flexibility, instead of always counting from the same number.

    • Print the question to the user. They need to know what they are supposed to enter.
      print("How many seconds to count down? Enter an integer:")
      
    • Get the answer. Store the answer in a variable so that you can do something with it later.
    • While the user’s answer is not an integer, ask the user for another integer. You can do this with a while-loop. If the first answer is already an integer, the program will not enter the loop and just proceed with the next code.
      while not seconds.isdigit():
          print("That wasn't an integer! Enter an integer:")
          seconds = input()
      
    • Now you can be sure that the user entered an integer. However, it is still stored inside a string (input() always returns a string, because it can’t know whether the user will enter text or numbers). You need to convert it to an integer:

      If you would have tried to convert a string whose content isn’t an integer into an integer, you would get an error. This is the reason while the program checked whether the answer was actually an integer first.

  11. Image titled 4582307 11

    11

    Call the countdown() function. You had previously defined it, but defining a function doesn’t do what is written inside it. To actually run the countdown code, call the countdown() function with the number of seconds that the user inputted:

  12. Image titled 4582307 12

    12

    Check your finished code. It should look like this:

    import time
    def countdown(t):
        while t > 0:
            print(t)
            t -= 1
            time.sleep(1)
        print("BLAST OFF!")
    
    print("How many seconds to count down? Enter an integer:")
    seconds = input()
    while not seconds.isdigit():
        print("That wasn't an integer! Enter an integer:")
        seconds = input()
    seconds = int(seconds)
    countdown(seconds)
    
    • The empty lines are only there to make the code easier to read. They are not required, and Python actually ignores them.
    • You can write t = t - 1 instead of t -= 1 if you prefer.
  13. Advertisement

Add New Question

  • Question

    How do I get it to print at each second rather than having it all print at once?

    Community Answer

    Use the time.sleep(x) function. It allows for the program to pause for x seconds. After every print statement, insert time.sleep(1).

  • Question

    How do I make the font larger in Python on a Mac?

    Community Answer

    In the Python shell, click Options, Configure, Idle. From there, you can change the font size.

  • Question

    Why have the ‘time’ module if it is never used?

    Community Answer

    If you write a program for, say, a robot and have the servo controls in milliseconds, then it will use the time module to send the electrical signal for the right amount of time.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Thanks to all authors for creating a page that has been read 185,542 times.

Is this article up to date?

Ok, I’ll start with why your timer is lagging.

What happens in your program is that the time.sleep() call «sleeps» the program’s operation for 1 second, once that second has elapsed your program begins execution again. But your program still needs time to execute all the other commands you’ve told it to do, so it takes 1s + Xs to actually perform all the operations. Although this is a very basic explanation, it’s fundamentally why your timer isn’t synchronous.

As for why you’re constantly printing on a new line, the print() function has a pre-defined end of line character that it appends to any string it is given.

print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False)

You can overwrite this with anything by putting end="YourThing" in your print statement like so

for x in range(3):
    print("Test", end="")

The above example appends an empty string to the end of the line, so the output of the loop would be

"TestTestTest"

As for solving your timer problem, you should use something similar to

timePoint = time.time()

while True:

    #Convert time in seconds to a gmtime struct
    currentTime = time.gmtime(time.time() - timePoint))

    #Convert the gmtime struct to a string
    timeStr = time.strftime("%M minutes, %S seconds", currentTime)

    #Print the time string
    print(timeStr, end="")

Понравилась статья? Поделить с друзьями:
  • Как написать таджикские буквы
  • Как написать табы для калимбы
  • Как написать табы для губной гармошки
  • Как написать табы для гитары
  • Как написать табулатуру для гитары