You should increment height, otherwise it's an infinite loop. In general you want to use a for() or while() loop and append to a list on each loop. Add print statements to print what you don't get (especially 'height' and 'start').
You should increment height, otherwise it's an infinite loop. In general you want to use a for() or while() loop and append to a list on each loop. Add print statements to print what you don't get (especially 'height' and 'start').
If you are using pack(), not grid, then you want side=LEFT. See this tutorial http://effbot.org/tkinterbook/pack.htm
You can use a while loop, something along the lines of
found = 0
while not found:
print "Please use W or L to input the results of the game"
print
win_loss_code = raw_input('Enter W for Win or L for Loss: ')
win_loss_code = win_loss_code.lower()
if win_loss_code == "w":
print "You won"
found = 1
elif win_loss_code == 'l':
print "you lost"
found = 1
else:
print "Error"
print 'Please use only "W" or "L" '
##---------------------------------------------------------------------
## if you have a lot of letters to test, use a dictionary
print_dic = {"w":"You won", "l":"You lost", \
"x":"Stupid, no one uses x" }
found = 0
while not found:
print "Please use W or L to input the results of the game"
print
win_loss_code = raw_input('Enter W for Win or L for Loss: ')
win_loss_code = win_loss_code.lower()
if win_loss_code in print_dic:
print print_dic[win_loss_code]
found = 1
else:
print "Error"
print 'Please use only "W" or "L" '
There are a lot of variations on this, including the use of a function for input, but this is the general idea.
To delete from a dictionary, use
del dict_name[key]
so I think you would want
del records[entry]
but you will have to test that for yourself. You really should learn to Google as this is simple so examples abound on the net. See here http://www.diveintopython.org/getting_to_know_python/dictionaries.html
Scru just posted the same thing as I was (well except that I would use floats, unless income is whole dollars only), so I will submit an idea to simplify entry.
x = [] ## will contain the entries
total = 0
for j in range(1, 5):
income = float(raw_input("Enter Income %d: " % (j)))
x.append( income )
total += income
# Note that total is a float, not a list.
print "total income is %9.2f" % (total)
Submit a sample file so we can see specifically what you are trying to run. And what operating system is your computer running. It may be the file and not python.
Yep, homework.
if entry in records:
should work. You then replace the "r" in the print statements with "entry".
A slight modification.
for index, item in enumerate(arr):
if item > 100:
return index, item
See here for info on lists http://effbot.org/zone/python-list.htm
Edit: Damn, this is probably homework. My mistake. Using enumerate will probably red flag it though.
I think this does what you want with the host write function but the code is truncated http://code.activestate.com/recipes/152043/
I think this probably has to do with Python's garbage collection. The file might not be closed at the exact moment you close it. You can let the program sleep for say one second, or try putting the read() through the close() in a function and call the function. All references should be destroyed when you exit the function. You should then be able to delete immediatly after exiting the function, but that's just my theory. Please post back if you come up with a solution, as others will want to know in the future.
The program that I submitted works fine, with "?", on Python 2.5. Take a look at it. If you still can't get your program to run, then submit the code you are now using as it has changed from the first post.
rcw is a list of lists. You want to write strings to a file so you have to add one more level.
for record in rcw:
bird = record.strip().split()
## add this to each record
outgroup.write("%s" % (dID[bird[3]]) ## assuming this is a string
## bird is a list
for field in bird:
outgroup.write(", %s" % (field)) ## you may not want the
comma
outgroup.write("\n")
##
## or more simply
for record in rcw:
bird = record.strip().split()
## prepend this to each record
outgroup.write("%s " % (dID[bird[3]]))
## and the record
outgroup.write("%s" % (record)) ## assumes record already has a "\n"
You also want a conn.comit() after inserting. And you should take advantage of using a class, plus change the first statement to use python.
#!/usr/bin/python
# SQLite command to be used with the applications
import sqlite3 as sqlite
class SqliteCommands:
def ___init__(self, parent):
self.parent = parent
def list_all_recs( self, t_name ) :
self.cur.execute("select * from %s" % (t_name))
recs_list = self.cur.fetchall()
for rec in recs_list:
print rec
# Create database
def onCreateDb(self, t_name):
self.conn = sqlite.connect("%s" % (t_name))
self.cur = self.conn.cursor()
## return (conn, cur) ## not necessary
#Create New Table
def onCreateTable(self, t_name):
SQL_str="CREATE TABLE IF NOT EXISTS %s" %(t_name)
SQL_str += "(Date TEXT, Explanations TEXT, Deposit REAL, "
SQL_str += "Withdraw REAL, Balance REAL)"
self.cur.execute(SQL_str)
#Create Rows for the New table
def onInsertRows(self, t_name, tuple_rows):
SQL_str ="INSERT INTO %s VALUES(?, ?, ?, ?, ? )" % (t_name)
self.cur.execute(SQL_str, tuple_rows)
self.conn.commit()
x = SqliteCommands()
x.onCreateDb("Steve")
x.onCreateTable("Steve")
t = ("03/02/2009", "Billing for electricity", 200.0, 230.0, 270.0)
x.onInsertRows("Steve", t)
t = ("03/02/2009", "Billing for gas", 100.0, 210.0, 200.0)
x.onInsertRows("Steve", t)
x.list_all_recs("Steve")
Maybe you should write a simpler test program first
This is good advice. First, test onCreateDb to see that it is working, then test onCreateTable, etc. When the program doesn't run at all there is something wrong with the shebang (#!/usr/bin/python
).
"records" should be a dictionary (code has not been tested)
# A list of entries
# Each element will be a dictionary
records = {}
next_number=1
# User input
user = ""
while user!="0":
#display menu
print
print " Film Database"
print "-----------------"
print "1 -- Add Entry"
print "2 -- List Entries"
print "3 -- List Single Entry"
print "4 -- Delete Single Entry"
print "0 -- Exit"
print "-----------------"
print len(records), "entries."
print
print "Enter option:",
#Get user input
user=raw_input()
if user=="1":
#Add to database
#create empty dictionary
item={}
print "Enter title:"
item["Title"]=raw_input()
print "Enter director:",
item["Director"]=raw_input()
print "Enter year:"
item["Year"]=raw_input()
records[next_number] = item
next_number += 1
elif user=="2":
#display database
print '-'*10
for r in records:
print "record number", r
print "Title: ",records[r]["Title"]
print "Year: ",records[r]["Year"]
print "Director:",records[r]["Director"]
print "-"*10
print
##--------------------------------------------
## which is the same as
#this_item = records[r]
#print "Title: ",this_item["Title"]
#print "Year: ",this_item["Year"]
#print "Director:",this_item["Director"]
elif user=="3":
#ask for which entry to view
print "-"*10
entry = int(raw_input('entry: '))
else:
print "Unknown option"
This would work much better using an SQLite database.
You just have to dig a little bit, although I am making the assumption that version 1.2 is compatible with python2.3. http://sourceforge.net/project/showfiles.php?group_id=104148&package_id=130611&release_id=291663
If you are talking about an icon on the desktop that a user can click on to execute the program, that depends on the desktop you are using. I would suggest asking this on the Ubuntu forum, telling them which desktop you are using, Gnome, KDE, XFCE, etc. and which version of Ubuntu Hardy, Ibex, etc. http://ubuntuforums.org/ Sorry, that's the best advice that I can give.
You would use a simple bash file for this and create an icon to the bash file. You could use python, but it would simply call bash to run the program.
The following works fine on my machine. Perhaps you should submit some of the data in the file as it may be corrupted. Also, has_key is being replaced with "in".
f = ["PUT key1 value1A", \
"Junk key1 value1", \
"PUT key1 value1B", \
"PUT key2 value2", \
"PUT key1 value1C" ]
## don't use dict or list, they are reserved words
##dict = {}
key_dic = {}
for line in f:
print line
keyword = line.split()
if keyword[0] == 'PUT': # keyword[1] = key; keyword[2] = value
if keyword[1] in key_dic:
# append keyword[2] to keyword[1]'s value list
key_dic[keyword[1]].append(keyword[2])
else:
key_dic[keyword[1]] = [keyword[2]]
print key_dic
##
##
## or you can replace this part of your code
else:
templist = keyword[2]
list(templist)
dict[keyword[1]] = templist
##
## with (also using a name other than "dict")
else:
templist = []
templist.append(keyword[2])
dict[keyword[1]] = templist
##
## this will also work
else:
templist = list(keyword[2])
## you don't do anything with the list object returned
## list(templist) ## so this is still a string
dict[keyword[1]] = templist
Another way to go at it
edge = "# "*8 + "#"
center = "# " + ". "*7 + "#"
print edge
for j in range(0, 6):
print center
print edge
In any case, you want each line to be a single string, so if you want it all in one list, it will be a list containing 8 strings, one for each line you want to print, not individual characters.
if you want to make a super amazingly quick program and it had to be in python then maybe this could even matter (i doubt it)
I doubt it as well. I view the "function calls are expensive" as someone trying to impress with how much they know. Function calls are expensive, AFAIK, because the function is in a different block of memory, so the program has to go to that block, execute it, and then come back to where it was. I care a __lot__ more about readability and being able to understand something that was written long before my little gray cells' memory of it. A function separates things nicely. If it takes an extra milli-second or two, fine.
why not go for Python 2.5 ?
Yes, decimal was first included in Python 2.4 http://www.python.org/doc/2.5.2/lib/module-decimal.html On linux, upgrading is as simple as telling the package manager to upgrade. For MS Windows, http://python.org/download/releases/2.5.4/ ActiveState also has a version. Either version is fine. Also, you want to update when new releases come out for security reasons.
This is a well know and well documented result on PCs due to the use of binary numbers. Our base 10 system also has problems (with numbers like 1/3 or Pi). The explaination at python.org is here www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate and http://www.lahey.com/float.htm A google for "floating point precision" or something similiar will yield more results. Most, if not all programming languages have add-ons for exact precision. In python it is the decimal module.
import decimal
x = decimal.Decimal("1")
y = decimal.Decimal("3")
print x / y
## set precision to 3
decimal.getcontext().prec = 3
## set rounding type
decimal.getcontext().rounding=decimal.ROUND_HALF_EVEN
print x / y
In fact, I had this lying around. Pretty basic but should give you an idea.
class Class1 :
def __init__ (self) :
self.field1 = "***"
self.field2 = 0
self.field3 = "EMPTY"
#==========================================================================
ctr = 0
class_dic = {}
C = Class1()
C.field1 = "Test1"
C.field2 = 1
C.field3 = "Test1A"
class_dic[ctr] = C
ctr += 1
C = Class1()
##C.field1 = "Test2"
C.field2 = 2
C.field3 = "Test2A"
class_dic[ctr] = C
ctr += 1
C = Class1()
C.field1 = "Test3"
C.field2 = 3
##C.field3 = "Test3A"
class_dic[ctr] = C
class_dic[1].field3 = "ID test"
for D in class_dic :
print D, class_dic[D].field1, class_dic[D].field2, class_dic[D].field3
You would generally use a dictionary for this (and please do not use "l", "i", or "o" for single digit variables--they look too much like numbers). The dictionary key would point to a list ["abstract", "title", "ID"]
class classic:
def __init__(self,text):
text ="TI -xxTI -yy TI -z"
self.class_dic = {}
for r in range(text.count('TI -')):
self.class_dic[r] = ["empty", "empty", "empty"]
## change the "ID" (element 2) for key=1
self.class_dic[1][2] = "ID test"
print self.class_dic
If you really want to use a class for abstract, title, and ID, then the dictioary key can point to a class instance instead of a list.
It is more common to iterate the file one record at a time instead of the read() and split().
import random
outfile = open('numbers.txt', 'w')
for count in range(20):
##Get random numbers
rebmun = random.randint(1,99)
outfile.write(str(rebmun) + '\n')
outfile.close()
numbers={}
fp = open('numbers.txt','r')
for rec in fp:
numbers[rec.strip()] = "test"
print numbers
I once Googled for "python web crawler". There were many but this is the only one saved http://www-128.ibm.com/developerworks/linux/library/l-spider/ "See Example 4: Web site crawler"
If you do not understand the shorthand version in Gribouillis' code, it is the same as
def addbook(ISBN, author, title, stock):
if ISBN in bookdic:
## booklist[ISBN][2] += stock
ISBN_list = bookdic[ISBN] ## returns the list for this key
print ISBN, ISBN_list
ISBN_stock = ISBN_list[2]
ISBN_stock += stock
ISBN_list[2] = ISBN_stock
else:
bookdic[ISBN] = [author, title, stock]
As you can see, the original code is much simplier once you understand it.
You return the string "error". It is an empty string unless the following is true.
for element in find_text(item):
if extra+element.tag.replace(' ','') in Results[0].keys():
if element.text >= Results[0][extra+element.tag.replace(' ','')]:
error = error + "Error with "+item.tag+" "+element.tag+" value = "+element.text +" \n"
else:
continue
Whatever you decide, jump in and try it. You will have to post some code if you want any specific help.
Using an SQLite database is the simpliest and best. It comes with Python and a tutorial is here http://www.devshed.com/c/a/Python/Using-SQLite-in-Python/
This will only execute actionDefault once.
do_action = 0
if testA:
actionA()
if testB:
actionB()
if textC:
actionC()
else:
do_action=1
else:
do_action=1
else:
do_action=1
if do_action:
actionDefault()
I just happen to have it handy:
We all have interesting little snippets lying around. Too bad we can't find some way to create some sort of central index, but it is more than I have time for.
Image Files
tif to gif
SQLite
database - create
database - modify record
Homework problems
common
primes - find all up to a certain number
etc.
Wonder how polyphonic gotrucculliet gets his frigging spam onto DaniWeb?
Report it to spam@uce.gov They will at least start blocking that one web address i.e. mobilephonemusic + org (don't want to increase the number of search engine hits for that site)
I waited for the super-sized 10 meg drive and I think I paid $1100.00 for it.
A cardinal rule is don't mix tabs and spaces for the obvious reason that everyone does not have the same tab settings. The unoffical poll for this forum is that most people use spaces only. Most editors/IDE can be set to indent with either.
I want the program to say that after the first year the value would be(50*1.05=52.5) and the second year would be (50*1.05^2+52.5=107.625)
That does not appear to be correct IMO. In the second year you have the same $50 drawing interest twice for the first year, once in the $52.50 and once in the $50*1.05^2. You have $50.00 that will be paid interest every year
$50 * 1.05 over some range of years
or you will have accumulated interest
new_principle_interest * 1.05 (or += .05) over some range of years.
and the third year would be (50*1.05^3+107.625=165.50625)
If $50 is deposited every year, which I did not see in the original problem, then this is still incorrect as each $50 would only earn interest from the time it was deposited. First get the math down and then worry about converting it into code.
I want the program to say that after the first year the value would be(50*1.05=52.5) and the second year would be (50*1.05^2+52.5=107.625) and the third year would be (50*1.05^3+107.625=165.50625)
That does not appear to be correct IMO. In the second year you have the same $50 drawing interest twice for the first year, once in the $52.50 and once in the $50*1.05^2. You have $50.00 that will be paid interest every year
$50 * 1.05 over some range of years
or you will have accumulated interest
new_principle_interest *= 1.05 (or += .05) over some range of years. First get the math down and then worry about converting it into code.
Python has the built in isupper() and islower() (also isdigit, isspace, ispunct) http://www.python.org/doc/2.5.2/lib/module-curses.ascii.html
test=["AabcdEFg.",
"jKLmnopR?" ]
upper_total=0
lower_total=0
neither_total=0
for rec in test:
for chr in rec:
if chr.isupper():
upper_total += 1
elif chr.islower():
lower_total += 1
else:
neither_total += 1
print "%d Upper Case, %d lower case, and %d neither" % \
(upper_total, lower_total, neither_total)
#
# And if you wanted to go with your original idea, it would be
if (chr >= "A") and (chr <= "Z"):
upper_total += 1
etc.
Edit: and it looks like great minds think alike.
I don't use this so am not sure, but you can do something along the lines of this so you have a pre-defined string instead of substitution in the SQL statement.
field_type = "TEXT"
SQL_statement = "CREATE TABLE %s (%s %s, %s %s, %s %s, %s %s, %s %s)" % \
(t_name, field_type, \
t_date, field_type, \
t_explanations, field_type, \
t_deposit, field_type, \
t_withdraw, field_type, \
t_balance, field_type)
print SQL_statement
cursor.execute(SQL_statement)
Note that in the example you linked in the previous post, they are using VARCHAR, which I always use, so if you get an error try changing TEXT to VARCHAR. SQLite does not support a full SQL set of statements but has most of the stuff that a normal user will use.
Edit: Doh! I have a work-in-progress program that I use to create a simple and quick database with access. I fed in your fields, and the following came out which hopefully should help some. It sould be trivial to pass the database's name to the class as a variable or change the number of fields, etc.
##======================================================================
class DummyClass:
def __init__( self ) :
self.SQL_filename = './test_dbf'
self.open_files()
## END __init__()
##----------------------------------------------------------------------
def add_rec( self ) :
val_tuple=(self.t_date, self.t_explanations, self.t_deposit, self.t_withdraw, self.t_balance)
self.cur.execute('INSERT INTO test_dbf values (?,?,?,?,?)', val_tuple)
self.con.commit()
## END AddRec()
##----------------------------------------------------------------------
def copy_to_struct( self, rec ) :
self.t_date = rec[0]
self.t_explanations = rec[1]
self.t_deposit = rec[2]
self.t_withdraw = rec[3]
self.t_balance = rec[4]
## END copy_to_struct()
##----------------------------------------------------------------------
def list_all_recs( self ) :
self.cur.execute("select …
And this may be because of 32 bit MS Windows limitations. Datetime will go down to microseconds on Linux, but only milliseconds on MS Windows. There was a bug report filed, and supposedly fixed, but the files tested were only a few GB each http://bugs.python.org/issue1672853 You may have to either split the file into parts or use the whence option as stated above, with either a seek from the end, or multiple os.SEEK_CUR statements (which may or may not work).
f.seek(2, os.SEEK_CUR) advances the position by two and f.seek(-3, os.SEEK_END) sets the position to the third to last.
At one time you could pass a float to seek() and it would convert to a long long. I don't know if that still works or not. It would be doubtful if you are using 2.6 or 3.0.
You have to give each field in the SQLite db a name so you can access each one individually, and define it as a variable length character field, integer, etc.. Select where sql_date == date_today kind of thing. Assuming that everything is a string...
## Create a connection to the database file
con = sqlite.connect('test_db')
## Get a Cursor object that operates in the context of Connection con
cursor = con.cursor()
cursor.execute('''create table test_db(sql_date varchar,sql_exp varchar, sql_deposit varchar, sql_withdraw varchar, sql_balance varchar)''')
val_tuple=(t_date, t_explanations, t_deposit, t_withdraw, t_balance)
cursor.execute('INSERT INTO test_db values (?,?,?,?,?)', val_tuple)
con.commit()
This may be a good time to learn to use a class as it works much better for this type of program. Here is some simple code to get you started. If it is easier to understand, you could also use a dictionary to hold the deck of cards, with the index being some abbreviation of the card, pointing to the value of that card.
import random
class BlackJack:
def __init__(self):
self.testing = True
self.card_number = 0
self.players_hand = []
self.dealers_hand = []
self.shuffle_deck()
## initial deal the hand
for j in range( 0, 2):
self.deal_one_card(self.players_hand)
self.deal_one_card(self.dealers_hand)
self.calculate_totals()
## ask player for another card
ask = 1 ## simulate player asking for another card
while ask:
self.deal_one_card(self.players_hand)
ask = 0 ## simulate player only asked for one card
self.calculate_totals()
if self.testing:
print "initial players hand", self.players_hand
print "initial dealers hand", self.dealers_hand
def calculate_totals(self):
players_total = self.calculate_totals_generic(self.players_hand)
print "players hand totals", players_total
dealers_total = self.calculate_totals_generic(self.dealers_hand)
print "dealers hand totals", dealers_total
def calculate_totals_generic(self, list_to_total):
card_total = 0
suit = 0
for card in list_to_total:
## numer = 0 = clubs
## 1 = diamonds
## 2 = hearts
## 3 = spades
## denominator = face value
numer, denom = divmod(card, 13)
print "N/D =", card, numer, denom
if 1 == denom:
print "\n-----> Ace Found\n"
card_total += denom
return card_total
def deal_one_card(self, hand):
hand.append(self.deck[self.card_number])
self.card_number += 1
def shuffle_deck(self):
""" 1=Ace of clubs
11=Jack of clubs
12=Queen of clubs
13=King of clubs
14=Ace of diamonds
26=King of diamonds
27=Ace of …
A personal preference would be to use a list for the printed portion.
word = "alphabetical" ## simulate getting a word from the file
guess_list = []
for j in range(0, len(word)):
guess_list.append("_")
#
# Ask for a guess, etc.
# Guess is incorrect
guess_word = "".join(guess_list)
print guess_word
#
# Simulate letter "P" is guessed and the third element of the
# list is replaced with the correct letter
guess_list[2]="p"
guess_word = "".join(guess_list)
print guess_word
#
# More visually appealing?
guess_word = " ".join(guess_list)
print guess_word
You would of course have functions to do most of this and call the "check_if_the_letter_is_correct" function, or the "print_guess_word" function instead of one long program.
Take a look at Vegaseat's example of moving rectangles using canvas. http://www.daniweb.com/forums/thread147502.html
This is the errant code. If it finds any file that fulfills the requirements, the whole path is zipped (and is re_zipped multiple times if more than one file is found). Perhaps you want to append the file name to a list, and zip those files only. You could also copy the files to a temporary directory, zip that directory, and then delete everything in it. That may cause problems when un-zipping as it will unzip to the temporary directory and not the original directory.
if os.stat(true_file).st_mtime < ftime:
if os.path.isfile(true_file):
#print os.stat(true_file).st_mtime
##--- zips everything in the path
zippy(path)
#os.remove(path)
Using a simple if
test_file = [
'User-Agent: Googlebot',
'#Disallow: /',
'Disallow: /comments',
'Disallow: /user',
'Disallow: /poll',
'Disallow: /print',
'Disallow: /search',
'',
'User-Agent: Cogger',
'#Disallow: /',
'Disallow: /comments',
'Disallow: /user',
'Disallow: /poll',
'Disallow: /print',
'Disallow: /search',
'',
'User-Agent: ia_archive',
'Disallow: /comments',
'Disallow: /user',
'Disallow: /poll',
'Disallow: /print',
'Disallow: /search' ]
found_list = []
found = 0
to_find = "Cogger"
for rec in test_file:
rec = rec.strip()
if rec.startswith("User-Agent"):
found = 0
if to_find in rec:
found = 1
if (found) and (len(rec)):
found_list.append(rec)
for rec in found_list:
print rec
I would like to know if there is an easier way than what I just did
Would raise red flags for a beginning homework assignment like above, but you can use operator to sort on any list element
import operator
data = [
'kick me 989',
'bodybody 344',
'Santa Clause 0943',
'Bart Simpson 100',
'As Is 2856' ]
## sort on last element
data_as_lists = [ rec.split() for rec in data ] ## convert into list of lists
data_as_lists.sort(key=operator.itemgetter(-1))
print data_as_lists
print
for each_rec in data_as_lists :
print each_rec
## or, using integers
for rec in data_as_lists:
rec[-1] = int(rec[-1])
data_as_lists.sort(key=operator.itemgetter(-1))
print data_as_lists
print
for each_rec in data_as_lists :
print each_rec