Timer for Python game - python

I'm trying to create a simple game where the point is to collect as many blocks as you can in a certain amount of time, say 10 seconds. How can I get a timer to begin ticking at the start of the program and when it reaches 10 seconds, do something (in this case, exit a loop)?

import time
now = time.time()
future = now + 10
while time.time() < future:
# do stuff
pass
Alternatively, if you've already got your loop:
while True:
if time.time() > future:
break
# do other stuff
This method works well with pygame, since it pretty much requires you to have a big main loop.

Using time.time()/datetime.datetime.now() will break if the system time is changed (the user changes the time, it is corrected by a timesyncing services such as NTP or switching from/to dayligt saving time!).
time.monotonic() or time.perf_counter() seems to be the correct way to go, however they are only available from python 3.3. Another possibility is using threading.Timer. Whether or not this is more reliable than time.time() and friends depends on the internal implementation. Also note that creating a new thread is not completely free in terms of system resources, so this might be a bad choice in cases where a lot of timers has to be run in parallel.

I use this function in my python programs. The input for the function is as example:
value = time.time()
def stopWatch(value):
'''From seconds to Days;Hours:Minutes;Seconds'''
valueD = (((value/365)/24)/60)
Days = int (valueD)
valueH = (valueD-Days)*365
Hours = int(valueH)
valueM = (valueH - Hours)*24
Minutes = int(valueM)
valueS = (valueM - Minutes)*60
Seconds = int(valueS)
print Days,";",Hours,":",Minutes,";",Seconds
start = time.time() # What in other posts is described is
***your code HERE***
end = time.time()
stopWatch(end-start) #Use then my code

The threading.Timer object (documentation) can count the ten seconds, then get it to set an Event flag indicating that the loop should exit.
The documentation indicates that the timing might not be exact - you'd have to test whether it's accurate enough for your game.

In this example the loop is run every second for ten seconds:
import datetime, time
then = datetime.datetime.now() + datetime.timedelta(seconds=10)
while then > datetime.datetime.now():
print 'sleeping'
time.sleep(1)

For a StopWatch helper class, here is my solution which gives you precision on output and also access to the raw start time:
class StopWatch:
def __init__(self):
self.start()
def start(self):
self._startTime = time.time()
def getStartTime(self):
return self._startTime
def elapsed(self, prec=3):
prec = 3 if prec is None or not isinstance(prec, (int, long)) else prec
diff= time.time() - self._startTime
return round(diff, prec)
def round(n, p=0):
m = 10 ** p
return math.floor(n * m + 0.5) / m

Asks you when to stop [seconds]
Adds '0' at starting [1-9]
import time
import sys
stop = int(input('> '))
second = 0
print('> Stopwatch Started.')
while stop > second:
if second < 9:
second = second + 1
time.sleep(1)
sys.stdout.write('\r> ' + '0' + str(second))
else:
second += 1
time.sleep(1)
sys.stdout.write('\r' + '> ' + str(second))
print('\n> Stopwatch Stopped.')

As a learning exercise for myself, I created a class to be able to create several stopwatch timer instances that you might find useful (I'm sure there are better/simpler versions around in the time modules or similar)
import time as tm
class Watch:
count = 0
description = "Stopwatch class object (default description)"
author = "Author not yet set"
name = "not defined"
instances = []
def __init__(self,name="not defined"):
self.name = name
self.elapsed = 0.
self.mode = 'init'
self.starttime = 0.
self.created = tm.strftime("%Y-%m-%d %H:%M:%S", tm.gmtime())
Watch.count += 1
def __call__(self):
if self.mode == 'running':
return tm.time() - self.starttime
elif self.mode == 'stopped':
return self.elapsed
else:
return 0.
def display(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
print "Name: ", self.name
print "Address: ", self
print "Created: ", self.created
print "Start-time: ", self.starttime
print "Mode: ", self.mode
print "Elapsed: ", self.elapsed
print "Description:", self.description
print "Author: ", self.author
def start(self):
if self.mode == 'running':
self.starttime = tm.time()
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.starttime = tm.time()
self.mode = 'running'
self.elapsed = 0.
elif self.mode == 'stopped':
self.mode = 'running'
#self.elapsed = self.elapsed + tm.time() - self.starttime
self.starttime = tm.time() - self.elapsed
else:
pass
return
def stop(self):
if self.mode == 'running':
self.mode = 'stopped'
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.mode = 'stopped'
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def lap(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def reset(self):
self.starttime=0.
self.elapsed=0.
self.mode='init'
return self.elapsed
def WatchList():
return [i for i,j in zip(globals().keys(),globals().values()) if '__main__.Watch instance' in str(j)]

This is the Shortest Way I know of doing it:
def stopWatch():
import time
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1

New to the python world!
I need a System Time independent Stopwatch so I did translate my old C++ class into Python:
from ctypes.wintypes import DWORD
import win32api
import datetime
class Stopwatch:
def __init__(self):
self.Restart()
def Restart(self):
self.__ulStartTicks = DWORD(win32api.GetTickCount()).value
def ElapsedMilliSecs(self):
return DWORD(DWORD(win32api.GetTickCount()).value-DWORD(self.__ulStartTicks).value).value
def ElapsedTime(self):
return datetime.timedelta(milliseconds=self.ElapsedMilliSecs())
This has no 49 days run over issue due to DWORD math but NOTICE that GetTickCount has about 15 milliseconds granularity so do not use this class if your need 1-100 milliseconds elapsed time ranges.
Any improvement or feedback is welcome!

Related

how to record between key input delay?

When I run the code below, I have noticed that what key is entered is recorded.
But there is one more thing I want.
That's for example, assuming I typed a and b, I want the time between a and b to be recorded between the keys as well.
import pynput, time
from pynput.keyboard import Key, Listener
count = 0
keys = []
def on_press(key):
global keys, count
keys.append(key)
count += 1
print("{0} pressed".format(key))
if count >= 10:
count = 0
write_file(keys)
keys = []
def write_file(keys):
with open("log.txt", "w") as f:
for key in keys:
k = str(key).replace("'", "")
if k.find("space") > 0:
f.write('\n')
elif k.find("Key") == -1:
f.write(k)
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
I sloved question.
Thanks for everyone.
# From: https://github.com/moses-palmer/pynput
from pynput.keyboard import Key, Listener
import logging
import keyboard, sys, os
import time
on_press_previous = 0
log_dir = ""
os.remove(log_dir + 'key_log.txt')
logging.basicConfig(filename=(log_dir + "key_log.txt"), level=logging.DEBUG, format='%(message)s')
def on_press(key):
global on_press_previous
on_press_current = time.time()
delta = round(on_press_current - on_press_previous, 3)
on_press_previous = on_press_current
logging.info('{0}'.format(key))
logging.info('{0}'.format(delta))
if keyboard.is_pressed("F7"):
sys.exit()
with Listener(on_press=on_press) as listener:
listener.join()
Here is a Timer class I use to count / record time when writing programs:
class Timer:
def __init__(self):
self.start_time = None
self.on = False
def start(self):
# start counting
self.start_time = time.time()
self.on = True
def value(self):
# --- return current value ---
if self.on:
return time.time() - self.start_time
return 0
def tostr(self):
# --- return value as {min:sec} format ---
val = math.floor(self.value())
mins = '0' + str(int(val / 60)) if len(str(int(val / 60))) == 1 else str(int(val / 60))
secs = '0' + str(val % 60) if len(str(val % 60)) == 1 else str(val % 60)
return "{}:{}".format(mins, secs)
def stop(self):
# --- stop counting ---
self.__init__()
Use timeit module (import timeit):
Put this two lines in on_press:
print("The time difference is :", timeit.default_timer() - start)
start = timeit.default_timer()
Now it will print out time difference between two button clicks:
count = 0
keys = []
start = timeit.default_timer()
def on_press(key):
global keys, count, start
...
...
Also you will have to declare new global variable start.
You can track the time for the on_press event, store it, and then calculated the difference. Here I am using a global variable just for simplicity and consistency with your existing code. Library function time.time_ns() should give plenty of resolution.
import pynput, time
from pynput.keyboard import Key, Listener
count = 0
keys = []
on_press_previous = 0
def on_press(key):
global keys, count, on_press_previous
# current timestamp in nanoseconds
on_press_current = time.time_ns()
# calculate delta from previous on_press event
delta = on_press_current - on_press_previous
# store the current timestamp for the next round
on_press_previous = on_press_current
keys.append((key,delta))
count += 1
print("{} pressed {} nanoseconds from previous".format(key, delta))
if count >= 10:
count = 0
write_file(keys)
keys = []
def write_file(keys):
with open("log.txt", "w") as f:
for key,delta in keys:
k = str(key).replace("'", "")
if k.find("space") > 0:
f.write('\n')
elif k.find("Key") == -1:
f.write(k)
f.write(str(delta))
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()

"How to print list data on a specific time delay list ?"

I want to print list data on the specific delays which are on another list. I Want to loop this process for a specific time, but I'm unable to implement it in a thread.
from time import sleep
import datetime
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
class sampleTest:
#staticmethod
def test():
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
# print(f"{data} delay {delay} & time is {t} ")
# sleep(delay)
i = 0
while i < len(list1):
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t} ")
sleep(list2[i])
i += 1
else:
print("All Data is printed")
if __name__ == '__main__':
obj = sampleTest
while Str_time < End_Time:
obj.test()
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
print("Time Is done")
Expected output: On first, loop it should print all list data but in the second loop, it should run as per the delay.
1st time: Hello, Hi, Ola
after that
1. Every 5 seconds it should print Hello
2. Every 10 seconds it should print Hi
3. Every 7seconds it should print Ola
Actual Output: List of data is getting printed as per the delay.
Hello delay 5 & time is 11:41:45
Hi delay 10 & time is 11:41:50
Ola delay 3 & time is 11:42:00
All Data is printed
Hello delay 5 & time is 11:42:03
Hi delay 10 & time is 11:42:08
Ola delay 3 & time is 11:42:18
You can try comparing the current time with the start time, for example:
time.sleep(1);
diff = int(time.time() - start_time)
if (diff % wait_time == 0):
print(text_to_print)
Here is the full code implementing this:
from time import sleep
import time
import datetime
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
starttime=time.time()
diff = 0
class sampleTest:
#staticmethod
def test():
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
for i in range(len(list1)):
if (diff % list2[i] == 0):
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t} ")
if __name__ == '__main__':
obj = sampleTest
while Str_time < End_Time:
obj.test()
time.sleep(1);
diff = int(time.time() - starttime)
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
print("Time Is done")
In accordance with your desired output, I believe threads are the best option, which means:
from time import sleep
import datetime
import threading
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
class sampleTest:
def __init__(self):
self.run = True
print ("1st time: Hello, Hi, Ola")
print ("Now: " + datetime.datetime.now().strftime('%H:%M:%S'))
def test(self, i):
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
while self.run:
sleep(list2[i])
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t}")
def stop(self):
self.run = False
if __name__ == '__main__':
obj = sampleTest()
t1 = threading.Thread(target=obj.test,args=(0,))
t2 = threading.Thread(target=obj.test,args=(1,))
t3 = threading.Thread(target=obj.test,args=(2,))
t1.start()
t2.start()
t3.start()
while Str_time < End_Time:
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
obj.stop()
t1.join()
t2.join()
t3.join()
print("All data is printed")
print("Time Is done")

How can I get loops to run sequentially without locking GUI?

I'm writing a photobooth program in Python on my Raspberry Pi 2 and it worked if I just want to take one picture or use auto focus once. I'm trying to write a function "scheduler" that waits 4 seconds then runs auto-focus, then waits 4 seconds to take picture 1, waits another 4 seconds for picture 2 and waits 4 seconds for picture 3 while updating a status bar in PyGTK. But when the "scheduler" function is called it goes through and starts all the while loops at the same time.
I tried putting the while loops in separate functions and running them as threads and using threadx.start(), threadx.join() commands under each thread call. I suspect the way gobject.timeout_add() function is preventing blocking, which I need to keep the GUI updated and the live preview running, but I also can't figure out how to get blocking when I need it. I also started scheduler as a thread and used time.sleep(1) in each of the while loops and it acts behaves how I want it to except the GUI disappears after the first image gets processed and I can't find any error message to explain it.
I've been working on this for weeks and would happily pay someone to help me get this finished via email. I live in a rural area and have had a very hard time finding someone locally to help. I can paypal... please contact me at derosia at the popular google email service. If you have a camera supported by gphoto2 and a usb tether that would be a bonus.
class Photobooth(gtk.Window):
def set_statusBar(self, status):
self.statusBar.label.set_text(str(status))
def focus_counter2(self, counter):
if counter > 3:
self.set_statusBar("Get into position!")
elif counter > 0:
self.set_statusBar("Focusing: " + str(counter-1))
else:
self.set_statusBar("Focusing: " + str(counter-1))
self.focus_function() #runs the function for auto focus
def countdown_function(self, counter, image_name):
if counter > 1:
self.set_statusBar(str(counter-1))
elif counter > 0:
self.set_statusBar("Keep Smiling!")
else:
self.photo_cb(image_name) #runs the function to take an image
def scheduler(self, widget, data = None):
global ftp_path
global image_names
global countdown_timer
image_names = []
counter = countdown_timer
while counter > 0:
gobject.timeout_add(counter * 1000, self.focus_counter2, countdown_timer-counter)
counter -= 1
counter = countdown_timer
while counter >= 0:
image_name = datetime.datetime.now().strftime("%Y_%m-%d_%H-%M-%S")
gobject.timeout_add(counter * 1000, self.countdown_function, countdown_timer-counter, image_name)
counter -= 1
image_names.append(image_name + ".jpg")
counter = countdown_timer
while counter >= 0:
image_name = datetime.datetime.now().strftime("%Y_%m-%d_%H-%M-%S")
gobject.timeout_add(counter * 1000, self.countdown_function, countdown_timer-counter, image_name)
counter -= 1
image_names.append(image_name + ".jpg")
counter = countdown_timer
while counter >= 0:
image_name = datetime.datetime.now().strftime("%Y_%m-%d_%H-%M-%S")
gobject.timeout_add(counter * 1000, self.countdown_function, countdown_timer-counter, image_name)
counter -= 1
image_names.append(image_name + ".jpg")
def __init__(self):
super(PictureBox, self).__init__()
startB_image = gtk.image_new_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_SMALL_TOOLBAR)
startB = gtk.Button()
startB.set_image(startB_image)
startB.set_tooltip_text("Start countdown")
startB.connect('clicked', self.scheduler, None)
Thanks to andlabs I solved this the way he suggested:
Call a function and have each function call the next one when they finished what they were doing. Then to make sure it looped through the proper number of times I just passed along a counter to each function that got iterated at the end of each loop, image_number. It seems to work.
class Photobooth(gtk.Window):
def set_statusBar(self, status):
self.statusBar.label.set_text(str(status))
def focus_counter1(self, widget, data=None):
global countdown_timer
counter = countdown_timer
while counter > 0:
gobject.timeout_add(counter * 1000, self.focus_counter2,
countdown_timer-counter)
counter -= 1
def focus_counter2(self, counter):
if counter > 3:
self.set_statusBar("Get into position!")
elif counter > 0:
self.set_statusBar("Focusing: " + str(counter))
else:
self.set_statusBar("Focusing: " + str(counter))
self.focus_function()
gobject.timeout_add(1000, self.countdown_clicked, 1)
def countdown_clicked(self, image_number):
global countdown_timer
counter = countdown_timer
while counter >= 0:
gobject.timeout_add(counter * 1000, self.countdown_function,
countdown_timer-counter, image_number)
counter -= 1
def countdown_function(self, counter, image_number):
global images_per_sequence
if counter > 1:
self.set_statusBar(str(counter-1))
elif counter > 0:
self.set_statusBar("Keep Smiling!")
else:
image_name = datetime.datetime.now()
self.photo_cb(image_name.strftime("%Y_%m-%d_%H-%M-%S"))
if image_number < images_per_sequence:
gobject.timeout_add(1000, self.countdown_clicked,
image_number + 1)
def __init__(self):
super(PictureBox, self).__init__()
startB_image = gtk.image_new_from_stock(gtk.STOCK_YES,
gtk.ICON_SIZE_SMALL_TOOLBAR)
startB = gtk.Button()
startB.set_image(startB_image)
startB.set_tooltip_text("Start countdown")
startB.connect('clicked', self.focus_counter1, None)

Python 3.4 won't use information from .json file

I am currently working on a small Python clock. The clock doesn't have anything to do with real time, it was just for a fun side project. After every second, the clock is supposed to save the hour, minute, second, time of day, and other information. It saves the information, but when I restart the program, it doesn't reuse the information. Here is my code:
#Importations
import jsonpickle
import os
import sys
import time
#Setups
SAVEGAME_FILENAME = 'time.json'
game_state = dict()
#Class
class clocktime(object):
def __init__(self, hour, minute, second, timeday, day):
self.hour = hour
self.minute = minute
self.second = second
self.timeday = timeday
self.day = day
#Load Program Save
def load_game():
"""This runs if a .json file IS found"""
with open(SAVEGAME_FILENAME, 'r') as savegame:
state = jsonpickle.decode(savegame.read())
return state
#Save Program to JSON
def save_game():
"""This saves the program to a .json file."""
global game_state
with open(SAVEGAME_FILENAME, 'w') as savegame:
savegame.write(jsonpickle.encode(game_state))
#Initialize Program
def initialize_game():
"""Runs if no AISave is found"""
hour = 1
minute = 0
second = 0
timeday = 1
day = ('am')
the_time = clocktime(hour, minute, second, timeday, day)
state = dict()
state['the_time'] = [the_time]
return state
#Clear Screen
def cls():
os.system('cls')
#Clock Program
def clock():
hour = 1
minute = 0
second = 0
timeday = 1
day = ('am')
global game_state
while True:
print ("The time is: %s" % hour + ":%s" % minute + ":%s" % second + " %s" % day)
print (" H M S")
print ("H = Hour, M = Minute, S = Second")
time.sleep(0.5)
cls()
second += 1
save_game()
if second == 60:
minute += 1
second = 0
if minute == 60:
hour += 1
minute = 0
if hour == 13:
hour = 1
timeday += 1
if timeday == 1:
day = ('am')
if timeday == 2:
day = ('pm')
if timeday == 3:
day = 0
game_state['the_time'][0].hour = hour
game_state['the_time'][0].minute = minute
game_state['the_time'][0].second = second
game_state['the_time'][0].timeday = timeday
#Main Program
def main():
"""Main function. Check if a savegame exists, and if so, load it. Otherwise
initialize the game state with defaults. Finally, start the game."""
global game_state
if not os.path.isfile(SAVEGAME_FILENAME):
game_state = initialize_game()
else:
game_state = load_game()
clock()
#Launch Code
if __name__ == "__main__":
isSaveOn = False
main()
You're overwriting game_state with initial hour/minute/second/timeday values ) at the end of the loop when you save them, and they are always 1/0/0/1 regardless of the game_state. So basically you load game_state and then overwrite it with default values. Replace initializations in clock function to something like this:
# ...
def clock():
# Change to this:
hour = game_state['the_time'][0].hour
minute = game_state['the_time'][0].minute
second = game_state['the_time'][0].second
timeday = game_state['the_time'][0].timeday
while True:
# (displaying time and incrementing values)
game_state['the_time'][0].hour = hour
game_state['the_time'][0].minute = minute
game_state['the_time'][0].second = second
game_state['the_time'][0].timeday = timeday
# Move save_game here (to the end of loop):
save_game()

How to delete from an object

import pickle
class TasksError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Task(object):
def __init__(self, task = () ):
if task ==():
raise TasksError('Empty task.')
self.name = task[0]
self.date = task[1]
self.priority = task[2]
self.time = task[3]
self.type = task[4]
self.comment = task[5]
def __str__(self):
output = '''Name: %s
Date: %s
Priority: %s
Time: %s
Type: %s
Comment: %s
''' % ( self.name,
self.date,
self.priority,
self.time,
self.type,
self.comment)
return output
class Tasks(object):
def __init__(self, container = []):
self.container = [ Task(todo) for todo in container ]
def delete(self):
x = 0
for todo in self.container:
x = x + 1
print "Task Number",x,"\n", todo
delete = raw_input("what number task would you like to delete")
if delete == "y":
del todo
############
#x = 0
# for task in self.container:
# x = x+1
#print "Task Number",x,"\n", task
#delete = raw_input("what number task would you like to delete")
#if delete == "y":
#del(task)
def add(self, task):
if task == '':
raise TasksError('Empty task')
self.container.append( Task(task) )
def __str__(self):
output = '\n'.join( [ str(todo) for todo in self.container ] )
return output
if __name__== "__main__":
divider = '-' * 30 + '\n'
tasks = Tasks( container = [] ) # creates a new, empty task list
while True:
print divider, '''Make your selection:
1. Add new task
2. Print all tasks
3. Save tasks
4. Load tasks from disk
5. Find high priority tasks
6. Sort by date
7. Delete task
<ENTER> to quit
'''
try:
menu_choice = int(input("Select a number from the menu: "))
except:
print 'Goodbye!'
break
if menu_choice == 1:
task = raw_input (">>> Task: ")
date = raw_input (">>> Date as string YYYYMMDD: ")
priority = raw_input (">>> Priority: ")
time = raw_input (">>> Time: ")
Type = raw_input (">>> Type Of Task: ")
comment = raw_input (">>> Any Comments? ")
todo = (task, date, priority, time, Type, comment)
tasks.add( todo )
print tasks
elif menu_choice == 2:
print divider, 'Printing all tasks'
print tasks
elif menu_choice == 3:
print divider, 'Saving all tasks'
tasks.save()
elif menu_choice == 4:
print divider, 'Loading tasks from disk'
tasks.load()
elif menu_choice == 5:
print divider, 'Finding tasks by priority'
results = tasks.find_by_priority(priority='high')
for result in results: print result
elif menu_choice == 6:
print divider, 'Sorting by date'
tasks.sort_by_date()
print tasks
elif menu_choice == 7:
tasks.delete()
I have deleted parts of my code (hopefully nothing important).
Im having trouble getting python to delete my tasks once added.
Both methods defined as "def delete" give the error message type error: task/todo object does not support deletion.
Does anyone know a way around this?
You don't delete from list like that... Your code have 2 problems:
if you use for to loop through a iterable, you should not change it inside the loop.
to del from list you should use index.
Try this:
index = 0
while index < len(self.container):
delete = raw_input("what number task would you like to delete")
if delete == "y":
del self.container[index]
else:
index += 1

Categories