vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Richard "Little Dick" West (1860 - 1898) was an outlaw of the Old West, and a member of Bill Doolin's Wild Bunch gang.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Replace your list comprehension with a generator expression ( simply replace [] with () ), then you can use the ifilter() method of module itertools to limit the range of values ...

# create an iterable of square numbers and return only numbers that
# are above 20 and below 200 using itertools.ifilter(predicate, iterable)

from itertools import ifilter

# use a generator expression
square_gen = ( x**2 for x in range(100) )

result = list(ifilter(lambda x: 20 < x < 200, square_gen))

print(result)

"""result >>>
[25, 36, 49, 64, 81, 100, 121, 144, 169, 196]
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Formatting time/date strings is easy with Python module time ...

# convert 14-05-1999 to May-14
# see Python manual for module time format specifiers

import time

date_old = "14-05-1999"

# use strptime(time_str, format_str) to form a time tuple
time_tuple = time.strptime(date_old, "%d-%m-%Y")

#print(time_tuple)  # test

# use time.strftime(format_str, time_tuple) to create new format
date_new = time.strftime("%b-%d", time_tuple)

print(date_old)  # 14-05-1999
print(date_new)  # May-14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... when you remember the days when a tennis match was just that, and not a match of screams, squeals and groans. I cant' believe that every time they hit the ball, they have to let go of an annoying loud sound. Sounds so stupid!

Imagine programmers doing that with every keystroke.

jonsca commented: You don't do that? +0
Nick Evan commented: That's brialliant. I'm certainly going to try this :) +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here we are using a class to create a decorator. The Memoize decorator is very useful in speeding up recursive functions ...

# applying a memoize decorator  to a recursive function
# and timing to show the improvement in speed
# keyword args allowed
# tested with Python 2.6.5 and Python 3.1.2

import timeit

class Memoize(object):
    """
    use as a decorator to avoid repeating calculations
    previously done by the decorated function
    (allows functions with keyword arguments)
    """
    def __init__(self,f):
        self.f = f
        self.memo = {}
    def __call__(self, *args, **kwargs):
        # allows keyword args with some performance cost  
        kws = tuple(kwargs.items())
        if (args,kws) in self.memo:
            return self.memo[(args,kws)]
        result = self.f(*args, **kwargs)
        self.memo[(args,kws)] = result
        return result

def use_timeit(stmt, setup, passes=1000):
    """
    use module timeit to time a statement stmt
    (this can be a function call too)
    setup gives information where too find variables/functions
    (for time consuming functions use fewer passes to save time)
    for instance ...
    stmt = 'myfunction(x)'
    setup = 'from __main__ import myfunction, x'
    """
    t = timeit.Timer(stmt=stmt, setup=setup)
    # doing 10 passes * 100000 gives the time in microseconds/pass
    elapsed = (1000000//passes * t.timeit(number=passes))
    print( "Function '%s' takes %0.3f micro-seconds/pass" % \
        (stmt, elapsed) )     


@Memoize
def fibo1(n):
    """
    use recursion to get Fibonacci number for n
    not very efficient because of the many function calls
    """
    if n < 2:
        return n
    else:
        return fibo1(n - 1) + fibo1(n - 2)

stmt1 = 'fibo1(n=30)'
setup1 = 'from __main__ import fibo1'
passes1 = 3
use_timeit(stmt1, setup1, passes1) …
TrustyTony commented: Usefull as long as multiple arguments don't change too much +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It might just be the space-in-directory-name problem the some versions of Windows have.
Try the well known kludge ...

# the Microsoft kludge, quoting a string within a string fixes the 
# space-in-folder-name problem, tells the OS to use the whole string
# including spaces as a single command
'"C:/Documents and Settings/User/Desktop/myscript.py"'
lrh9 commented: A legitimate attempt to help the user accomplish what they want to accomplish. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In Python you can combine functions to form a new functions. Here is an example of combining two functions ...

# combining functions in Python

def combine_two(f1, f2):
    """
    combine two functions f1 and f2
    having arguments *a
    """
    def inner(*a):
        return f1(f2(*a))
    return inner

def reverse(s):
    """reverse string s"""
    return s[::-1]

def uppercase(s):
    """convert string s to all upper case"""
    return s.upper()

# combine the functions reverse, uppercase
# creating a new function rev_up()
rev_up = combine_two(reverse, uppercase)

print(rev_up('hello world!'))  # !DLROW OLLEH
TrustyTony commented: Nice trick +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It's Father's Day and a father walks into a drug store with his 10-year old son.

They happen to walk by the condom display, and the boy asks,
"What are these, Dad?"

To which the father matter-of-factly replies,
"Those are called condoms, son. Men use them to have safe sex."

"Oh I see," replied the boy, "Yes, I've heard of that in health class at school."

He looks over the display and picks up a package of 3 and asks, "Why are there 3 in this package?"

His father replies, "Those are for high school boys. One for Friday, one for Saturday, and one for Sunday."

"Cool!" says the boy. He then notices a 6 pack and asks, "Then who are these for?"

"Those are for college men." his father answers, "Two for Friday, two for Saturday, and two for Sunday."

"Wow!" exclaimed the boy, "then who uses these?" he asks, picking up a 12 pack.

With a sigh, the father replies, "Those are for married men. One for January, one for February, one for March ...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another short look at the simplicity of Python class inheritance ...

# a look at Python's class constructor, method, instance
# inheritance, private variables/methods
# class names are captalized by convention to aid readability
# modified for Python3 formatted printing

class Cat:
    # this is public to all instances of class Cat
    cost = 100
    # this is private to the class
    __price = cost + cost * 0.25
    # constructor
    def __init__(self, num=1):
        self.num = num
        self.sound = "meow " * self.num
        print(self.sound)

    def own(self):
        #print("I own %s cats" % self.num)
        print("I own {:d} cats".format(self.num))

    def paid(self):
        self.total = self.__price * self.num
        #print("I paid $%0.2f for my cats" % self.total)
        print("I paid ${:0.2f} for my cats".format(self.total))

    def kitten(self):
        self.kit = 5
        print("One cat just had {:d} kittens".format(self.kit))
        return self.kit


class Dog:
    # this is public
    cost = 400
    # this is private to the class
    __price = cost + cost * 0.25
    # constructor
    def __init__(self, num=1):
        self.num = num
        self.sound = "woof " * self.num
        print(self.sound)

    def own(self):
        #print("I own %s dogs" % self.num)
        print("I own {:d} dogs".format(self.num))

    def paid(self):
        self.total = self.__price * self.num
        #print("I paid $%0.2f for my dogs" % self.total
        print("I paid ${:0.2f} for my dogs".format(self.total))


class Pets(Cat, Dog):
    """class Pets inherits class Cat and class Dog"""
    # constructor
    def __init__(self):
        self.num = cat.num + dog.num
        self.sound = cat.sound + dog.sound
        print(self.sound)

    def own(self):
        #print("I own %s pets" % self.num)
        print("I own {:d} pets".format(self.num))

    def paid(self):
        total = dog.total + cat.total
        #print("I paid $%0.2f …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you use a Python container called a dictionary, you can come close to what you aspire ...

text = 'ARARAKHTLROGKFMBLFKKGOHMFDGRKLRNGROGINFBLMNFBAEKJGFGOQEITHRGLFDKBN'

abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# create a letter dictionary with character:frequency pairs
letter = {}
for c in text:
    letter[c] = letter.get(c, 0) + 1

print letter['A']  # 4
print letter['R']  # 7

for c in abc:
    if c in letter:
        print c, letter[c]

"""my output -->
A 4
B 4
D 2
E 2
F 7
G 8
H 3
I 2
J 1
K 7
L 5
M 3
N 4
O 4
Q 1
R 7
T 2
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

So, what was your questions and what was your answer?
Maybe other people can learn from your skills.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I used the PyQT Designer to create a simple XML file (ButtonList1.ui) containing just a QWidget, a QPushButton, and a QListWidget ...

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>272</width>
    <height>259</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Button and List</string>
  </property>
  <widget class="QPushButton" name="button1">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>10</y>
     <width>111</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>Add item to list</string>
   </property>
  </widget>
  <widget class="QListWidget" name="list1">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>50</y>
     <width>111</width>
     <height>192</height>
    </rect>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

I then wrote a simple loader to used the XML file and PyQT ...

# a simple loader for .ui files generated with QTDesigner
# this UI is an XML file that contains
# QWidget
# QPushButton named button1
# QListWidget named list1
# link from button1 to list1 is via a decorator
# however, you have to use method name on_button1_clicked
# tested with PyQT version 4.7.2

from PyQt4 import QtCore, QtGui, uic

class MyWindow(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        uic.loadUi("ButtonList1.ui", self)
        self.count = 1
  
    @QtCore.pyqtSignature("")
    def on_button1_clicked(self):
        """button1 has been clicked, add item to list1"""
        s = "This is item%s" % self.count
        self.list1.addItem(s)
        self.count += 1


app = QtGui.QApplication([])
widget = MyWindow()
widget.show()
app.exec_()

The button1 click was not linked to list1 in the Designer, the little decorator used seems to figure that out, as long as you use the method name on_button1_clicked

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is another code example using Python module sqlite3 that you can use to experiment with ...

# test module sqlite3 write and read a database file
# (Python25 and higher have module sqlite3 built in)
# sqlite3.connect(database, timeout=5.0, isolation_level=None,
#   detect_types=0, factory=100)
# keywords:
# timeout=5.0 --> allows multiple access for 5 seconds
# isolation_level=None -->  autocommit mode
# detect_types=0 --> native types TEXT, INTEGER, FLOAT, BLOB and NULL
# factory=100 --> statement cache to avoid SQL parsing overhead

import sqlite3

# create/connect to a permanent file database
con = sqlite3.connect("my_db.db3")

# establish the cursor, needed to execute the connected db
cur = con.cursor()

# create/execute a table:
# (optionally used capital letters to show commands)
cur.execute('CREATE TABLE IF NOT EXISTS clients \
    (id INT PRIMARY KEY, \
    firstname CHAR(60), \
    lastname CHAR(60))')

# insert several lines at once using a
# list of (id, firstname, lastname) tuples
# use try/except or the existing db will complain about
# the non-unique id since it is already in the db
try:
    clients = [
    (107, "Ella", "Fitzgerald"),
    (108, "Louis", "Armstrong"),
    (109, "Miles", "Davis")
    ]
    cur.executemany("INSERT INTO clients (id, firstname, lastname) \
        VALUES (?, ?, ?)", clients )
except:
    pass

# add another client
# use try/except or the existing db will complain about
# the non-unique id if it is already in the db
try:
    new_client = (110, "Benny", "Goodman")
    cur.execute("INSERT INTO clients (id, firstname, lastname) \
        VALUES (?, ?, ?)", new_client)
except:
    pass

# important if you make …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Looks like the author is talking about the fact that a word:frequency dictionary of the book would be a lot shorter than a word list. Efficiency would be to get a representative random word from the book, that also reflects the frequency of the word, directly from the dictionary without expanding it into a long word list.

Imagine a book of 1 million words. A word list of every word in the book would have 1 million items. A word:frequency dictionary might only have 5,000 to 10,000 items, since duplicate words are taken care of in the frequency value.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"I love to do the things the censors won't pass."
-- Marilyn Monroe

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Starting with version 2.6 Python has introduced a new container called the named tuple. You can use it similar to a class based record structure, but it has the memory efficiency of a tuple.

griswolf commented: I appreciate hearing about the new things Python has for us +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just an example of drawing shapes with the pygame module ...

# exploring module pygame

import pygame as pg

# pygame uses (r, g, b) color tuples
white = (255, 255, 255)
blue = (0, 0, 255)

# create a 300 x 300 pixel display window
win = pg.display.set_mode((300, 300))
# optional title bar caption
pg.display.set_caption('A Pygame Drawing')
# default background is black, so make it white
win.fill(white)


# --- draw a blue circle on a white background ---
# center coordinates (x, y)
center = (150, 150)
radius = 100
# width of 0 (default) fills the circle
# otherwise it is thickness of outline
# test it by changing width to 1, 2 or 5
width = 0
# draw.circle(Surface, color, pos, radius, width)
pg.draw.circle(win, blue, center, radius, width)


# update the display window to show the drawing
pg.display.flip()

# event loop and exit conditions
# (windows titlebar x click to exit)
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            raise SystemExit

You can use the above code as a general template to draw many different shapes. Just the center of the code needs to be changed ...

# exploring module pygame
# draw a blue rectangle on a white background

import pygame as pg

# pygame uses (r, g, b) color tuples
white = (255, 255, 255)
blue = (0, 0, 255)

# create a 300 x 300 pixel display window
win = pg.display.set_mode((300, 300))
# optional title bar caption
pg.display.set_caption('A Pygame Drawing') …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Simple code to show you how to access the selected choice of a Tkinter Optionmenu() ...

# using Tkinter's Optionmenu() as a combobox
# allows one item to be selected
# use trace() and globalgetvar(name) to show selected choice

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

def show_choice(name, index, mode):
    sf = "value is %s" % root.globalgetvar(name)
    root.title(sf)


root = tk.Tk()

choices = ['red', 'green', 'blue', 'yellow','white']
color = tk.StringVar(root)
color.trace('w', show_choice)
# optionally preselect a choice
color.set(choices[2])
color_option = tk.OptionMenu(root, color, *choices)
color_option.pack(padx=70, pady=10)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Well, your mind seems to be made up, if you dislike Python, there isn't much I will do about it!
Python is a tool, just like any other computer language. If you can't figure out any advantages, don't use that tool.

Computer languages are tools that allow you to write the real world in little chunks that even a mindless machine like a computer can understand.

Or as more important people have so wisely said ...

"Coded with Python" is a trade secret for the companies enlightened enough to use it as their
language of choice, because it is so productive that it provides a competitive advantage.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just like Miller Lite, there is now Spam Lite. Turkey Spam is highly recommended and very good for you! I would avoid Signature Spam, that one simply suggs!

A day without Spam is like a day without healthy food. :)

nav33n commented: :P +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can expand on something simple like that ...

''' contents of data_file_1.txt -->
Fred, Nurke, 16, 17, 22
Jack, Sprat, 12, 13, 19
George, Reynolds, 14, 11, 30
Harry, Smith, 19, 19, 37
Daniel, Robins, 10, 8, 22
Jacquiline, Stevens, 23, 18, 31
Erin, Collins, 24, 30, 35
William, Steadford, 12, 15, 20
Laura, Schmidt, 25, 27, 36
Nikki, Dimitri, 14, 17, 24
'''

with open('data_file_1.txt', 'r') as fin:
    print("%-20s %5s %5s %5s" % ('name', 'score1', 'score2', 'score3'))
    for line in fin:
        # strip trailing newline char
        line = line.rstrip()
        first, last, score1, score2, score3 = line.split(',')
        name = first + last
        print("%-20s %5s %5s %5s" % (name, score1, score2, score3))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Interesting, you must have hit a gap in the algorithm. I tested it out and came up with these results ...

# numpy.random.hypergeometric(ngood, nbad, nsample, size=None)

import numpy as np

# these work fine
print np.random.hypergeometric(10000, 10000, 10000)
print np.random.hypergeometric(100000, 1000000, 100000)
print np.random.hypergeometric(10000000, 1000000000, 1000000)

# these freeze up
#print np.random.hypergeometric(1000000, 10000000, 100000)
#print np.random.hypergeometric(1000000/10, 10000000/10, 100000/10)
#print np.random.hypergeometric(1000000*10, 10000000*10, 100000*10)
#print np.random.hypergeometric(1000000*100, 10000000*100, 100000*100)

# this works again
# would it give meaningful data?
print np.random.hypergeometric(1000000/100, 10000000/100, 100000/100)*100
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Of course, you simply move the find() start position up as you search ...

# multiple searches of a string for a substring
# using s.find(sub[ ,start[, end]])

text = 'MSKSASPKEPEQLRKLFIGGLSFETTDESLRSAHFESSSYGSAGRRF'

search = 'SA'
start = 0
while True:
    index = text.find(search, start)
    # if search string not found, find() returns -1
    # search is complete, break out of the while loop
    if index == -1:
        break
    print( "%s found at index %d" % (search, index) )
    # move to next possible start position
    start = index + 1

"""my result (index is zero based)-->
SA found at index 3
SA found at index 31
SA found at index 41
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Make the min_item the first item in the list. Then iterate through the list and compare. If the list item is less than the present min_item, make it the new min_item.

Do a similar thing with max_item.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This would be a simple search in a nested list, but this approach has certain caveats ...

mylist = [['dog', 'cat'], ['lizard', 'sheep', 'pig']]
print( "'sheep'" in str(mylist) )  # True
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Many folks have stumbled over the behavior of floating point number representations common in most computer languages. On the surface two floating point numbers look alike or should look alike, however in the inner workings of a binary beast like the digital computer there appear tiny differences. Here is Python code showing you what I mean ...

# let's say we have a = 6.4 and b = 6.3 + 0.1
# for all practical purposes a and b should be the same
# however, there is a tiny discrepancy in the way the
# binary computer represents floating point numbers

def fuzzy_compare(a, b, delta=0.000000001):
    """
    used for == comparison of floating point numbers a and b
    returns True if the difference between a and b does not
    exceed delta otherwise returns False
    """
    return abs(a-b) < delta

# testing ...
a = 6.4
b = 6.3 + 0.1
# a list truly shows the reality
# the difference is a very tiny 0.0000000000000009
print( [a, b] )  # [6.4000000000000004, 6.3999999999999995]

print( a == b )  # False

print( fuzzy_compare(a, b) )  # True
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A short look at creating lists of file names or full path names using the versatile Python module glob. Glob follows the standard wildcard protocol.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a function that will check for valid numeric input ...

# a simple input function to guarantee numeric input
# tested with Python 3.1.2

def input_num(prompt="Enter a number: "):
    """
    prompt the user for a numeric input
    prompt again if the input is not numeric
    return an integer or a float
    """
    while True:
        # strip() removes any leading or trailing whitespace
        num_str = input(prompt).strip()
        num_flag = True
        for c in num_str:
            # check for non-numerics
            if c not in '+-.0123456789':
                num_flag = False
        if num_flag:
            break
    # a float contains a period (US)
    if '.' in num_str:
        return float(num_str)
    else:
        return int(num_str)

def input_num2(prompt="Enter a number: "):
    """
    prompt the user for a numeric input
    prompt again if the input is not numeric
    return an integer or a float
    """
    while True:
        # strip() removes any leading or trailing whitespace
        num_str = input(prompt).strip()
        # make sure that all char can be in a typical number
        if all(c in '+-.0123456789' for c in num_str):
            break
    # a float contains a period (US)
    if '.' in num_str:
        return float(num_str)
    else:
        return int(num_str)

# test ...
num = input_num()

print(type(num))
print(num)
print('-'*20)

num2 = input_num2()

print(type(num2))
print(num2)

Function input_num2() is mildly more pythonic.

arithehun commented: Creative +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Start experimenting with Python module decimal ...

# high accuracy calculations with Python module decimal
# tested with Python 3.1.2

import decimal as dc

# regular float calculation
sqrt1 = 2 ** 0.5

print(type(sqrt1))
print(sqrt1)
print(sqrt1 * sqrt1)

# set decimal precition
dc.getcontext().prec = 60

# using module decimal
sqrt2 = dc.Decimal(2) ** dc.Decimal('0.5')

print(type(sqrt2))
print(sqrt2)
print(sqrt2 * sqrt2)

"""my result -->
<class 'float'>
1.41421356237
2.0
<class 'decimal.Decimal'>
1.41421356237309504880168872420969807856967187537694807317668
2.00000000000000000000000000000000000000000000000000000000000
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another approach to keep variable names and values together ...

def funk():
    v1 = 3
    v2 = 1
    v3 = 7
    v4 = 6
    v5 = 5
    # returns function's local variable dictionary
    return vars()

mydict = funk()
print(mydict)
print('-'*55)

# create (value, key) tuples and sort by value
# keeps key and value together
vk_tuple = sorted((v, k) for k, v in mydict.items())
print(vk_tuple)

"""my results -->
{'v1': 3, 'v2': 1, 'v3': 7, 'v4': 6, 'v5': 5}
-------------------------------------------------------
[(1, 'v2'), (3, 'v1'), (5, 'v5'), (6, 'v4'), (7, 'v3')]
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

God loves stupid people
He made so many

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It has never made much sense to sort mixed type lists. So it's nice to see that Python3 put a stop to it ...

mixed_list = [3, 2, 'a', (5, 2,), 'd', 'c']

print(sorted(mixed_list))

"""my result -->
Python2
[2, 3, 'a', 'c', 'd', (5, 2)]
Python3
TypeError: unorderable types: str() < int()
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Enlighten us a little ...
What is protege?
What is owl ontology?
What does a short sample of the raw data look like?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The idea of portable python is to run it from the usb drive, but it will run a little slower. Try out the great IDEs that come with it, like pyscripter or SPE.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A little late for April 1, but here is the secret code ...

searchEngineNames = []
for c in range(ord('A'), ord('Z')+1):
    name = chr(c)+'ing'
    searchEngineNames.append(name)

# pick #1
print(searchEngineNames[1])
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can discover more about a person after a few beers than in a year of sober conversation.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a code example ...

# using the module ctypes you can access DLLs written in C/C++
# ctypes converts between Python types and C types
# there are two ways to write DLLs:
# most common uses cdecl, import with cdll
# Win and VB may use stdcall, import with windll
# module ctypes is built into Python25 and higher
# look under ctypes in the Python manual

from ctypes import *

# as an example let's use msvcrt.dll
# this is the MS C library containing many standard C functions
# import the C function strchr() from msvcrt.dll
strchr = cdll.msvcrt.strchr

# declare the return type ...
# a 'pointer to a string' (which then converts to a Python string)
strchr.restype = c_char_p

# these are the argument types ...
# Python string converts to 'pointer to a string' --> c_char_p
# Python single char string converts to C char --> c_char
strchr.argtypes = [c_char_p, c_char]

# now call the function and show the result
print strchr('abcdefg', 'd')  # result --> defg

# some C functions are easier to access ...
printf = cdll.msvcrt.printf
printf("Hello, %s\n", "World!")
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The example shows how to establish a dictionary of (row, column):value pairs to mimic a two dimensional array. This can be easily expanded to more dimensions. Python3 has dictionary comprehension, making the process of creating a dictionary of this type easier.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just change your range(start, stop, step) parameters ...

n = 15
total = 0

# start at 1 in steps of 2 to get odd numbers
for i in range(1, n + 1, 2):
    total += i
    print i, total  # test

"""my result -->
1 1
3 4
5 9
7 16
9 25
11 36
13 49
15 64
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Originality is the fine art of remembering what you hear, but forgetting where you heard it.
-- vegaseat original

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Great find!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I would agree with SgtMe.
Even though you are running Windows7-64bit, you are better of to install the 32bit versions of Python and PyQt at this time.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Jython comes to mind. It would allow you to run Python code under Java.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If debugging is the process of removing bugs,
Then programming must be the process of putting them in.
-- Edsger Dijkstra

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a little quirk in Tkinter. Since the canvas has a default border of 2 pixels simply give it a bd=-2 to cancel it.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can keep track of the lines of text by using a list and the index number ...

# text for the test
test_text = """\
apple
banana
lemon
melon
pear"""

fname = "myfruits.txt"
#write the multiline text to a test file
fout = open(fname, "w")
fout.write(test_text)
fout.close()

# read the file back as a list of lines
fin = open(fname, "r")
data_list = fin.readlines()
fin.close()

print data_list

"""my output -->
['apple\n', 'banana\n', 'lemon\n', 'melon\n', 'pear']
"""

# optionally strip the trailing newline char '\n'
data_list = [item.rstrip('\n') for item in data_list]

print data_list

"""my output -->
['apple', 'banana', 'lemon', 'melon', 'pear']
"""

# now you can access each line (list item) by the index
# the index of a list is zero based
print data_list[0]  # apple
print data_list[3]  # melon
elvis1 commented: You blew my hat off, excelent, really thrilled me +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Two things stick out, the while loop is not needed and don't use Python function names like input as variable names ...

def saveScore(self):
        inp = raw_input().upper();
        if inp == "Y":
            #the use of 'a' will append the score to the scores.txt 
            fileHandle = open ( 'scores.txt', 'a' ) 
            fileHandle.write(str1)
            fileHandle.close()
            #print str1
            return
        elif inp == "N":
            return
        else:
            print "Choose either (Y) or (N)o. "
            self.saveScore()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... you know it all, but just can't remember it all at once.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To write out to file use ...

fileHandle = open ( 'scores.txt', 'w' )
fileHandle.write(str1)
fileHandle.close()

To append to an existig file use ...

fileHandle = open ( 'scores.txt', 'a' )
fileHandle.write(str1)
fileHandle.close()
Simes commented: did not know about the append function for text files. Thanks! +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Happiness does not buy money.