Ene Uran 638 Posting Virtuoso

Line 9
if isinstance(key, types.SliceType):
can be changed to
if isinstance(key, slice):
to work with Python27 and Python33

Gribouillis commented: thanks, changed this in the code. +13
Ene Uran 638 Posting Virtuoso

Americans on average send out 28 Christmas cards to friends and family each year.

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

How about knitting yourself a sweater?

Ene Uran 638 Posting Virtuoso

Oh my goodness, you are mixing a recursive fibonacci number function with an attempt to make a sliced list. A recipe for disaster.

Ene Uran 638 Posting Virtuoso

A list can have a number of the same elements, whereas a set has only unique elements.

mylist = ['b', 'a', 'n', 'a', 'n', 'a', 'b', 'o', 'a', 't']
print(mylist)

# elements will be unique and in hash order
myset = set(mylist)
print(myset)

print(list(myset))

''' result -->
['b', 'a', 'n', 'a', 'n', 'a', 'b', 'o', 'a', 't']
set(['a', 'b', 't', 'o', 'n'])
['a', 'b', 't', 'o', 'n']
'''
Ene Uran 638 Posting Virtuoso
# Define a procedure, biggest, that takes three
# numbers as inputs and returns the largest of
# those three numbers.

def biggest(first, second, third):
    if first > second and first > third:
        return first
    if second > first and second > third:
        return second
    else:
        return third


# result is 9 in each case
print biggest(3, 6, 9)
print biggest(6, 9, 3)
print biggest(9, 3, 6)
print biggest(3, 3, 9)
print biggest(9, 3, 9)

You could do:

def biggest(first, second, third):
    return max(first, second, third)
Ene Uran 638 Posting Virtuoso

Try this:

# wx.Slider(parent, id, value, minValue, maxValue, pos, size, style)

import wx

class freem(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self, parent, id, size=(300,100))
        panel = wx.Panel(self)

        slider = wx.Slider(panel, -1, 50, 1, 100, pos=(10,10), size=(250,-1),
                           style=wx.SL_AUTOTICKS | wx.SL_LABELS)
        slider.SetTickFreq(5)

if __name__=='__main__':
    app = wx.App()
    frame = freem(parent=None, id=-1)
    frame.Show()
    app.MainLoop()
Ene Uran 638 Posting Virtuoso

You can use the canvas image as a background to your turtle drawings:

''' turtle_Tk_Canvas_Image_url.py
display a GIF image obtained from an internet web page
on a Tkinter canvas, then use the canvas for some turtle drawing
modified Vegaseat code
'''

import io
import base64
import turtle
try:
    # Python2
    import Tkinter as tk
    from urllib2 import urlopen
except ImportError:
    # Python3
    import tkinter as tk
    from urllib.request import urlopen


root = tk.Tk()
root.title("turtle graphics a website image")

# this GIF picture previously downloaded to tinypic.com
image_url = "http://i46.tinypic.com/r9oh0j.gif"

image_byt = urlopen(image_url).read()
image_b64 = base64.encodestring(image_byt)
photo = tk.PhotoImage(data=image_b64)

# create a white canvas large enough to fit the image+
w = 540
h = 340
cv = tk.Canvas(bg='white', width=w, height=h)
cv.pack()

# this makes the canvas a turtle canvas
# point(0, 0) is in the center now
tu = turtle.RawTurtle(cv)

# put the image on the turtle canvas with
# create_image(xpos, ypos, image, anchor)
xpos = int(w/2 * 0.9)
ypos = int(h/2 * 0.9)
print(xpos, ypos)
cv.create_image(-xpos, -ypos, image=photo, anchor='nw')

# now do some turtle graphics
tu.pensize(2)
for radius in range(50, 200, 40):
    # pen up
    tu.up()
    # move pen to point x, y
    # keeps the center of the circle at canvas center
    tu.goto(0, -radius)
    # pen down
    tu.down()
    tu.circle(radius)

root.mainloop()
Ene Uran 638 Posting Virtuoso

Assume the sentences end with '.' or '?' or '!' so count these characters and divide the total words by the number of these characters.

Gribouillis commented: interesting idea +13
Ene Uran 638 Posting Virtuoso

Another option you can use:

''' wx_FancyText2.py
wxPython's wx.lib.fancytext can apply XML code to color text
'''

import  wx
import  wx.lib.fancytext as fancytext

class FancyText(wx.Panel):
    def __init__(self, parent, text_black, text_red):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        self.xml_str = '%s<font color="red">%s</font>' % (text_black, text_red)

    def OnPaint(self, evt):
        """generate the fancytext on a paint dc canvas"""
        dc = wx.PaintDC(self)
        fancytext.RenderToDC(self.xml_str, dc, 0, 5)


text_black = '''\
just some normal text
to display ahead of the
special red text
'''

text_red = 'now the red text'

app = wx.App(0)
frame = wx.Frame(None, wx.ID_ANY, title='wxPython fancy text',
    pos=(100, 50), size=(500, 250))
FancyText(frame, text_black, text_red)
frame.Show(True)
app.MainLoop()
Ene Uran 638 Posting Virtuoso

You need to update the canvas as shown. Otherwise the Tkinter event loop just waits till time.sleep(5) is done.

import ImageTk
import tkMessageBox
from Tkinter import*
from turtle import *
import time

root = Tk() #main window

canvas = Canvas(root, width=800, height=480, bg="white")
canvas.grid(column=1, rowspan=6, row=0, columnspan=5)

start=ImageTk.PhotoImage(file="start.gif")
after_prymase2a=ImageTk.PhotoImage(file="after_prymase2a.gif")

canvas.create_image(200,400,image=start)
canvas.update()  # needed to do one pic at a time

time.sleep(5)

canvas.create_image(100,100,image=after_prymase2a)

root.mainloop()
Ene Uran 638 Posting Virtuoso

Just a few more rumblings:

''' class_private1.py
class variable or method names with a two underline prefix
will be private too the class
'''

class A(object):
    # actually creates self.k which is public
    k = 1234
    # variable names like
    # __m or __m_ will be private to the class
    # same goes for names of class methods
    __m = 5678
    # _n or _n_ or _n__ or __n__ will be public
    __n__ = 999
    # __init__() will be used first, if it's there
    def __init__(self, v):
        self.value = v

    def add(self, x):
        return self.value + x

    def __subtract(self, y):
        """function only internal/private to class"""
        return self.value - y

    def deduct(self, y):
        return self.__subtract(y)

class B(A):
    '''inherit class A, but not private methods or variables'''
    def __init__(self, *arg):
        #super(B, self).__init__(*arg)
        A.__init__(self, *arg)


a = A(7)    # implies A.__init__(a, 7)
print(A)    # <class '__main__.A'>
print(a)    # <__main__.A object at 0x02854A70>

print(a.add(2))     # 9
print(a.deduct(4))  # 3
print(a.value)      # 7
print(a.k)          # 1234

print(a.__n__)      # 999

# note that __m is private to the class
# so this will give an error
#print(a.__m)        # AttributeError: 'C' object has no attribute '__m'

# this would also create a similar error
#print(a.__subtract(4))

b = B(2)
print(b)  # <__main__.B object at 0x02794B10>

# works as expected, method add has been inherited
print(b.add(5))  # 7

# does not work as expected, method __subtract has not been inherited
print(b.deduct(1))  # 1
Ene Uran 638 Posting Virtuoso

Also, please use a meaningful title.

Ene Uran 638 Posting Virtuoso

Here we create radiobuttons with list comprehension:

''' tk_RadioButton_multi3.py
explore Tkinter's Radiobutton widget
create muliple radio buttons with list comprehension

'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def click():
    """shows the value of the radio button selected"""
    root.title(vs.get())

root = tk.Tk()

# create a labeled frame for the radiobuttons
# relief='groove' and labelanchor='nw' are default
labfr = tk.LabelFrame(root, text=" select one ", bd=3)
labfr.pack(padx=55, pady=10)

# use a string variable
vs = tk.StringVar()

values = ['eggs', 'spam', 'cheese', 'bacon']
# create a list of Radiobutton instances
radiobuttons = [tk.Radiobutton(labfr, text=val, value=val,
    variable=vs, command=click) for val in values]

# use the pack() layout manager to position the radio buttons
[rb.pack(anchor='w') for rb in radiobuttons]

# needed, set to None or any of the radiobutton values
vs.set('spam')
# show value set
if vs:
    click()

root.mainloop()
Ene Uran 638 Posting Virtuoso

Assume you have a list of unique integers, write a program that will show the closest pair or pairs.

Ene Uran 638 Posting Virtuoso

Control a turtle graphics canvas (module turtle) from an external Tkinter window with buttons.

Ene Uran 638 Posting Virtuoso

Don't jump the gun and download Python 3.3 yet, it still has a few bugs.
Download the much more stable Python 3.2

Ene Uran 638 Posting Virtuoso

Another look at the Python module turtle:

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, 0) by default
# draw 3 turtle lines to form a triangle

import turtle as tu

tu.title('draw an equilateral triangle')
# set at 50% of original size
tu.setup(width=0.5, height=0.5)

# optional ...
# values for speed are 'fastest' (no delay), 'fast', (delay 5ms),
# 'normal' (delay 10ms), 'slow' (delay 15ms), 'slowest' (delay 20ms)
#tu.speed('fastest')

# optional ...
# turtle by default starts at (x=0, y=0) center of a (450x550) window
# to pick another center lift the pen up then move
# to the right x units and up y units or ...
# to the left -x units and down -y units
# now drop the pen down to start drawing
tu.up()
tu.goto(60, 100)
tu.down()

# optional pen color
tu.color('red')

# form a triangle by drawing 3 lines of 150 pixels length
# changing the direction by 120 degrees (360/3) each time
# starts at upper right corner and points down
for k in range(3):
    tu.right(120)
    tu.forward(150)

# keep showing until window corner x is clicked
tu.done()
Ene Uran 638 Posting Virtuoso

Look at this:

# named tuples have named indexes they behave similar to class
# instances but require no more memory than regular tuples
# the record_list of named tuples can be saved(dumped) and loaded
# with Python module pickle

import collections as co

# create the named tuple
Movies = co.namedtuple('Movies',
         'title, year, director, minutes, cast')

record_list = []
# create one record for the record_list
title = "The Holy Grail"
year = 1975
director = "Terry Jones & Terry Gilliam"
minutes = 91
cast = [
'Graham Chapman',
'John Cleese',
'Terry Gilliam',
'Eric Idle',
'Terry Jones',
'Michael Palin']
record_list.append(Movies(title, year, director, minutes, cast))

# now you can do things like this
actor = 'John Cleese'
for movies in record_list:
    if actor in movies.cast:
        print("%s acted in %s" % (actor, movies.title))

'''my result -->
John Cleese acted in The Holy Grail
'''
vegaseat commented: the way to go +14
Ene Uran 638 Posting Virtuoso

Just a note, Python3 does not contain string.letters

Ene Uran 638 Posting Virtuoso

Now I have a few questions to out international friends.

This is what I get from my computer here in the USA:

# run on a computer set to English language

import string

eng_letters = string.letters

print(eng_letters)

'''my result -->
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
'''

Here are my questions:

What does string.letters look like in your country?

Does isalpha() include the alphabet of your country?

Could you post the results of string.letters so we can use that constant?
(Maybe they are published somewhere?)

Ene Uran 638 Posting Virtuoso

Hope you are not a mouse. This shows you how to select multiple listbox items from a Tkinter listbox widget:

'''Tk_Listbox_multiselect1.py
create a scrollable listbox using Tkinter
load the listbox with tasty cheese data
and select your favorite cheese or cheeses with the mouse
press <Shift> and/or <Ctrl> to select multiple cheeses
'''

try:
    # for Python2
    import Tkinter as tk
except ImportError:
    # for Python3
    import tkinter as tk


def get_list(event):
    """
    function to read the listbox selection(s)
    and put the result in a label widget
    """
    # get multiselected line indices
    indices = listbox.curselection()
    print(indices)  # test
    # get the selected lines' text
    seltext = '\n'.join(listbox.get(ix) for ix in indices)
    # put the selected text in the label
    label['text'] = seltext

root = tk.Tk()
root.title("Cheeses")
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("150x300+100+70")

# create a label (width in characters)
s1 = "Click on a cheese"
s2 = "press <Shift> and/or"
s3 = "<Ctrl> for multiples"
sf = "%s\n%s\n%s" % (s1, s2, s3)
label = tk.Label(root, text= sf, width=25)
label.grid(row=0, column=0)

# create a listbox (height in characters/lines)
# give it a nice yellow background (bg) color
# press <Shift> and/or <Ctrl> to select multiple listelements
listbox = tk.Listbox(root, height=15, bg='yellow', selectmode='extended')
listbox.grid(row=1, column=0)

# the Tkinter listbox does not automatically scroll, you need
# to create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(command=listbox.yview, orient=tk.VERTICAL)
yscroll.grid(row=1, column=1, sticky='n'+'s')
listbox.configure(yscrollcommand=yscroll.set)

cheese_list = [
'Feta', 'Limburger', 'Camembert', 'Roquefort', 'Edam',
'Romadur', …
Ene Uran 638 Posting Virtuoso

Or you can do this:

import sys

def myprint(item):
    '''
    print items on the same line
    works with Python2 and Python3 versions
    '''
    sys.stdout.write(str(item))
    sys.stdout.flush()

for x in range(10):
    myprint(x)

'''result -->
0123456789
'''
Ene Uran 638 Posting Virtuoso

pyTony's code does not work on my US computer, it gives False for his name.

Ene Uran 638 Posting Virtuoso

There are a number of other errors, wit this:

# calculates sum of squares of natural numbers
print "Enter number of terms."
n = int(raw_input("Terms? "))

first_term = ( ( n * n + n ) / 2 ) - 1

m = n
if m != 0:
    b = m * m + m
    m -= 1
    a = b

while m != 0:   # use !=
    a = b
    b = m * m + m
    m -= 1
    a = a + b
else:
    print "----"  # test
    #break  # error: at that point you are outside of the loop

second_term = a

third_term = 1

answer = first_term + second_term + third_term

print answer
Ene Uran 638 Posting Virtuoso

Look under PYTHONOPTIMIZE in the Python manual.

Ene Uran 638 Posting Virtuoso

The PyGTK GUI toolkit can make a list box, but it is not simple:

'''pgtk_listbox1.py
uses gtk.TreeView(), gtk.ListStore() and gtk.CellRendererText()
to create a single column listbox
'''

import pygtk
pygtk.require('2.0')
import gtk

class MyListBox(object):
    '''
    create a single column listbox
    '''
    def delete_event(self, widget, event, data=None):
        gtk.main_quit()
        return False

    def __init__(self, name_list):
        """create a single column list box and load it with data"""
        self.name_list = name_list
        # Create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_size_request(200, 300)
        # allows for smooth exit on 'x' click
        self.window.connect("delete_event", self.delete_event)

        # create the list model and load with the name_list
        self.listmodel = self.make_list()

        # create the TreeView
        self.treeview = gtk.TreeView()

        cell = gtk.CellRendererText()
        # create the "Name" column
        self.tvcolumn = gtk.TreeViewColumn("Names", cell)
        # align data to the left
        cell.set_property('yalign', 1.0)
        self.tvcolumn.set_cell_data_func(cell, self.cell_property)
        # append the only column to the treeview
        self.treeview.append_column(self.tvcolumn)
        # make it a list
        self.treeview.set_model(self.listmodel)
        # create a scrolled window for the treeview
        self.scrolledwindow = gtk.ScrolledWindow()
        self.scrolledwindow.add(self.treeview)
        # add the scrolled window to the main window
        self.window.add(self.scrolledwindow)
        # now show the main window
        self.window.show_all()

    def make_list(self):
        """
        create and load the list model
        """
        self.window.set_title("My name list")
        listmodel = gtk.ListStore(object)
        for name in self.name_list:
            #print(name)  # test
            listmodel.append([name])
        return listmodel

    def cell_property(self, column, cell, model, iter):
        """set cells to text"""
        cell.set_property('text', model.get_value(iter, 0))
        return


# a list of names for testing
name_list = [
"Frank Ferkel",
"Erich Meitinger",
"Leon Larimee",
"Jens Klein",
"Bjorn Bork",
"Heidrun Lovelace",
"Klaus Abraham",
"Ulla Jorgens",
"Volger Jenkings",
"Alexander Arm",
"Helmut Schmidt",
"Freja Larse",
"Larry Orkan",
"Andreas …
Ene Uran 638 Posting Virtuoso

Maybe this will help you:

import string

allowed_alpha = string.ascii_letters + string.whitespace

# a test name
name = "Mark Zumkoff"

# gives False because of space
print(name.isalpha())

# this test allows spaces
if all(c in allowed_alpha for c in name):
    print(name)
else:
    print("not an allowed name")
vegaseat commented: well done +14
Ene Uran 638 Posting Virtuoso

Even though the numpy array is shown as a list of tuples, you can change the items in the tuples. For example:

# test module numpy loadtxt()
# Python27 or Python32

import numpy as np
try:
    # Python2
    from StringIO import StringIO
except ImportError:
    # Python3
    from io import StringIO

# csv type test data
data_str = '''\
Fred,223.0
Monika,156.0
Larry,189.5
'''

# create a file object
data_file = StringIO(data_str)

#mytype = np.dtype([('mystring','S20'),('myfloat','float')])
# or more descriptive
mytype = {'names': ('person','weight'), 'formats': ('S20', 'f4')} 

print(mytype)  # test

print('-'*30)

arr = np.loadtxt(data_file, delimiter=',', dtype=mytype) 

print(arr)
print(type(arr))

print('-'*30)

print("look at parts of the array;")
print(arr['weight'])
print(arr['weight'][1])
print(arr['person'])
monika_ix = list(arr['person']).index('Monika')
print(monika_ix)

print('-'*30)

# even though the array is shown as a list of tuples
# you can change the items in the tuples
print("change a specific item like Monika's weight:")
arr['weight'][monika_ix] = 177.5
# show change
print(arr)

'''result >>>
{'names': ('person', 'weight'), 'formats': ('S20', 'f4')}
------------------------------
[('Fred', 223.0) ('Monika', 156.0) ('Larry', 189.5)]
<type 'numpy.ndarray'>
------------------------------
look at parts of the array;
[ 223.   156.   189.5]
156.0
['Fred' 'Monika' 'Larry']
1
------------------------------
change a specific item like Monika's weight:
[('Fred', 223.0) ('Monika', 177.5) ('Larry', 189.5)]
'''
Ene Uran 638 Posting Virtuoso

I am glad you could make it work! Nice job and interesting project!

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

This might help:

# sum some data of a csv file

raw_data = '''\
Station Name,Lat,Long,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Test 1,45.125478,-105.623154,3.12,0.15,0.08,0.61,0.67,1.24,2.32,1.06,0.64,0.07,0.32,1.02
Test 2,42.854123,-106.321587,0.09,3.15,1.61,0.03,0.84,1.62,3.01,1.51,0.81,0.02,0.23,1.09
Test 3,43.974532,-105.896214,2.65,2.01,0.05,3.02,1.05,0.08,0.08,1.06,0.43,0.65,0.12,1.06
'''

# create the test data file
fname = "mydata.csv"
with open(fname, "w") as fout:
    fout.write(raw_data)

# read the data file
data_list = []
for line in open(fname):
    # remove trailing newline char
    line = line.rstrip()
    # create a list
    line_list = line.split(',')
    data_list.append(line_list)

# create a months dictionary with month:index pairs
mdict = {}
for ix, item in enumerate(data_list[0]):
    print(ix, item)  # test
    if ix > 2:
        mdict[item] = ix

print(mdict)  # test
print('-'*70)

month_start = 'Apr'
month_end = 'Jul'
new_list = []
for item in data_list[1:]:
    #print(item) # test
    station = item[0]
    lat = item[1]
    long = item[2]
    start = mdict[month_start]
    end = mdict[month_end]+1
    plist = [float(x) for x in item[start : end]]
    print(plist) # test
    mysum = sum(plist)
    new_list.append([station, lat, long, mysum])

print('-'*70)
print("Result:")
for item in new_list:
    print(item)
Ene Uran 638 Posting Virtuoso

Mutable objects can change their value but keep their id().

Ene Uran 638 Posting Virtuoso

Could be the start of a word game:

# a simple rotate cipher

from collections import deque

def rotate_right(text, n=1):
    """
    use deque to rotate text n steps to the right
    return rotated text
    """
    rot_right = deque(text)
    rot_right.rotate(n)
    return "".join(rot_right)

def rotate_left(text, n=1):
    """
    use deque to rotate text n steps to the left
    return rotated text
    """
    rot_left = deque(text)
    rot_left.rotate(-n)
    return "".join(rot_left)

# cipher the text by rotating 3 steps
text = 'peanuts'
n = 3
print(rotate_right(text, n))  # utspean

# decipher the text
text = 'utspean'
print(rotate_left(text, n))  # peanuts
Ene Uran 638 Posting Virtuoso

Orange chicken on noodles, drinking hot black tea.

Ene Uran 638 Posting Virtuoso

"Deleted code is debugged code."
-- Jeff N. Sickel

Ene Uran 638 Posting Virtuoso

I am not sure if the book
"Python for Idiots"
has been published yet.
I am waiting!

Ene Uran 638 Posting Virtuoso

If you are bored, you most like know less than 0.0001% of the world. So, get to know the remaining percentage of the world!

Ene Uran 638 Posting Virtuoso

I normally use:

from PyQt4.QtCore import *
from PyQt4.QtGui import *

to make life simpler

Ene Uran 638 Posting Virtuoso

Blueberies (real fresh from Canada) and cream.

Ene Uran 638 Posting Virtuoso

"Everyone thinks of changing the world, but no one thinks of changing himself."
-- Leo Tolstoy

Ene Uran 638 Posting Virtuoso

Maybe this test print will help:

import djvu.decode as DjVu
from PyQt4.QtCore import QImage
from PyQt4.QtGui import QPixmap, QApplication, QLabel

def djvu2pixmap( filename, width, height ) :
    doc = DjVu.Context().new_document( DjVu.FileURI( filename ) )
    doc.decoding_job.wait()
    pg = doc.pages[ 0 ]
    pg.decode( wait = True )
    data = pg.thumbnail.render( ( width, height ), 
           DjVu.PixelFormatRgbMask( 0xff0000, 0xff00, 0xff, bpp = 32 ) )
    image = QIamge( data[ 1 ], data[ 0 ][ 0 ], data[ 0 ][ 1 ], 
            QImage.Format_RGB32 )
    image.save( "/tmp/image.png" )
    return QPixmap.fromImage( image )

if __name__ == '__main__' :

    import sys

    app = QApplication( sys.argv )

    lbl = QLabel()
    pixmap = djvu2pixmap( "trial.djvu", 200, 300 ) 
    print(pixmap)  # a test print
    lbl.setPixmap( pixmap, 200, 300 )
    lbl.show()
    lbl.resize( lbl.pixmap().size() )

    exit( app.exec_() )
Ene Uran 638 Posting Virtuoso

To test out your program and possible help you, I installed
python-djvulibre-0.3.4.win32-py2.7.exe
from
http://pypi.python.org/pypi/python-djvulibre/0.3.4

This works:

import djvu

help(djvu)

'''output -->
Help on package djvu:

NAME
    djvu

FILE
    c:\python27\lib\site-packages\djvu\__init__.py

PACKAGE CONTENTS
    const
    decode
    dllpath
    sexpr
'''

However, this gives an error:

import djvu.decode

'''output -->
Traceback (most recent call last):
  File "C:/Python27/Atest27/Bull/djvu_test2.py", line 1, in <module>
    import djvu.decode
ImportError: DLL load failed: The specified module could not be found.
'''

Is there something missing that you have found?

Ene Uran 638 Posting Virtuoso

Threading may solve your problem, here is an example:

'''threading_Timer1_sound.py
threading allows other program segments to run at the same time
threading.Timer() forms an interruptable sleep() function
t = threading.Timer(interval, function, args=[], kwargs={})
t.start()   starts the thread
t.cancel()  stops the thread
t.isAlive() checks active thread
winsound.Beep(frequency, duration) needs Windows OS
'''

import threading
import winsound

def action1():
    print("We are being attacked!")

def alarm():
    # 500 hz sound for 9 seconds
    winsound.Beep(500, 9000)

def action2():
    print("Wake up our troops!")

def action3():
    print("Our troops are ready!")

# after 0.1 seconds do action1
t1 = threading.Timer(0.1, action1)
# after 3.5 seconds do action2
# and after 10.0 seconds do action3
t2 = threading.Timer(3.5, action2)
t3 = threading.Timer(10.0, action3)

# this will wake the troops after action2 has been called
t4 = threading.Timer(4.5, alarm)

t1.start()
t2.start()
t3.start()
t4.start()
Ene Uran 638 Posting Virtuoso

Tobacco kills more Americans than AIDS, drugs, homicides, fires, and auto accidents combined.

Ene Uran 638 Posting Virtuoso

If you smoke you are honest, at least it shows the rest of us that you are not very smart.

Reverend Jim commented: Same reason I like body piercing and tattoos. +0
Ezzaral commented: The view from such a high horse must be quite grand indeed. +0
Ene Uran 638 Posting Virtuoso

You will end up with two competing event loops. Threading might be the answer.

Ene Uran 638 Posting Virtuoso

Rednecks only have to count to 10.

"Pain is temporary; pride is forever!"

Reverend Jim commented: Hah! +0
Ene Uran 638 Posting Virtuoso

2 problems:

line 11 the list yfoo needs to end with a ]

line 26 needs to be if Fail == True: