woooee 814 Nearly a Posting Maven

Check your post after posting. If it doesn't look right, hit the edit button and try again.

Beat you TONYJV by that much.

This is my first function in python and i need to get item quantity and price loops into the function Processorderitems. I took out the items loop because I was not doing anything with it. I need to return the subtotal and I have a 3% discount for quantities over 10. I am not sure how to loop the information into and out of the function. Do I send the list or can you send each index? I have tried both ways so far and get errors. Here is what I have now.

print "This program calculates a total after the user enters: \n the Item, Quantity and Price"
#define process function
def Processorderitem(quantitylist,pricelist):
    #discount variable so it can be changed
    discount = .03
    subtotal = 0
    for i in range(len(quantitylist)):
        for j in range(len(pricelist)):
            subtotal[i] = quantitylist[i] * pricelist[j]
    while quantity >= 10:
        subtotal *= discount
        subtotal -= discount
    return subtotal

#create lists for data
itemlist = []
quantitylist = []
pricelist = []
totlist = []
quantity = 0
price = 0
total = 0
discount = .03

#get user input
for i in range(0,2,1):
    item = str(raw_input('Enter an item: '))
    quantity = int(raw_input('How many of these do you want? '))
    price = int(raw_input('Enter the price: '))
    itemlist.append(item)
    quantitylist.append(quantity)
    pricelist.append(price)
    print itemlist,quantity,price
    
#loop over the lists
#    for item in enumerate(itemlist):
for …
woooee 814 Nearly a Posting Maven

The user enters a number and the program should output that amount of rows and colunmns.

Your for() loop actually prints the same number of __rows__ as the number entered by the user. Instead, you want to use a counter to count each object when it is printed/displayed. According to your diagram, you want to print up to number/2 and then print the bottom half=number/2 as well. Also, how would you print if an odd number, like 9, was entered. Here's an example for the top half to get you started:

number = 12
ctr = 0
row = 1

while ctr < number/2:
    print "*" * row, 
    ctr += row     ## number of objects printed
    print "    row =", row, "ctr is now", ctr
    row += 1
woooee 814 Nearly a Posting Maven

It's what programming's all about We can't learn python for you, so show some effort.

For any newbies, this is the never-ending question technique. The OP keeps posting questions (with no effort at all) until someone is worn down enough to write the code for them. I don't care enough to check, but if you look at the OP's other posts you will probably see a similar style, so ignore this post, and this OP, as long as (s)he views us as code servants.

woooee 814 Nearly a Posting Maven

The encoding info is contained at the beginning of the file (I think), so that would write some sort of header to indicate the file's encoding, i.e. how to process the bytes following. The rest of the file would be just bytes, as all files are.

woooee 814 Nearly a Posting Maven

enumerate is the same as

ctr = 0
for this_entry in sales_list:
    print ctr, this_entry
    ctr += 1
woooee 814 Nearly a Posting Maven

You would do something along the lines of the following. Note that if you open the file using a program that does not encompass encoding, then you will see what appears to be some garbage letters. This in not the file's fault, but the lies with the program being used to view it. Also, Python3.X has unicode built in, so what happens depends on which version of Python you are using. If there are any further questions, include the version of Python that you are using with the question.

fp = codecs.open('test', encoding='utf-8', mode='w+')
fp.write(u'\u4500 blah blah blah\n')

See this page http://docs.python.org/howto/unicode.html

woooee 814 Nearly a Posting Maven

bonuslist will always be the same as the saleval list
bonuslist = saleval
You add the bonus to the field named "bonus" but try to print "bonuslist" which you do not change. See if using a lists of lists, that is one sub_list for each [staff, sales, bonus] helps. Generally you would use a dictionary for each sales person pointing to a list containing sales & bonus, but I am assuming that you have not covered dictionaries yet. Also, do not use "i", "l", "or "O" as single digit variable names as they look too much like numbers.

sales_list = []
for i in range(0,3,1):
    staff = str(raw_input('Enter staff member Name: '))
    sales = int(raw_input('How much is the sale? '))
    if sales >= 0:
        bonus = 0
        ## if sales < > statements here
        sales_list.append ([staff, sales, bonus])

    ## --- this "i" is different from the "i" used in the for loop and does nothing
    ## i += 1

##--- print each sub-list
for ctr, this_entry in enumerate(sales_list):
    print ctr, this_entry

## print the second sales person
this_entry = sales_list[1]
print "\nname =" this_entry[0]
print "sales =", this_entry[1]
print "bonus =", this_entry[2]
woooee 814 Nearly a Posting Maven

Cleaned up the code for my own satisfaction so that all dictionary entries are of the same format, i.e. a list as the second element that can contain zero or more indexes to the game_dict.

regen() is defined on line 597, wearregen() on line 601. Both are used above that so should yield some kind of undefined error message.

game_dict = {}
game_dict['area'] = 0
game_dict['sword'] = 0
game_dict['pots'] = 20
game_dict['first'] = 'Harry'
game_dict['last'] = 'Palms'
 
text_dict = {}
text_dict[0] = ["Welcome ", ['first','last'], "to the world of slime fighter."]
text_dict[1] = ["You have ", ["pots"] ,"potions."]
text_dict[3] = ["Rested", []]
text_dict[4] = ["At least you're not naked", []]  ## spelling corrected
 
def textbox_conf(text):
    print "\ntext is always set to -1 and fg is always 'black'"
    list_to_print = text_dict[text] 
    text_string = list_to_print[0]
    for index in list_to_print[1]:     ## members of game_dict to print
       text_string += str(game_dict[index]) + " "
    for x in range(2, len(list_to_print)):
        text_string += list_to_print[x]
    print "textbox.configure test =", text_string
 
text = 1
textbox_conf(text)
 
text = 3
textbox_conf(text)
 
text = 1
game_dict['pots'] = 30
textbox_conf(text)

text = 0
textbox_conf(text)
woooee 814 Nearly a Posting Maven

You can reverse the for loop and use a step of -1, or append the results to a list and reverse the list before printing.

woooee 814 Nearly a Posting Maven

I don't see "equip" declared anywhere so there is no way to tell what equip.delete() is trying to do, but there is too much code=too much wasted time, to sort through. Also, a dictionary container is your friend here. Pretty much all of the if statements can be replaced with a dictionary, and all of the variables at the beginning should be a dictionary or list so you only pass around one container. A simple example for setting the textbox using one function and a dictionary that is much more readable IMHO. The same can be done for armor, sword, etc.

game_dict = {}
game_dict['area'] = 0
game_dict['sword'] = 0
game_dict['pots'] = 20

text_dict = {}
text_dict[1] = ["You have", "pots" ,"potions."]
text_dict[3] = ["Rested"]
text_dict[4] = ["At least you're not naked"]  ## spelling corrected

def textbox_conf(text):
    print "\ntext is always set to -1 and fg is always 'black'"
    list_to_print = text_dict[text] 
    print "textbox.configure test =", list_to_print[0],
    next_el = 1
    if len(list_to_print) > 2:    ## we have a member of game_dict to print
        game_dict_index = list_to_print[1]
        print game_dict[game_dict_index],
        next_el = 2
    for x in range(next_el, len(list_to_print)):
        print list_to_print[x],
    print

text = 1
textbox_conf(text)

text = 3
textbox_conf(text)

text = 1
game_dict['pots'] = 30
textbox_conf(text)
woooee 814 Nearly a Posting Maven

'Blessings are not received twice, calamities do not occur alone.

Zen Master Wuzu

iamthwee commented: nice +0
woooee 814 Nearly a Posting Maven

Pypi is always a good place to start. I have not tried this wrapper though http://pypi.python.org/pypi/jaraco.mysql

woooee 814 Nearly a Posting Maven

display the data using canvas

Which GUI toolkit are you using? If it is Tkinter, begin at Effbot for line drawing. Also, the polyline1 & 2 should be calculated by one function that receives the parameters and returns the number, and the same for distance1 & 2.

##  pseudo-code example
def calc_poly(data):
    ret_polyline = []
    for ctr in range(len(data)):
        ret_polyline.append(data[ctr].split(','))

    return ret_polyline

polyline1 = calc_poly(data)
polyline2 = calc_poly(data2)
woooee 814 Nearly a Posting Maven

You probably should roll your own here, that is read one record, split on the comma's and test for length. If the length is too short, read another record, split, and append to the first, although there is probably a little more coding here since the "\r\n" is in the middle of the description. Sometimes the difficult way is the easy way.

woooee 814 Nearly a Posting Maven

Usually you should also strip the record first, as no data should be assumed to be 100% reliable. You may or may not want to convert to lower case as well.

for line in open('testconn.txt'):
    rec = line.strip()
    if rec.startswith('Domain') or rec.startswith('Referer'):
       print line
woooee 814 Nearly a Posting Maven

Add a print statement so you know what is being compared, and hence if the append is correct or not. Also, you should first check that both lists are the same length.

h=[]
for i in range(len(change2)):
	for j in range(len(atom)):
                print "comparing" atom[j], atom[i]
		if atom[j]==atom[i]:
			h.append("H")
		else:
			h.append("-")
print h
woooee 814 Nearly a Posting Maven

You might want to post this in a more permanent place as well like pypi.python.org or Activestate. as they are also places that people look for code.

woooee 814 Nearly a Posting Maven

The point is in this code, and it should be giving you problems as p is a class instance of MainProcess, not multiprocessing's Process.

for i in runlist:
    i.join()
 
while True:
    for i in runlist:
        if not i.isAlive():
            i.terminate()
woooee 814 Nearly a Posting Maven

I have 2.7 installed on my Slackware disto. Bleachbit will not run with 2.7, so it may be that there are third party packages that have to be converted first.

woooee 814 Nearly a Posting Maven

How to add an entry to the file /etc/apt/sources.list

sources.list is a list of the repositories to search. It has nothing to do with the individual packages. Try 'man dpkg' and you should find something similar to (I don't remember the exact syntax for dpkg)
dpkg -f package_name
which you can use to see if Python2.6 is in one of the repositories. I found python2.6_2.6.6-6_i386.deb here so you should be able to install it normally. You can always Google for "deb package_name" as well to find something.

woooee 814 Nearly a Posting Maven

Assuming MainProcess is a class, you probably want something along the lines of the following code. If that doesn't help, post back.

for item in proclist:
    MP = MainProcess(item,csvMap)
    p = Process(target=MP.run_something(), args=('XX',))
    p.start()
    runlist.append(p)
woooee 814 Nearly a Posting Maven

He who hesitates is lost

All good things come to he who waits

woooee 814 Nearly a Posting Maven

Add some swear words. That will make it mean. Also, add some print statements so you can see what the program is doing. And if you can not complete the problem, try it another way. Perhaps computing the mean by adding each element of the list to a total field, via a for loop. Obviously you do not understand what this code is doing so staring at it will not help; a different method may.

def mean(alist):
    belowMean = alist
 
    mean = sum(alist) / len(alist)
    print "I am mean, GRRRRR", mean
    print "comparing for <=", mean, "with", alist
    if mean <= alist:
        belowMean = item
 
    return belowMean
woooee 814 Nearly a Posting Maven

soft brian (es): "it doesn't run" isn't enough info, (and no one is going to waste their time trying to properly indent the code you posted so they can run it). Also, try a more descriptive title. There are people who won't even look at threads with titles like "Please Help".

woooee 814 Nearly a Posting Maven

Isn't SharpDevelop an IDE, or have they added a GUI as well? The short answer to your question is to use a toolkit that is not so obscure. There is wxFormBuilder and wxDesigner for the wx toolkit and VisualPython for starters; see also the "Python GUI Programming" and "Starting wxPython" sticky threads. To answer your question, the general way is to use a set() function, or label.text =, but no idea for SharpDevelop.

woooee 814 Nearly a Posting Maven

Eclipse has the fonts installed to print the encoding. The command line obviously does not. You can try to change the default font but that is dependent on which distro you are using as well as which terminal program (xterm is -fa font-name).

woooee 814 Nearly a Posting Maven

Split on the "=" and the first "." or parse the string and pick out the digits.

s = ":enterprises.18489.1.2.1.5.1.10.0 = INTEGER: 1"
t = s.split("=")
v = t[0].split(".")
to_replace=".".join(v[1:])
print to_replace
woooee 814 Nearly a Posting Maven

Perhaps something along the lines of the following. Otherwise, you want to use 2 prompts, one for the number, and another for the word. Note that you can also use isdigit() to test for a number, but it doesn't really matter which one you use.

def check_input(low, high):

    prompt = "Enter an integer number between %d and %d: " % (low, high)
    while True:
        try:
            a = int(input(prompt))
            if low <= a <= high:
                return a
        except ValueError:
            print("A word was entered = %s" (a))

num_input = check_input(33, 126)
print(chr(num_input))
woooee 814 Nearly a Posting Maven

but I need to return the result of the ButtonRelease-1 to main

I for one have no idea what this means as the URL referenced contains many examples.

woooee 814 Nearly a Posting Maven

You should be able to use .configure(background=color) or whatever, but I have not tried it with menus http://pmw.sourceforge.net/doc/howtouse.html.

woooee 814 Nearly a Posting Maven

For unique descriptions, you would want to test the list also, only appending if that color is not already in the list, or use a set. Also, strip() both the description and the word before adding to the dictionary to get rid of spaces and newlines. Then you would use the length of the list/set.

woooee 814 Nearly a Posting Maven

To debug code like this, you have to break it down into individual steps to know where the error lies.

for p in media.get_pixels(pic):
        x = (sum(range(media.get_red(p))))
        print x
##
##   with minimum/terse print statements, it becomes
    ctr = 0
    for p in media.get_pixels(pic):
        if ctr < 5:     ## don't print the entire picture
            ctr += 1
            y = media.get_red(p)
            print type(y), y
            z = range(y)
            print z
            x = sum(z)
#        x = (sum(range(media.get_red(p))))
            print type(x), x

Edit: I just noticed the extra set of parens, which creates a tuple.

here                         here
x = (sum(range(media.get_red(p))))
woooee 814 Nearly a Posting Maven

You have to test for a length of 2 or greater, otherwise you get and index error on the [1:]s.

return matchPat(CH[1:], string[1:])
    elif CH[1] == string[0] or matchPat(CH, string[1:]):

Note also that line 10
matchPat(CH[1:], string)
does not catch the return from the matchPat function so the "return True" is never caught. Add some print statements so you can see what is happening with each recursion.

woooee 814 Nearly a Posting Maven

You are mixing strings and lists. This should help.

class Sentence:
 
    def __init__(self, astr="I'm going back"):
        self.astr = astr
 
    def setWord(self, astr):
        self.astr=astr
 
    def getfirstword(self):
        return ' Changer the word back', self.astr[2]

    def getallword(self):
        print "astr[2]", self.astr[2]
        astr_list = self.astr.split()
        print "astr_list[2]", astr_list[2]
        astr_list[2] = "XXX"
        print "join", " ".join(astr_list)
##        self.astr[2] = "home"
        return self.astr
 
sent = Sentence()
 
print sent.getfirstword()
ret_val = sent.getallword()
print type(ret_val), ret_val
Ghostenshell commented: Thanks again. +2
woooee 814 Nearly a Posting Maven

A good example of using a class is in this tutorial. Note especially the use of "self" and the indentation.

woooee 814 Nearly a Posting Maven

Pass the "driver" to a class function which appends to the list. The same for deleting from the list. You should try to keep all methods within the class.

woooee 814 Nearly a Posting Maven

so please bare with me

You must be a nudist. Please test your code before you post it here.

for file in [f for f in files if f.endswith(".html" or ".htm" or ".txt")]:

So first, get the file names one at a time and print on the screen so you know you are testing the correct names. Next, you should split off the last 4 bytes, and can test for
split_off in ["html", ".htm", ".txt"]
You can try list comprehension some other time. Now, just write code that you understand.

woooee 814 Nearly a Posting Maven

Take a look at this tutorial, especially the references to "self".

woooee 814 Nearly a Posting Maven

squares() never saves or prints the perfect squares within the while loop, (or tests if the arg "num" is ever found as a perfect square if that is what you want to do. I can't tell as there are no comments in the code). Add a print statement which will tell you that the problem is with incrementing.

def squares(num):
    i = 1
    s = 0
    while s <= num :
        s = (i * i)
        print "testing", i, s, "compared to", num
        i = i + 1
    return s
##
## also, you have redundant code, i.e calling squares several times
    while num <= stop:
        ret_s = squares(num)
        if num == ret_s:
            print ret_s
##  the else statement does nothing
##        else :
##            num = num
        num = num + 1
woooee 814 Nearly a Posting Maven

Next, read each record in the file and print it.
After that, split each record and print that. Then decide how you can use this data.

woooee 814 Nearly a Posting Maven

You would have to return big_num. This is a modified version of the first problem, using a string to store the output. It shows passing variables. Try it and add some print statements so you know what is happening. Post back with any problems.

def main():
 
    x = input("Enter an integer (the number of times to print): ")
    y = input("Enter another integer (the number to be printed): ") 
 
    message(x,y)
    print     ## goto a new line
    ret_str = using_a_string(x, y, "")
    print ret_str[:-2]     ## strip last " +"
 
def message(x,y):
 
    if (x > 0):
        print y, "+", 
        message(x - 1,y)

def using_a_string(x, y, str_out):
    if (x > 0):
        str_out += " %d +" % (y) 
        str_out = using_a_string(x - 1, y, str_out)
    return str_out
main()
woooee 814 Nearly a Posting Maven

Sorry, I missed the recursion part. You want to print "y", since you are using "x" as the number of times to print, and you only print "y" once per function call. Since the function calls itself until x = 0, each call in turn will print one "y" value. There is a trailing "+" on the end when using this code. You will have to test for x==1 to get rid of it. FYI, recursion is rarely used in the real world, and is considered bad coding style by some, so you probably won't have to use this outside of the class.

def main():
    x = input("Enter an integer (the number of times to print): ")
    y = input("Enter another integer (the number to be printed): ")
 
    message(x,y)
    print     ## goto a new line

  
def message(x,y):
    if (x > 0):
        print y, "+", 
        message(x - 1,y)


main()
woooee 814 Nearly a Posting Maven
1   2   3   4   5   6   7??
The book has an example of 7 * 4 = 4 + 4 + 4 + 4 + 4 + 4.

I hope that's a typo on your part, otherwise you should find another book. Sorry, couldn't pass that one up. You want to start thinking of data as bytes that you use or format however you want. So, the following are 2 more ways. I'm sure there are others.

multiplier = 7
output_str = "4"
for ctr in range(multiplier-1):
    output_str += "+4"
print output_str
#
output_list = []
for ctr in range(multiplier):
   output_list.append("4")
print "+".join(output_list)
woooee 814 Nearly a Posting Maven

I would suggest a dictionary with the key pointing to a list, which would show up similar to your example

D_dict = {"D1":[0, 0, 1, 0, 0, 1, 0, 0, 0 ],
          "D2":[0, 1, 0, 0, 0, 1, 1, 1, 0 ] }

Come up with some code to read the file and split/compare the words, and post back with any problems.

woooee 814 Nearly a Posting Maven

Edit: It seems that I haven't to place a full directory path. Can someone help me out with this?

The directory either has to be in the PATH or you can call it in the current directory with
python ./script1.py
or just
./script1.py if on Linux and the script is executable with the bash shebang.
http://code.activestate.com/lists/python-tutor/71566/

woooee 814 Nearly a Posting Maven

Try to import Tkinter by itself to see if the problem is with Tkinter or matplotlib, or TCL & Tk are not installed. What is a "port install". Those packages should come pre-built from the standard Mac repositories. Generally speaking, a problem like this occurs when the library is installed in a different location. There are several possible things to do depending. On Linux we would check the PYTHONPATH to see where Python searches, or print sys.path.

woooee 814 Nearly a Posting Maven

I know this is newbie basics - sorry about that

As long as you learned something and are making progress. Please mark the thread "Solved". Also, I would place the statement
a,b = max(a,b),min(a,b) #making sure a>b
under the function so you can send any two values to it and have the function take care of the max/min part. And do you want to test for two numbers that are the same, again the function should do this for you.

Seems to run ok.

Capture the value "a" returned by the function.
ret_a = fac(a,b) #running the function on a and b
print "final 'a' value is", ret_a

woooee 814 Nearly a Posting Maven

It doesn't have to be raw_input, as long as it's a prompting function that can be connected to a variable.

I don't want images. And I want to be able to prompt.

Make up your mind. Those of us who volunteer have a limited amount of time to spend here and do not wish to waste it generating code that will not be used.

woooee 814 Nearly a Posting Maven

for lastmod_seconds, val in date_file_list:

Obviously you should print at least part of date_file_list. No one here has ESP AFAIK, so no one can discern the contents of date_file_list, but what happens if no file is found.

date_file_tuple = lastmod_seconds, file
        date_file_list= tuple(date_file_tuple)
        date_file_set = set(date_file_list)
        date_file_list = list(date_file_set)

"""  You can replace the above lines of code with
"""
date_file_list = [lastmod_seconds, file]   ## creates a list

"""  note also that you do not append or add items, so the tuple, set, list will
     only contain one item
"""
woooee 814 Nearly a Posting Maven

i cant use this in debian lenny

I don't understand why you can't use this. Also, you probably only want root access for the script, otherwise anyone can shut down your system. If you want to run it from a non-root user, then you or the program will also have to be able to supply the correct password, which also is a bad idea.