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

That's called string formatting http://www.python.org/doc/2.5.2/lib/typesseq-strings.html (assuming you are using Python 2.5). A simple example:

year = 1
pop = 12345
for x in range(2):
    print "Year %d population = %d" % (year, pop)
    year += 1
    pop += 12345
woooee 814 Nearly a Posting Maven

Agreed. You should do your own research from here. Especially since you are just going to forget most of this anyway. Herb Schildt was the consensus guru when this was commonly done, so if you can find a copy of "The Craft of C" online or in a library, it will explain what it takes to write the program. Bottom line is that somewhere, for every OS, you have to have something that puts pixels on the screen via a program, for every video card, monitor, etc. The precise details are left up to you.

woooee 814 Nearly a Posting Maven

If you wanted to draw a box on the screen and display some sort of message, you would have to access the memory on the video card. Before toolkits like Tkinter that is the way it was done. In simple terms, you would copy that part of the screen, blank it by putting whatever color you wanted to use, draw the outline of the box with another color, add any other color effects you wanted to use, and then display the message. When finished, you would copy back the original contents of the window. Every one who did programming had these routines in their toolbox, although C, not Python was the language of choice. Today, I don't think Python has the capability as that requires a little assembly code, so the programming language has to be able to execute some assembly.

woooee 814 Nearly a Posting Maven

Try this and then go to the page from the earlier link which explains why you returned a tuple.

def junk(f):
    d1 = {}
    d2 = {}
    for line in f:
        columns = line.split(":")
        letters = columns[1]
        numbers = columns[2]
        d1[letters] = numbers
        d2[numbers] = letters
    return d1, d2

if __name__ == "__main__":
    f = open("filename.txt")
    d1_ret, d2_ret = junk(f)[0]
    print type(d1_ret)
woooee 814 Nearly a Posting Maven

First you are not returning a dictionary. I've added a print statement to show that. Also, take a look at "returns" and "arguments" here http://www.penzilla.net/tutorials/python/functions/ for the "something" function.

def junk(f):
    d1 = {}
    d2 = {}
    for line in f:
        columns = line.split(":")
        letters = columns[1]
        numbers = columns[2]
        d1[letters] = numbers
        d2[numbers] = letters
    return (d1, d2)
 
 
def something():  
    print d1
    print d2
 
if __name__ == "__main__":
    f = open("filename.txt")
    d1 = junk(f)[0]
    print "type d1 =", type(d1)
    d2 = junk(f)[1]
woooee 814 Nearly a Posting Maven

It is generally done with a list.

def test_input(input_str):
   accept_list = []
   for x in range(0, 10):
      accept_list.append(str(x))
   accept_list.append("d")
   accept_list.append("r")

   for character in input_str:
      if character not in accept_list:
         return False

   return True
#
#  test it
input_string = "a"
print input_string, test_input(input_string)
input_string = "3A3"
print input_string,  test_input(input_string)
input_string = "9d3"
print input_string,  test_input(input_string)
woooee 814 Nearly a Posting Maven

It should be simple with Python's gstreamer interface. http://pygstdocs.berlios.de/

woooee 814 Nearly a Posting Maven

The get an error when i try to execute this?

Not enough info for anyone to help (could be an indentation error, or could be in the calcs). First add some print statements for the individual calcs to isolate the error, and post the specific error message.

def distance_between_points(p1, p2):
   p2subp1 = p2-p1
   p1subp2 = p1-p2
   print "after subtraction", p2subp1, p1subp2
   ## one print for each step

point_1 = (1, 2)
point_2 = (4, 6)
distance_between_points(point_1, point_2)
woooee 814 Nearly a Posting Maven
finderGuess = finderGuess - ((((finderGuess*((1+finderGuess)^numberMonths))/(((1+finderGuess)^numberMonths)-1))-
          (monthlyPayment/loanAmount))/(((((1+finderGuess)^numberMonths)-1)
          (finderguess*(numberMonths*((1+finderGuess)^(numberMonths-1)))+
          (1+finderGuess)^((finderGuess*(1+finderGuess)^numberMonths)*
          (numberMonths*((1+finderGuess)^(numberMonths-1)))))/
((((1+finderGuess)^numberMonths)-1)^2))))

I hope you are the only one who has to deal with this code. It may help to remember that the compiler can only do one thing at a time, unless you have a multi-core machine and an OS that is multi-core aware, which is very unlikely. So, for most of us there is little between one long calculation and several shorter ones, from the compiler's viewpoint. But there is a big difference in terms of readability.

Note the lack of a mathematical symbol between two lines of code as pointed out below. Also, all of your calculations are done as integers. You may or may not want floats instead.

## a calculation common to several other calcs
## increase the guess by one and raise it to the power of the number of months
interim divisor = (1+finderGuess)^numberMonths

## this is the do-hickey which is calculated by
## subtractng one from the thing-ma-bob and raising it to
## the power of 2
last_divisor = interim_divisor - 1
last_divisor = last_divisor^2

"""  note that there is no mathematical symbol between the first and
     second lines in this block of code
(((((1+finderGuess)^numberMonths)-1)
(finderguess*(numberMonths*((1+finderGuess)^(numberMonths-1)))+
(1+finderGuess)^((finderGuess*(1+finderGuess)^numberMonths)*
(numberMonths*((1+finderGuess)^(numberMonths-1)))))
"""

## so the code becomes something like this, making sure that the number are floats, or are converted in the calculations.
finderGuess = finderGuess - descriptive_name_for_numerator /
              descriptive_name_for_first_divisor /
              descriptive_name_for_second_divisor /
              descriptive_name_for_third_divisor /
              last_divisor
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

Also, is there anyway in Python that you can test whether or not a line of data is binary?

All data is binary. That's the way the computer does it. I am assuming that you mean bytes that are not text. If you look at an ASCII table like this one http://www.asciitable.com/ it becomes apparent that for the English character set you want to check for anything less than decimal 32 (space) or greater than decimal 126 (~). Python uses ord(character) to covert and I don't know of any way other than converting and checking every byte in the file. Post some code and we can help you with problems

BTW, thread titles like ...
Can Python do this?
I need help
Help
are meaningless and kind of stupid! Use a tiltle that tells the rest of us what you want.

It takes a large amount of self control not to respond with
Can Python do this? (Who are you, Steve Urkel)
I need help (We all do but most of us can't afford a psychiatrist)
Help (Have you fallen and can't get up?)

woooee 814 Nearly a Posting Maven

Wouldn't this lead to an infinite loop.

def Prime(x,y):
    n=2
    if x == 1:
       Prime(x+1,y)
   elif x == 2:
      print (2)
      Prime(x+1,y)
   elif x <= 0:
      print ("Number must be a positive integer"
   else:
      while n < n+1:     ## <=====
woooee 814 Nearly a Posting Maven

You want to use "readlines()",as readline reads one line at a time, where readlines() reads all data. Also, a print statement is added for clarity.

records = open(grades.txt,'r').readlines()
table = []
newtable = []
for line in records:  
   line = line[:-1]
   r = string.split(line,':')
##   table.append(r)
##  for x in table:           ## x = r so just use r
##   for all in x:
   for all in r:
    print "testing isalpha()", all.isalpha(), all
    if all.isalpha() == 0:
     num = float(all)
    else:
     num = all

##---  get the first part of the program working first
##   t.append(num)
##   newtable.append(tuple(t))
woooee 814 Nearly a Posting Maven

And it's not tough to do.

import Tkinter

root = Tkinter.Tk()
root.title('Canvas')
canvas = Tkinter.Canvas(root, width=450, height=450)

canvas.create_oval(100,50,150,100, fill='gray90')

x = 125
y = 175
stick = canvas.create_line(x, y-75, x, y)

diff_x = 25
stick_leg1 = canvas.create_line(x, y, x-diff_x, y+50)
stick_leg2 = canvas.create_line(x, y, x+diff_x, y+50)

y=145
stick_arm1 = canvas.create_line(x, y, x-30, y-20)
stick_leg2 = canvas.create_line(x, y, x+30, y-10)

canvas.pack()
root.mainloop()

But for some reasn (reason) my code doesnt (doesn't) seem to be working

What version of Python are you using? Make sure you are using an integer for the radius.

def draw_circle():
    x = input("please enter the radius of the circle: ")
    print "the radius is", x, type(x)
    centre= Point(100, 100)
    circle1 = Circle(centre, x)
    circle1.draw(win)
woooee 814 Nearly a Posting Maven

This is very simple to do.

print len(set([1,2,4,2,7]))
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

I thought this path was suppose to be set by default. it's not so i'm trying to set it.

You can modify it on startup by adding PYTHONPATH to your ~/.bash.rc file, or create one if you don't have it.
export PYTHONPATH=$PYTHONPATH:/path/to/add:/second/path

woooee 814 Nearly a Posting Maven

Always use absolute path+file names.

filePath = "Dataset/parameter feature vectors"
for fname in os.listdir(filePath):
    complete_name = os.path.join(filePath, fname)
    data_str = open(complete_name).read()
    index = data_str.find("female")
    if index != -1:
        females.append(index)
        print fname
    else:
        print "append the ones that aren't female to a males"
woooee 814 Nearly a Posting Maven

I still don't understand why not 1 and not 2 and not 3 is the proper way to do this

Alternatives would be:

while (play_choice < 1) or (play_choice > 3):

while play_choice not in [1, 2, 3]:

# Also, you can use .lower instead of 2 compares
while play_again.lower() == 'y'':
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

You can pipe top to a file on Linux and then read the file.

Apparently you can use WMI for MS WIndows but I have not used it http://timgolden.me.uk/python/wmi_cookbook.html#running_processes

woooee 814 Nearly a Posting Maven

Please ass "Solved" to the thread title so no one else wastes their time on this.

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

Doug Hellmann has excellent write ups. http://www.doughellmann.com/PyMOTW/

As far as books go, I like "Dive into Python" http://diveintopython.org/native_data_types/index.html#odbchelper.dict

woooee 814 Nearly a Posting Maven

This will get you started, but a dictionary would work much better for this.

elif stChoice == 2:
    for stock_list in portfolio:
        print "symbol = %s for %s" % (stock_list[1], stock_list[0])

    rmv = raw_input("Type in the ticker name for the stock you wish to remove. ")
    for stock_list in portfolio:
        ticker = stock_list[1]
        if ticker == rmv:
            portfolio.remove(stock_list)
    print portfolio
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

You want to keep all of the sqlite stuff in Database.py and call the add, change, delete functions from the WX program. An example using addition.

import sqlite3
##import addnew

class DBClass:
    def __init__(self):
        #Creating a connection to the database.
        self.connection = sqlite3.connect('contacts.db')

        #Creating a cursor object to interact with the databae
        self.db = self.connection.cursor()

        #creating tables
        self.db.execute("CREATE TABLE IF NOT EXISTS contacts (fname VARCHAR, lname VARCHAR NOT NULL PRIMARY KEY, phonenumber VARCHAR, address VARCHAR, email VARCHAR)")
        self.connection.commit()

    ##................................................................................................
    def __del__(self):
        self.db.close()

    ##................................................................................................
    def add_record(self, add_tuple):
        """ receives a tuple and adds it to the database
            does not do any checking of data, so will add
            duplicate records, or malformed data
            to call this: self.database.add_record(tuple_to_add)
        """
        self.db.execute("insert into contacts (fname, lname, phonenumber, address, email) values (?, ?, ?, ?, ?)", add_tuple)
        self.connection.commit()

    ##................................................................................................
    def print_all(self):
        """ Retrieves all rows as a sequence and prints that sequence:
        """
        self.db.execute("select * from contacts")
        for rec in self.db.fetchall():
            print rec

##====================================================================
## simulate calling this from the wxpython program
##====================================================================
class WXProgram:
    def __init__(self):
        self.database = DBClass()
        f_name = "abc.txt"
        last_name = "Smith"
        phone="555-5555"
        address="123 Main St."
        email="Smith@gmail.com"
        self.database.add_record( (f_name, last_name, phone, address, email) )

        f_name = "def.txt"
        last_name = "Jones"
        phone="555-1111"
        address="345 First St."
        email="Jones@gmail.com"
        to_add = (f_name, last_name, phone, address, email)
        self.database.add_record(to_add)

        print "printing records"
        self.database.print_all()

        ## we don't have to explictly close the class, but it can be
        ## done by assigning self.database some other value
        self.database = None

##====================================================================
if __name__ == "__main__":
   WX=WXProgram()
woooee 814 Nearly a Posting Maven

If you didn't close the database
connection.commit()
db.close()
you sould be able to access it via Database.db from the second program so try substituting that for self.database and see if it works, or just use
self.database = Database.db

woooee 814 Nearly a Posting Maven

It's defined in a external file called Database.py. That is the reason I imported Database at the top. Do you want to see that file. I haven't fixed my problem yet. More help would be greatly appreciated. Thanks!

Post the code. You have to access the variable from the class in Database.py It would roughly be something along the lines of
DB = Database.database() ## create instance of database class
self.database = DB.connection.cursor()

woooee 814 Nearly a Posting Maven

Does anyone know how to change border colour of a widget

Border colors, AFAIK, are the same as the widget color, so you would have to use an outside, empty widget of one color, and an inside widget of another color, although that is not quite what you want. The PMW toolkit extension does have a bordercolor key word but I have never tried it.

woooee 814 Nearly a Posting Maven

self.database.execute('INSERT INTO contacts (fname) VALUES (null,?),' [fname])
AttributeError: 'contact' object has no attribute 'database'

It means that you have not declared "self.database" anywhere in your program, and the interpreter does not know if it is a variable, file pointer, another class, etc.

woooee 814 Nearly a Posting Maven

A Python list will hold something like 2 trillion items, but is going to be pretty slow with a very large number or records in it. If your list is going to be 100 million records or more, then consider an SQLite database instead. If it's a paltry one million records (we now live in a gigabyte world), then there should not be a problem, but you might want to consider using a dictionary or set as they are both indexed via a hash and would be much faster on lookups.

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

but i am interested multi process

This is an example of multiprocessing/pyprocessing running 2 threads and passing variables back and forth via a dictionary.

import time
from multiprocessing import Process, Manager

def test_f(test_d):
   """  frist process to run
        exit this process when dictionary's 'QUIT' == True
   """
   test_d['2'] = 2     ## change to test this
   while not test_d["QUIT"]:
      print "test_f", test_d["QUIT"]
      test_d["ctr"] += 1
      time.sleep(1.0)

def test_f2(name):
    """ second process to run.  Runs until the for loop exits
   """
    for j in range(0, 10):
       print name, j
       time.sleep(0.5)

    print "second process finished"
    
if __name__ == '__main__':
   ##--- create a dictionary via Manager
   manager = Manager()
   test_d = manager.dict()
   test_d["ctr"] = 0
   test_d["QUIT"] = False
   
   ##---  start first process and send dictionary
   p = Process(target=test_f, args=(test_d,))
   p.start()
   
   ##--- start second process
   p2 = Process(target=test_f2, args=('P2',))
   p2.start()

   ##--- sleep 2 seconds and then change dictionary
   ##     to exit first process
   time.sleep(2.0)
   print "\nterminate first process"
   test_d["QUIT"] = True
   print "test_d changed"
   print "data from first process", test_d

   ##---  may not be necessary, but I always terminate to be sure
   time.sleep(5.0)     ## let 2nd process finish
   p.terminate()
   p2.terminate()
woooee 814 Nearly a Posting Maven

Is there some way I can display the 'escape characters'

Escape characters are generally < decimal 32 and > decimal 127 (in English), but you may have to adjust for your character set. This works for me.

# -*- coding: utf-8 -*-

test_file = [ "about, approximately περίπου cinema σινεμά (το)", \
              "after μετά cinema σινεμά/κινηματογράφος", \
              "afternoon απόγευμα (το) city πόλη (η)" ]

escape_min = 32
escape_max = 127
for rec in test_file:
   printed = 0
   for num, character in enumerate(rec):
      ord_chr = ord(character)
      if (ord_chr < escape_min) or (ord_chr > escape_max):
         if not printed:
            print "\n", rec
            printed = 1
         print "     ", num, ord_chr
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

Some ideas. First, tkinter does not display all image types. I do not think that it will display a JPG but am not sure. Convert some pictures to a gif and see it that works. Second, "file" is a reserved word and so should not be a variable name, Third, you are not iterating through the entire list of files because of the delete in the for loop. Append the names you want to keep to a second list. Also, you don't have to create a list of n elements, just append as you go along (see below). Finally, if you don't know about effbot, it is a good reference. http://effbot.org/tkinterbook/label.htm

label_list = []
for k, fname in enumerate(files):
    image = Image.open(filedir+"/"+fname)
    ##((width, height))
    image.thumbnail((160, 240))
    photo = ImageTk.PhotoImage(image)
    this_label = Label(root, image=photo) 
    this_label.pack()  # pack when you want to display it
    label_list.append( this_label )
picSet.mainloop()
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

Use a dictionary to store the class instances.

class ClassTest :
   def __init__ (self, desc2="***") :
      self.field1 = "*"
      self.field2 = 0
      self.field3 = desc2

   def chg_field1(self, value):
      self.field1 = value


#==========================================================================
class_dict = {}
class_dict[1]=ClassTest("First Class")
class_dict[2]=ClassTest()
for key in class_dict:
   print "%d  %15s, %3d, %s" % (key, class_dict[key].field1, \
          class_dict[key].field2, class_dict[key].field3)
print

class_dict[2].field2=99
class_dict[1].chg_field1("Field 1 changed")
for key in class_dict:
   print "%d  %15s, %3d, %s" % (key, class_dict[key].field1, \
          class_dict[key].field2, class_dict[key].field3)
woooee 814 Nearly a Posting Maven

The question is not clear, so let us say
if number_list = [1,2,3,4,5,6,7,8,9]
3 = maximum numbers that can be combined
(and single numbers are not included),
then you would use a function to calculate the sum of a group of numbers and return True or False
def return_sum(number_list, compare_to):

and would use a for loop(s) to group the numbers, that is, send groups of 2, 3, etc to the function for comparison. Start with the individual parts. Use a loop to divide the list into groups, send each one to the function, and do something with the result.

woooee 814 Nearly a Posting Maven

Concerning your original code, you declare ind1 and ind2 beneath the if (), so keep them there

#-----------------------------------------------
if user_in in users:
   users = list(users)
   passw = list(passw)
   ind1 = users.index(user_in)
   ind2 = passw.index(passw_in)
   users = tuple(users)
   passw = tuple(passw)
 
   ## but if neither user name or password is found, 
   ## then ind1 == ind2 == -1
   if (ind1 > -1) and (ind1 == ind2):
      print('Match')
   else:
      print('Not Match')

I would think though that the point here is not to convert back and forth from lists, but to use a for() loop to iterate through the tuple(s). You can do this two ways, (1) use a separate tuple for name and password, or (2) use a nested tuple of tuples containing both name and password, It doesn't really matter which one you choose.

#----------------------------
def user_passw_1tuple(users_and_passw):
    user_in = raw_input('Username? ')
    user_in = user_in.strip()
    for ctr in range(0, len(users)):
        if user_in == users_and_passw[ctr][0]:
            passw_in = raw_input('Password? ')
            if passw_in == users_and_passw[ctr][1]:
                return True
    return False

#----------------------------
def user_passw_2tuples(users, passw):
    user_in = raw_input('Username? ')
    user_in = user_in.strip()
    for ctr in range(0, len(users)):
        if user_in == users[ctr]:
            passw_in = raw_input('Password? ')
            if passw_in == passw[ctr]:
                return True
    return False


##-------------------------------------------------------------------------------
users =  ('user1','user2','user3')
passw = ('pass1','pass2','pass3')

users_passw = (('user1', 'pass1'), ('user2', 'pass2'),
               ('user3', 'pass3'))

result = user_passw_1tuple(users_passw)
if result:
   print("Match for '1tuple'\n")
else:
    print("No Match for '1tuple'\n")

result = user_passw_2tuples(users, passw)
if result:
   print("\nMatch for '2tuples'")
else:
    print("\nNo Match for '2tuples'")

You will now have to come up with a function …

woooee 814 Nearly a Posting Maven

Run this code with some added print statements and see if it helps.

for i in range(n):
        y = input("Enter number: ")
        print "after input y =", y
        y = y + y
        print "after adding y =", y, "\n"
woooee 814 Nearly a Posting Maven

Note that you have a similar problem with the arithmetic. In the first function you subtract 32 from t and multiply by 5/9. In c2f you multiply t by 9/5 and then add 32. Perhaps this is the correct way to do it and I'm wrong, in which case appologies to the OP. I just use 9C + 160 = 5F for both conversions and solve for the unknown variable.

def f2c(t):
    """given t Fahrenheit return Celsius"""
    return 5/9.0 * (t - 32)
 
def c2f(t):
    """given t Celsius return Fahrenheit"""
    return 9/5.0 * t + 32
woooee 814 Nearly a Posting Maven

Defining and then calling the functions under the if() statements serves no purpose. Stripped to the minimum, it would be:

#Convert C to F
if x == 1:
    Tc = input ("What is the Celsius Temperature ?   " )
    print 'The temperature is %.2f Degrees Fahrenheit' % \
             (9.0/5.0 * Tc + 32 )

And generally, it would be more along the lines of this to avoid a double compare on "x", although there is nothing wrong with the way you did it.

def Tc_to_Tf ():        
    Tc = input ("What is the Celsius Temperature ?   " )
    print 'The temperature is %.2f Degrees Fahrenheit' %(9.0/5.0 * Tc + 32 )

def Tf_to_Tc ():
    Tf = input ("What is the Fahrenheit Temperature ?   " )
    print 'The temperature is %.2f Degrees Celsius' %((5.0/9.0)*(Tf - 32) )

##--------------------------------------------------------------------------------------------------
## "select" is a python function and should not be used as a variable
selection = True
while selection:
    x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n'))   
    if x == 1:
        Tc_to_Tf ()
        selection = False
    elif x == 2:
        Tf_to_Tc ()
        selection = False
    else:
        print 'Only options are 1 or 2'

Finally, check your arithmetic.
This subtracts 32 from Tf and then multiplies
(5.0/9.0)*(Tf - 32)

This multiplies Tc by 9/5 and then adds 32
9.0/5.0 * Tc + 32

When in doubt, use parens.

woooee 814 Nearly a Posting Maven

Indeed it should, but test for "key in x" as well, or use a try/except, as you can never tell. Please mark this "solved" so no wastes their time on a solved thread.

Edit: I just did the following and it worked fine so you don't have to test for "key in x" as update takes care of that for you.

x = {}
x[1] = {}
x[1][1]=1
x[1][2]=2

y = {}
y[2] = {}
y[2][3]=3
x.update(y)
print x
#
# prints
{1: {1: 1, 2: 2}, 2: {3: 3}}
woooee 814 Nearly a Posting Maven

This is correct, as you are updating x[1], that is y's key is also 1 and so overwrite's whatever is in x for that key. Change to
y[2][3]=3
or use
x[1].update(y[1])
and you should get what you expect.. If that's not satisfactory then you will have to write your own routine to update however you want.

woooee 814 Nearly a Posting Maven

Making counts on a months data

You should be able to process the data file(s) once, i.e. one 5 hour period, and store the counts for all of the customers in a dictionary or SQL file in one pass. Worst case is that you process the data once and output a separate, smaller file for each customer which is then processed in much less time. If you give us some sample input data and explain what you are trying to do, we can probably help with this.