woooee 814 Nearly a Posting Maven

See if adding this print statement gives you any ideas.

# New board function
def new_board():
    """Create new game board."""
    board = []
    for square in range(NUM_SQUARES):
        print "adding square #", square
        board.append(EMPTY)
        return board
Cjreynol commented: Very very helpful, helped me work out a bug I had been having lots of trouble with! +0
vegaseat commented: nice help +10
woooee 814 Nearly a Posting Maven

Some of the crazy/weird holidays for February.
Super Bowl Sunday
Jobs in Golf Month
Marijuana Awareness Month (is that an oxymoron)
National Condom Month
National Laugh Friendly Month
National Pet Dental Health Month
Pull Your Sofa Off The Wall Month
Return Supermarket Carts Month

And in the Valentine spirit
Chocolate Lover's Month

First week in February is
Intimate Apparel Week

Second Week is
Dump Your Significant Jerk Week
Just Say 'No' To Powerpoints Week (you love it or hate it)
Rejection Risk Awareness Week
International Flirting Week
National Acts of Kindness Week
Love a Mench Week (look it up; it's not what you think)

Third Week is
National Condom Week (in National Condom Month= No babies born in November)

February 1st is "Working Naked Day" so if you are going to observe it, please tell me where and when so I can be elsewhere.

woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

See if adding this print statement clears things up. You have to compare the same type of variables, i.e. an integer to an integer, etc.

def Marks(*score):
    print score, type(score)
    marks0 = 0
    marks1 = 0
    marks2 = 0
    marks3 = 0
    marks4 = 0
    marks5 = 0

    if score == 0:
        marks0 = marks0+1
    elif score == 1:
        marks1 = marks1+1
    elif score == 2:
        marks2 = marks2+1
    elif score == 3:
        marks3 = marks3+1
    elif score == 4:
        marks4 = marks4+1
    elif score == 5:
        marks5 = marks5+1

    print "0 marks scored by", marks0 , "people."
    print "1 mark scored by", marks1 , "people."
    print "2 marks scored by", marks2 , "people."
    print "3 marks scored by", marks3 , "people."
    print "4 marks scored by", marks4 , "people."
    print "5 marks scored by", marks5 , "people."

Marks(1)

Also you can use a list instead of 6 variables.

def Marks(*score_input):
    marks_list = [0, 0, 0, 0, 0, 0]
    for score in score_input:
        if score < 6:
            marks_list[score] += 1
        else:
            print "Bogus score entered ----->", score

    for score in range(6):
        print "%s marks scored by %d people." % \
                 (score, marks_list[score])

Marks(1, 3, 3, 7, 5)
vegaseat commented: very helpful +10
woooee 814 Nearly a Posting Maven

Do you have to find up and down as well? If North is (5,5), and you are using a dictionary, you can easily look up (5,7) etc. instead of the list comprehension.
print coord_dict[(5,7)]
instead of
East = [e.color for e in objectList if (e.coord[0] == object.coord[0] + 2 and e.coord[1] == object.coord[1])]

You will add one and subtract one from the first number, and do the same for the second, giving you the four neighbors (if you don't want up or down = 6 directions). And are you sure that you want +2 instead of +1? Again, if North is (5,5) and you are looking for (5,7), what is (5,6)? Finally, if all else fails, store the neighbors coordinates in another dictionary so you can look up the original coordinate, and it will point to a list of the coordinates of all neighbors.

woooee 814 Nearly a Posting Maven

Spamming is often combined with 'plotting' scams, where areas are divided up into plots. It became popular with the stock market boom in the 20s but is still going strong today. With plotting, an area is divided up into plots, with half of the areas being sent spam saying that the price of gold, or whatever, will go up in the next X days or weeks. The other half gets spam that says the price of gold will go down. At the end of the alloted time, the winning half from the first spamming is divided into two, with one half being sent spam saying the price of silver will go up. The other half of course are told the price of silver will go down. The remaining quarter of the people which received spam that actually proved to be true are then solicited for expensive investment letters based on the success of these 'advisories'.

woooee 814 Nearly a Posting Maven

If I understand correctly, you should read a record, look for one of the strings, and print the line. Something like the following should be close to what you want.

## pass "fin" to the function and avoid the use of globals
def CifT(self, fin):
    pos1 = ["_chemical_formula_moiety", "_chemical_formula_weight", "_symmetry_cell_setting", 
        "_symmetry_space_group_name_H-M ", "_cell_length_a","_cell_length_b", "_cell_length_c", "_cell_angle_alpha",
        "_cell_angle_beta", "_cell_angle_gamma", "_cell_volume", "_cell_formula_units_Z", "_cell_measurement_temperature",
        "_cell_measurement_theta_min", "_cell_measurement_theta_max", "_exptl_absorpt_coefficient_mu", "_diffrn_radiation_type", 
        "_refine_ls_R_factor_all", "_refine_ls_R_factor_gt", "_refine_ls_wR_factor_ref", "_refine_ls_wR_factor_gt", "_refine_ls_goodness_of_fit_ref"]

    for rec_num, rec in enumerate(fin):
        rec = rec.strip()
        start = 0
        for phrase in pos1:
          while 1:
            pos = rec.find(phrase, start)
            if  pos < 0:
              break

            print rec_num, phrase, pos  #print a number of line for each keyword
            print rec
            start = pos + len(phrase)
woooee 814 Nearly a Posting Maven

What type of objects does the query return? You may have to convert to a list to access it in this way.

query = db.GqlQuery("SELECT *" .....etc.
print type(query)
ctr = 0
for q in query:
    if ctr < 2:
        print type(q)
    ctr += 1
woooee 814 Nearly a Posting Maven

Inside this Class, there is another Class

Why is this necessary. Everything should be in functions inside a single class, or two classes with one calling an instance of the other.

TclError: image "pyimage8" doesn't exist

You are probably looking in the wrong directory. Use the absolute directory + file name for the image = /path/to/images/choose.gif

## missing a quote on the following line
photocho = PhotoImage(file=choose.gif")
                self.labelcho = Button(framebu, image= photocho)
                self.labelcho.image = photocho

                ##---------------------------------------------------------------
                ## you can not use grid and pack.  Pick one only
                self.labelcho.pack()
                self.labelcho.grid(row=2, column=0)

Effbot's Photoimage page http://effbot.org/tkinterbook/photoimage.htm

For any more help you will have to post some code.

Ash_Pokemaster commented: Thanks man +0
woooee 814 Nearly a Posting Maven

I don't use regex as a rule and it is not necessary in this case.

found = False
fp = open(fname, 'r')
for num, line in enumerate(fp):
    line = line.strip()
    if line.startswith(search_term):
        found = True
    if found:
        print num, line
fp.close()

and a number of lines before and after the search term

To do this, you will have to process the file twice, the first time to count the total number of records (so you can print the number of recs after the search term), and process a second time and print the info.

woooee 814 Nearly a Posting Maven

One thing, you can not open a directory, so you should test that it is a file.

import os
a = []
a = os.listdir('.')
for t in a:
    if os.path.isfile(t):
        f = open(t,'r')
        print t, "opened"
        f.close()
    else:
        print "     ", t, "not a file"

Also, if you are not using Idle for writing code, http://www.annedawson.net/Python_Editor_IDLE.htm that is the editor/IDE that you want to start with. You can choose from several other options once you know what you want in an IDE.

woooee 814 Nearly a Posting Maven
if option==3:
        active<>"on"

This will print "True" if active != 'on' and print "False" otherwise. <> has been deprecated so use "!=" instead. I think you want

if option==3:
        active = "off"

Also you can simplify the following code.

if option<>1 or option<>2 or option<>3:
        ondamenu()
##
## can also be written as
    if option not in (1, 2, 3):
        ondamenu()
woooee 814 Nearly a Posting Maven

effbot's tutorial turns up as the first hit for a Google of "tkinter scrollbars". Since we don't know what you want to attach it to, effbot would be the place to start. This is effbot's code for a canvas widget as an example.

from Tkinter import *

root = Tk()
frame = Frame(root, bd=2, relief=SUNKEN)

frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)

xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=E+W)

yscrollbar = Scrollbar(frame)
yscrollbar.grid(row=0, column=1, sticky=N+S)

canvas = Canvas(frame, bd=0,
                xscrollcommand=xscrollbar.set,
                yscrollcommand=yscrollbar.set)

canvas.grid(row=0, column=0, sticky=N+S+E+W)

xscrollbar.config(command=canvas.xview)
yscrollbar.config(command=canvas.yview)

frame.pack()

root.mainloop()
woooee 814 Nearly a Posting Maven

It would generally be something in this ballpark

file_pointer = open("Handylist.csv", "r")

name_in = raw_input("Enter the name")
for rec in file_pointer:
    substrs = rec.split()
    name = substrs[x]   ## don't know where this is
    if name == name_in:
        print("%s Found" % (name))
woooee 814 Nearly a Posting Maven

Just read it, line by line, as a normal file, unless it is not a text file, in which case you would have to read and convert to text. See 2.4.5 here http://www.rexx.com/~dkuhlman/python_101/python_101.html#SECTION004450000000000000000

woooee 814 Nearly a Posting Maven

It's pretty straight forward, and since I'm sick and not doing much today...

test_data = [ "c The random seed used to shuffle this instance was seed=1755086696",
              "p cnf 1200 4919",
              "-35 491 -1180 0",
              "479 1074 -949 0",
              "609 1177 -67 0" ]

formula = []
for rec in test_data:
   rec=rec.strip()
   junk_list = []

   ## record has to start with a number or a minus sign
   if (rec[0].isdigit()) or (rec[0].startswith("-")):
      substrs = rec.split()
      for num in substrs:
         try:
            num_int = int(num)
            if num_int < 0:
               junk_list.append( (abs(num_int), 0) )
            elif num_int > 0:         ## eliminate zero
               junk_list.append( (num_int, 1) )
         except:
            print "error converting", rec

      formula.append(junk_list)
print formula
jmark13 commented: Fast and accurate code. Thanks! +1
woooee 814 Nearly a Posting Maven

The first two posts found in a search of this forum, after your post which is the first/latest, have working solutions that you should be able to adapt.

woooee 814 Nearly a Posting Maven

A quick example of a spiral using deque. It still has a few problems (works best with a square and prints too many) but shows the general concept.

from collections import deque

##========================================================================
def print_spiral( total_cols, total_rows ) :
   d_list = []  ## hold pointers to separate deque objects
   for j in range( 0, total_rows ) :
      d_list.append( deque( ) )

   ##  find center square
   this_row = total_rows / 2
   d_list[this_row].append( 1 )

   num_ctr = 1   ## the number to print
   incr = 1      ## 1 for first 10, 2 for second 10, etc
   num_cols = 1  ## number of columns to print for this row for this pass
   stop = total_rows
   x_dir = True  ## True  = + direction (right for x, down for y)
   y_dir = True  ## False = - direction (left for x, up for y)

   for j in range( 0, total_rows ) :
      x_dir = not x_dir

      ## for this row, increment the number and add to each column
      ## in this row, either left to right, or right to left
      for k in range( 0, num_cols ) :
         num_ctr += incr
         if incr <= total_rows :
            if x_dir == True :
               d_list[this_row].append( num_ctr )
            else :
               d_list[this_row].appendleft( num_ctr )

      ## increment the number and add one to row, or subtract one
      ## depending on the direction
      y_dir = not y_dir
      for k in range( 0, num_cols ) :
         num_ctr += incr
         if incr <= total_rows  :
            if y_dir == True :
               if this_row …
woooee 814 Nearly a Posting Maven

It is easier to code than to explain. This will only work if you use a fixed width font. A proportional font would require more work. It is a little bit tricky in that you want to print one sub-list based upon the "b" in the previous sub_list. I have chosen to look for "b" in this sub-list and print the next sub_list. Note that "list" is a reserved word in Python and should not be used as a variable name.

a = 'a'
b = 'b'
c = 'c'
d = 'd'
X = 'X'
lst = [[a, b, c, d],[a, X, X, b, c, d],[a, X, X, b, c, d],[a, b, c, d]]
spaces = ""
print "".join(lst[0])
## only process through the next to the last sub-list
## since we print the next sub-list
for ctr in range(0, len(lst)-1):
   sub_lst = lst[ctr]
   w_ctr = 0
   ##  look at each letter
   while (sub_lst[w_ctr] != b) and (w_ctr < len(sub_lst)):
      spaces += " "
      w_ctr += 1
   ##  prints the second through the last sub-list with spaces
   ##  from this list prepended
   print spaces + "".join(lst[ctr+1])
woooee 814 Nearly a Posting Maven
if "EMERGENCY" or "Help" or "!" in heading:
   pass
elif ("no idea" in body) or (not Code() in body):
   pass
lllllIllIlllI commented: Like the only original poster in the thread :S +2
woooee 814 Nearly a Posting Maven

I think you could check for a number in the second position, if I understand correctly that overlays use numbers and updates/adds use a letter.

if len(line.strip()) and \
   not line.startswith("Found") and \
   not line[1].isdigit():
pizte commented: Clear and concise. Self explainable. +0
woooee 814 Nearly a Posting Maven

So i searched the sys.path for 2.6 and included
usr/lib/python2.6/dist-packages
in python3 sys.path

So you are obviously using PyQT4 built for Python 2.6. The error message confirms it.

undefined symbol: PyString_FromString

Ask how to install PyQT for both 2.6 and 3.x on the Ubuntu or PyQt forum. Some one has done this and if there isn't anything in the repositories then there is probably a deb package that someone has made. Otherwise you will have to build from source against Python 3.x The good news is that if you screw up things, you can just re-install PyQT and get back to where you are now.

woooee 814 Nearly a Posting Maven

Python does not have static variables, but does have global variables, which those are not. They are class objects and would be called using
Atom.cartesian
both inside and outside the class. In this simple example, note that cartesian belongs to the class and not the instance of the class:

class Atom:

    cartesian = 1

    def __init__(self):
        self.atom_name = "atom name"

    def print_cartesian(self):
        print "cartesian =", Atom.cartesian

print Atom.cartesian  ## --> 1
try:
    print Atom.atom_name  ## AttributeError: class Atom has no attribute 'atom_name'
except:
    print

Atom.cartesian += 1
x = Atom()
print Atom.cartesian
print x.atom_name
x.print_cartesian()
woooee 814 Nearly a Posting Maven

You have both class instances and class objects. The variables
cartesian = dict()
bondList = list()
atomName = str()
atomicNum = int()
would point to the same variable (block of memory) for all instances of the class, where
self.atomName = name
self.atomicNum = atNum
are unique for each instance of the class (point to a separate block of memory for a separate class instance). I think you want the latter so your code would change for "bondList" and the other variables.

class Atom:
    def __init__(self,name, atNum):
        self.atomName = name
        self.atomicNum = atNum
        self.bondList = []

    def addBondedAtom(Atom):
        self.bondList.append(Atom)

You might also take a look at the style guide for variable name conventions http://www.python.org/dev/peps/pep-0008/

jorgejch commented: Clear, didactic and solved the issue. +0
woooee 814 Nearly a Posting Maven

It's Christmas madness already. In 1999, the United States Postal Service issued a Slinky postage stamp (the spring toy that slinks down the stairs). In 2001, House Bill No.1893 of the 2001 Session of the General Assembly of Pennsylvania made Slinky the Official State Toy of Pennsylvania. Carried by communications soldiers in Vietnam, Slinky was tossed over a high tree branch as a makeshift radio antenna. Slinky was incorporated into a spring device used to pick pecans from trees. Over 300 million Slinkys have been sold.

woooee 814 Nearly a Posting Maven

You should use this with a try/except (within is while) since anyone would enter more or fewer characters at some time.

woooee 814 Nearly a Posting Maven

There are several online pages to do that.
http://primes.utm.edu/curios/includes/primetest.php
is one found on this very good page
http://primes.utm.edu/

Your program works correctly, at least for the range you tested.

woooee 814 Nearly a Posting Maven

Google came up with this site which has a link to download source code. I hope you didn't pay $99.95 for the book! http://www.jbpub.com/catalog/9780763746025/

woooee 814 Nearly a Posting Maven

You can set the encoding for the file
fp = codecs.open('test', encoding='utf-8', mode='w')

Or you can change the default encoding for the system
sys.setdefaultencoding('utf-8')

You may have to use encode/decode, see here
http://farmdev.com/talks/unicode/

Gribouillis commented: useful info +2
woooee 814 Nearly a Posting Maven

Using for() loops is easier. This is somewhat of a brute force method but works fine for smaller lists.

L1=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
L2=[1,2,3,4,11]
L3=[]

for number in L2:
    for a_list in L1:
        if (number in a_list) and (a_list not in L3):
            L3.append(a_list)
print L3 
##
##   You can also delete from the list of lists as you add it
##   to L3 so you don't search through it again, but deleting 
##   can cause problems in some cases
print "-" * 50
L1=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
L1_copy = L1[:]
L2=[1,2,3,4,11]
L3=[]
for number in L2:
    for a_list in L1:
        if (number in a_list) and (a_list not in L3):
            L3.append(a_list)
            L1.remove(a_list)
            print "-----> L1 =", L1
print L3
The_Kernel commented: Nice one. Beat me to it, and more cleverly too! +1
woooee 814 Nearly a Posting Maven

Roman to integer. Note that it will take something like XXIXV and convert it. If someone already has a routine to check for valid input, please post it. And I'm afraid we've just eliminated one standard homework question. Oh well, nothing lasts forever.

roman_to_decimal = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, \
                     'D': 500, 'M': 1000 }

roman = raw_input("Enter the roman numeral to convert to arabic: ").upper()

converted = True
arabic = 0
for n in range(0, len(roman)-1):
    this_char = roman[n]
    next_char = roman[n+1]
    if (this_char in roman_to_decimal) and \
       (next_char in roman_to_decimal):

        this_number = roman_to_decimal[this_char]
        next_number =  roman_to_decimal[next_char]
        print "converting %s to %d....." % (this_char, this_number),
        if this_number < next_number:
            arabic -= this_number
        else:
            arabic += this_number
        print "Total now =", arabic

    else:
        print "\nthis chr (%s) or next chr (%s) is not a valid roman numeral" \
              % (this_char, next_char)
        converted = False
        break

if converted:
    ##  add last roman numeral
    arabic += roman_to_decimal[roman[len(roman)-1]]

    print "\nThe roman numeral", roman, "is equal to",arabic
woooee 814 Nearly a Posting Maven

Dictionaries are indexed via a hash and so make it easy to look up things, in this case the stock symbol, without going through the sub-strings in each list. Also, they provide a convenient way to validate the data entered. In this example, "while rmv not in pf_dict:" will keep asking for an entry until one is entered that is in the dictionary. A simple example using the stock symbol as key, and a list with all of the other data as the item associated with the key.

stock1 = ["Google","GOOG", 100, 24.00, 21.98]
stock2 = ["Microsoft", "MCST", 300, 56.00, 54.00]
stock3 = ["Yahoo", "YHOO", 90, 20.00, 14.00]
stock4 = ["Apple", "AAPL", 289, 50.00, 46.99]

## assume the four lists were entered into a dictionary instead
pf_dict = {}
## indexed on symbol
for stock in [stock1, stock2, stock3, stock4 ]:
    pf_dict[stock[1]] = [stock[0], stock[2], stock[3]]
    print stock[1], pf_dict[stock[1]]

stChoice = 2
if stChoice == 2:
    rmv = ""
    while rmv not in pf_dict:
        print
        for key in pf_dict.keys():
            print "symbol = %s for %s" % (key, pf_dict[key][0])

        rmv = raw_input("Type in the ticker name for the stock you wish to remove. ")
        rmv = rmv.upper()
        if rmv not in pf_dict:
            print rmv, "is not a valid symbol"

    ##   valid symbol entered
    del pf_dict[rmv]
    print "\n", rmv, "deleted\n"
    print pf_dict

Would somebody explain to me the stock_list and how it's working. I'm kind of confused because stock_list wasn't defined

for stock_list in portfolio:
        print "stock_list =", stock_list
# …
woooee 814 Nearly a Posting Maven

return an error message if the values entered aren't either the strings 'on' or 'off'

Can you use a list instead of all of those variables? Otherwise, try the code below which tests each button individually instead of the confusing and, and, or, etc. in your code. Speaking of testing each button individually, it would be better to test each one as it is entered.

error_switch = False
for button in [b1, b2, b3, b4]:
    button = button.lower()
    if button != 'on' and button != 'off':
        error_switch = True
if error_switch:
    print 'You must enter either "on" or "off" for the button states.'

Edit: Do you know how and why
for button in [ b1, b2, b3, b4]:
works? Post any ideas. You can not really use anything like this unless you understand it.

woooee 814 Nearly a Posting Maven

You would have to step through the unicode and count the number of actual letters, and then add enough spaces to the string to make it the length you want. This appears to work, but you'll have to test for yourself.

def print_rec(rec):
   print rec
   substrs = rec.split()
   greek_str = " ".join(substrs[1:])
   num_chr = 0
   for chr in greek_str:
      print ord(chr),
      if ord(chr) not in [206, 207]:
         num_chr += 1

   print "\n", num_chr


fp = open("./origDict.txt", "r")
## skip heading
fp.readline()

print_rec(fp.readline())
print_rec(fp.readline())
print_rec(fp.readline())
chico2009 commented: of great assistance, thanks +1
woooee 814 Nearly a Posting Maven

That's not a good example to copy (although the book ultimately solves that problem if memory serves.). Find one using the canvas widget as it uses a top left corner (x,y) and a bottom right corner. A starting point
http://effbot.org/tkinterbook/canvas.htm
http://infohost.nmt.edu/tcc/help/pubs/tkinter/create_rectangle.html

woooee 814 Nearly a Posting Maven

You would generally use a for loop to iterate through a list. I'm creating one output string, but you could also print within the for loop. Also, please do not use "i", "l" or "o" as single letter variable names as they look too much like numbers.

test_list1 = [1,2,3]
test_list2 =['blah',50]
output_str = "%d" %(test_list1[0])
for n in range(1, len(test_list1)):
    output_str += " isn't %d" % (test_list1[n])
output_str += " which isn't %d" % (test_list2[1])
print(output_str)
woooee 814 Nearly a Posting Maven

so how would I get it to print Odd

def isOdd(n):
    if firstNum % 2 == 0:
        return False
    else:
        return True

for num in range( 97, 100 ):
    is_odd_returned = isOdd(num)
    print num, "is",
    if is_odd_returned == True:  ## or just if is_odd_returned:
        print "Odd"
    else:    ## "False' returned
        print "Not odd"
woooee 814 Nearly a Posting Maven

could anyone help me find out the error in my isPrime() function

You get a return on the first pass through the for() loop. A True if the first divide has a remainder, a False if the first divide has no remainder. You want the True after the for() loop, not within it.

def isPrime(n):
    if n == 2:
        return True
    for divisor in range(3, int(math.sqrt(n)), 2):
        if n % divisor == 0:
            return False

    ## did not return 'False' during the for() loop so it is prime
    return True

And this code will never print "Deficient". I'll let you figure out why.

def checkForPerfect(n):
 
    sum = 0
 
    if n %  == 0:
        sum +=
    if sum == n:
        return 'Perfect'
    elif sum > n:
        return 'Abundant'
    else:
        return 'Abundant'
    else:
        return 'Deficient'
woooee 814 Nearly a Posting Maven

I've added some print statements to give a hint about what is being processed

number_of_courses = input ('Number of course to enter... ')

for number_of_courses in range (0, number_of_courses):
    major = raw_input('\nEnter class type ') #cmsc, math, etc..
    coursenum = input('Enter course number ')
    print "input was", major, coursenum

print ("\nA Requirements") #for cmsc
print "comparing", major, coursenum

##-------------  my test  ---------------------------------------
Number of course to enter... 3

Enter class type csmc
Enter course number 101
input was csmc 101

Enter class type math
Enter course number 201
input was math 201

Enter class type junk
Enter course number 301
input was junk 301

A Requirements
comparing junk 301

there must be an easier way to do this than using a million if statements.

Start with a dictionary to store the requirements, etc. which you can then use to look up classes taken. What is left over is what they have yet to take.

woooee 814 Nearly a Posting Maven

A dictionary with the letter as the key is the straight forward way to do this. Otherwise use a function with a for loop to pass the letter and the string to the function.

import string

letter_dict = {}
for letter in string.ascii_uppercase:
    letter_dict[letter] = 0

f = [ "abc def\n",
      "ghi abc def\n",
      "mno stuvw abc\n" ]

for line in f:
   for word in line.strip().split():
      letter = word[0].upper()
      letter_dict[letter] += 1

for letter in string.ascii_uppercase:
    print "letter %s = %d" % (letter, letter_dict[letter])
vegaseat commented: very helpful +16
woooee 814 Nearly a Posting Maven

Your problem is here

for n in range(num_iterations):
        print "n before =", n
        n = B*10
        print "n after  =", n

You use "n" twice and are always multiplying the same number, "B". Something like this should give you the idea of how to go about it. Also, I've introduced divmod which is just another way to get the whole integer and the remainder (not decimal). Your main problem is that you haven't tried including print statements to see what is happening, so can not tell that you are getting the remainder as an integer and not as a float/decimal.

def rationalnum(n, d, num_iterations):
    whole, remain = divmod(n, d)
    print "divmod =", whole, remain
    print "% =", n%d, n, d

    ## convert to decimal
    dec = float(remain) / d
    print "dec =", dec

    ##---  you could also use this to convert
    number = float(n) / d
    number_int = int(number)
    number_decimal = number - number_int

    for n in range(num_iterations):
        dec *= 10
        print dec

    print "\nthe decimal multiplied %d times = %d\n" % \
             (num_iterations, int(dec))
 
def main():
    num = input('Please Enter a numerator to the rational number: ')
    denom = input('Please Enter a denominator to the rational number: ')
    num_iterations = input('Please Enter a number of decimal places to show: ')
    rationalnum(num, denom, num_iterations)

main()

Finally, there is no reason to have the main() function, with one orphaned statement that calls it, unless you want to call it from another program, in which case it should be named …

woooee 814 Nearly a Posting Maven

For exactness, use the decimal class. My take on the program using decimal. Note that decimal.Decimal is imported as "dec" to avoid confusion with the variable names. Also, I am not a decimal class expert and so use divmod to get the integer and remainder/decimal portions of a number. There are probably other ways, some of which may be better. Finally, using the decimal class is much slower than floats but is not noticeable for the normal type operations.

from decimal import Decimal as dec

def extractDecimals(num):
   """ the variable 'num' is expected to be a decimal.Decimal
   """
   try:
      whole, remainder = divmod(num, 1)
      print "whole =", whole, "  remainder =", remainder
      if remainder > 0:
         decimals = num - whole
         ctr = 0
         while (decimals > whole) and (ctr < 100):
            ctr += 1
            decimals *= 10
            whole, remainder = divmod(decimals, 1)
            print 'decimal: ' + str(decimals),
            print '     int: ' + str(whole)
         return int(decimals)
      else:
         raise DecimalError(num)
   except DecimalError, e:
      e.printErrorMessage()

extractDecimals(dec("0.988"))
sneekula commented: good point +8
woooee 814 Nearly a Posting Maven

There is an error on this line, no colon
for line in objconfigfile.readlines()

I would suggest that you print every line because
if line == None:
will probably never be true, but you will have to print it and see. Also, exec(line) expects "line" to be a valid python statement.

sneekula commented: good comment +8
woooee 814 Nearly a Posting Maven

For future coding conundrums, an "or" can be viewed as an if / elif, and "and" can be viewed as two nested if statements, which you would adapt to while() statements.

while overwrite != 'Y'.lower() or overwrite != 'N'.lower():  becomes
if overwrite != 'Y'.lower():
    do something
elif overwrite != 'N'.lower():
    do the same thing

For completeness, the 'and' would be
if overwrite != 'Y'.lower() and overwrite != 'N'.lower():  becomes
if overwrite != 'Y'.lower():
    if overwrite != 'N'.lower():
       do something

Hopefully this will help sort out the and/or's in the future.

nunos commented: very good post. explained in great detail. +1
woooee 814 Nearly a Posting Maven

My attempt. Once again, if not correct, post back with more info. The trick (I think) is to split each string on the "\n" to create individual rows, and is similiar to Gribouillis' solution but doesn't use list comprehension (which is an amazing tool). It instead uses a dictionary with row number as the key, in this case 0 through 4, and appends each row to the corresponding key. Finally, the joined rows are spaced and printed. Hopefully, using a dictionary with the row number is easy to understand.

def join_letters( letter_list, base_dict ):
   combined_rows_dict = {}

   ##---  base length to test for equality
   len_letter = len(base_dict[letter_list[0]])

   for j in range(0, len(letter_list)):
      this_letter = letter_list[j]

      ##--- all letters must be in the dictionary
      if this_letter not in base_dict:
         print "letter %s not in base_dict" % (this_letter)
         return "***"

      ##--- test for all translations are equal in length
      if len(base_dict[this_letter]) != len_letter:
         print "unequal letter lengths", len_letter, len(base_dict[this_letter])
         return "***"

      ##--- convert triple quote string into rows in a list
      string_list = base_dict[this_letter].split("\n")
      print "string_list", string_list

      ##---  append each row to the corresponding dictionary key
      for row in range(0, len(string_list)):
         if row not in combined_rows_dict:
            combined_rows_dict[row] = []
         combined_rows_dict[row].append(string_list[row])

   print
   for row in range(0, len(combined_rows_dict)):
      this_row = combined_rows_dict[row]
      print " ".join(this_row)
   return "Success"

base_dict = {}
base_dict["A"] = """X 0 X X
0 X 0 X
0 0 0 X
0 X 0 X
0 X 0 X"""

base_dict["B"] = """0 0 X X
0 X 0 X
0 0 …
Gribouillis commented: You're the best teacher in forum 114 ! +4
woooee 814 Nearly a Posting Maven

2. Is there any way to convert it to read only? Normally the user is able to modify the text but I want it to be read only.

Use the codebox
"Display some text in a monospaced font, with no line wrapping.
This function is suitable for displaying code and text that is
formatted using spaces.

The text parameter should be a string, or a list or tuple of lines to be
displayed in the textbox."
http://easygui.sourceforge.net/current_version/pydoc/easygui.html#-codebox

So you can send a list of lines to be printed. Sweet.

vegaseat commented: nice find +13
woooee 814 Nearly a Posting Maven

You use a StringVar and include the function in the class. Here is a simple example. Note that the same StringVar is used for the second label and the entry box. Take a look at this page http://infohost.nmt.edu/tcc/help/pubs/tkinter/control-variables.html

import Tkinter

class EntryTest:
   def __init__(self):
      self.top = Tkinter.Tk()

      self.str_1 = Tkinter.StringVar()
      label_lit = Tkinter.StringVar()

      label_1 = Tkinter.Label(self.top, textvariable = label_lit )
      label_1.pack()
      label_lit.set( "Test of Label")
    
      label_2 = Tkinter.Label(self.top, textvariable = self.str_1 )
      label_2.pack()

      entry_1 = Tkinter.Entry(self.top, textvariable=self.str_1)
      entry_1.pack()
      self.str_1.set( "Entry Initial Value" )

      cont = Tkinter.Button(self.top, text='PRINT CONTENTS',
             command=self.getit, bg='blue', fg='white' )
      cont.pack(fill=Tkinter.X, expand=1)

      exit=  Tkinter.Button(self.top, text='EXIT',
             command=self.top.quit, bg='red', fg='white' )
      exit.pack(fill=Tkinter.X, expand=1)

      entry_1.focus_set()
      self.top.mainloop()


   ##-----------------------------------------------------------------
   def getit(self) :
      print "getit: variable passed is", self.str_1.get()

##===============================================================

if "__main__" == __name__  :
   ET=EntryTest()
vegaseat commented: right on +12
woooee 814 Nearly a Posting Maven

You can do this two different ways.

items = {'sword':['sword', 3, 15],
             'axe':['axe', 5, 25],
             'bow and arrow':['bow and arrow', 4, 20]}

##---- the easiest to understand
for key in items:
   print "key =", key
   weapon_list = items[key]
   print "\tweapon_list =", weapon_list
   print "\tprice =", weapon_list[1]
   print "\tdamage =", weapon_list[2]
   
##--- the way you tried to do it
for key in items:
   print items[key][0]
   print '\tprice:', items[key][1]
   print '\tdamage:', items[key][2]
Ene Uran commented: good explanation +7
woooee 814 Nearly a Posting Maven

That works just fine. Being paranoid, I like to supply defaults. Using a class works fine until it becomes too cumbersome or you want a better way of looking things up, then you move up to using an SqLite DB in memory.

class MyClass:
	def __init__(self, f=" ", r=[]):
		self.first = f
		self.rest = r

if __name__ == "__main__":
   list_of_classes = []
   list_of_classes.append(MyClass())
   list_of_classes.append(MyClass("x", ["a", "b"]))
   print "----->", list_of_classes[1].first
   print "----->", list_of_classes[0].rest
woooee 814 Nearly a Posting Maven

Yes that should have been one to get the next value. A good example of why we don't use "i".

vegaseat commented: good example +12