Re: [Tutor] Writing to the file system and verify the files written out.
Becky Mcquilling wrote: dir_list = os.listdir(self.dirname) dir_set = set() for file in dir_list: dir_set.add(file) self.assertEqual(dir_list, text_files, "The filelist is not equal") You're comparing a list of file names to a set of file names. They will never match, even if they have the same content. Try this instead: dir_set = set(os.listdir(self.dirname)) self.assertEqual(dir_set, text_files, "The filelist is not equal") -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Python skipping if statement (Really simple code)
-- Forwarded message -- From: Casey Key Date: Thu, Apr 14, 2011 at 4:02 PM Subject: Python skipping if statement (Really simple code) To: tu...@python.com Hey im a newbie to python, but i made this test code. and it is just skipping over the if statement, which is essential to the program. import random print("Renees a hater, and you know what happens to hater? They hate!") print("They purpose of this program is to express your feelings toward Renee.") print("Note:I am not pointing of a particular Renee it is just a random name.") caution = input("After reading the note do you want to proceed? ") if caution == "yes" : print("Lets get started.") hate = random.randint(1, 5) print("Renees hate level is at ", hate) proceed = input(int("Do you want to see Renees hate in form of a picture? ")) if proceed == "yes": print("Chose a number between 1 and 3. ") choice = input("So whats your choice? ") if choice == "1": print( """ , (`. : \ __....__ `.`.| |: _,-':::''' ' `:`-._ `.:\|| _,':' ``-. \\`|_,':::' `:. `':::`. ;` `-'' `::. `::\ ,-' .::' `:. `::..`:\ ,' /_) -.`::. `:. | ,'.: ``:.`:. .::. \ __,-' ___,..-''-. `:.`. /. | |):'_,--' `.`::.. |::. ::\ `-' |`--.:_|_\.__ ::| | _/|| \::|::/\ :| /:./ |:::/\__:::):/ \ :\ ,'::' /:::|,'/_/`. ``-.__ jrei (//|/\ ,';':,-' `-.__ `'--..__ """) elif choice == "2": print( """ _,\,\,\|\|\|\|\|\|\|\/-\___.._ __,-' () .\ / __/---\_____ ---/ | / \ \___/\\ \___/ | |\ \\\ | |/ | \\__/_ | || \/_ /\ || \--\ || \\___ \---\\ """) elif choice == "3": print( """ /\ ( ;`~v/~~~ ;._ ,/'"/^) ' < o\ '".~'\\\--, ,/",/W u '`. ~ >,._.., )' ,/' w ,U^v ;//^)/')/^\;~)' ,/"'/ W` ^v W |; )/' ;'' | v' v`" W } \\ ".'\v `v/^W,) '\)\.)\/) `\ ,/,)' ''')/^"-;' \ ? ". \ """) suprise = input("Are you ready for a suprise?") if suprise == "yes": print( """ MMM88&&&, ,MMM8&&&. `'MMM88&&&, M88'MMM88&&&, M88&& 'MMM88&&&, M88&& 'MMM88&&& M88&&'MMM88&&& M88 MMM88&&& 'MMM8&&&' 888 'MM88&&& 88& MM88&&& 88& MM88&&& ,MMM8&&&. MM88&&& M88,MM88&&& M88&& MMM88&&&' M88&& MMM88&&&' M88&& MMM88&&&' M88 MMM88&&&' 'MMM8&&&'MMM88&&&' MMM88&&&' . """) input("\n\nPress the enter key to exit.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python skipping if statement (Really simple code)
"Casey Key" wrote Hey im a newbie to python, but i made this test code. and it is just skipping over the if statement, which is essential to the program. Which if statement, there are several? Are there any error messages? If so send them in their entirety. If not can you show us whatever output you do get. If you know which if statement is failing have you tried inserting a print statement to show what the test value is actually stored as? (For example the first if statement would require: print (caution) just before the if statement. ) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ import random print("Renees a hater, and you know what happens to hater? They hate!") print("They purpose of this program is to express your feelings toward Renee.") print("Note:I am not pointing of a particular Renee it is just a random name.") caution = input("After reading the note do you want to proceed? ") if caution == "yes" : print("Lets get started.") hate = random.randint(1, 5) print("Renees hate level is at ", hate) proceed = input(int("Do you want to see Renees hate in form of a picture? ")) if proceed == "yes": print("Chose a number between 1 and 3. ") choice = input("So whats your choice? ") if choice == "1": print( """ , (`. : \ __....__ `.`.| |: _,-':::''' ' `:`-._ `.:\|| _,':' ``-. \\`|_,':::' `:. `':::`. ;` `-'' `::. `::\ ,-' .::' `:. `::..`:\ ,' /_) -.`::. `:. | ,'.: ``:.`:. .::. \ __,-' ___,..-''-. `:.`. /. | |):'_,--' `.`::.. |::. ::\ `-' |`--.:_|_\.__ ::| | _/|| \::|::/\ :| /:./ |:::/\__:::):/ \ :\ ,'::' /:::|,'/_/`. ``-.__ jrei (//|/\ ,';':,-' `-.__ `'--..__ """) elif choice == "2": print( """ _,\,\,\|\|\|\|\|\|\|\/-\___.._ __,-' () .\ / __/---\_____ ---/ | / \ \___/\\ \___/ | |\ \\\ | |/ | \\__/_ | || \/_ /\ || \--\ || \\___ \---\\ """) elif choice == "3": print( """ /\ ( ;`~v/~~~ ;._ ,/'"/^) ' < o\ '".~'\\\--, ,/",/W u '`. ~ >,._.., )' ,/' w ,U^v ;//^)/')/^\;~)' ,/"'/ W` ^v W |; )/' ;'' | v' v`" W } \\ ".'\v `v/^W,) '\)\.)\/) `\ ,/,)' ''')/^"-;' \ ? ". \ """) suprise = input("Are you ready for a suprise?") if suprise == "yes": print( """ MMM88&&&, ,MMM8&&&. `'MMM88&&&, M88'MMM88&&&, M88&& 'MMM88&&&, M88&& 'MMM88&&& M88&&'MMM88&&& M88 MMM88&&& 'MMM8&&&' 888 'MM88&&& 88& MM88&&& 88& MM88&&& ,MMM8&&&. MM88&&& M88,MM88&&& M88&& MMM88&&&' M88&& MMM88&&&' M88&& MMM88&&&' M88 MMM88&&&' 'MMM8&&&'MMM88&&&' MMM88&&&' . """) input("\n\nPress the enter key to exit.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Python skipping if statement (Really simple code)
Casey Key wrote: > -- Forwarded message -- > From: Casey Key > Date: Thu, Apr 14, 2011 at 4:02 PM > Subject: Python skipping if statement (Really simple code) > To: tu...@python.com > > > Hey im a newbie to python, but i made this test code. and it is just > skipping over the if statement, which is essential to the program. When you run your code, enter yes to the first question Python stops with a "traceback", a dump of the error that has occured: $ python3 ascii_art.py Renees a hater, and you know what happens to hater? They hate! They purpose of this program is to express your feelings toward Renee. Note:I am not pointing of a particular Renee it is just a random name. After reading the note do you want to proceed? yes Lets get started. Renees hate level is at 3 Traceback (most recent call last): File "ascii_art.py", line 12, in proceed = input(int("Do you want to see Renees hate in form of a picture? ")) ValueError: invalid literal for int() with base 10: 'Do you want to see Renees hate in form of a picture? ' Read the last line carefully, then go upwards where the traceback tells you in what line the error occured and see if you can fix the problem yourself. Come back here if you can't. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] ImportError: No module named wdmmgext.load
Hi, I'm trying to install the code from http://wheredoesmymoneygo.org/getting-started/ on my local machine. I've got a mac os 10.6.7, python 2.7.1, pip, and the most recent postgres installation. I'm now testing imported data and I get 21 errors (see attached). The majority sounds like: from wdmmgext.load import uganda ImportError: No module named wdmmgext.load I've searched the files that use this module. Attached is an example file. I see 2 more errors; 1) that the file 'ukgov-finances-cra/cra_2009_db.csv' does not exist. 2) SolrException: HTTP code=404, reason=Not Found Maybe both are due to the wdmmgext.load error, so I'll ignore this for now and first try to find answer to my first question. Thanks in advance for the help! Ben import json import os import pkg_resources import wdmmg.model as model from wdmmgext.load import uganda class TestDepartments(object): @classmethod def setup_class(self): model.repo.delete_all() model.Session.remove() self.name = uganda.dataset_name filepath = 'wdmmg/tests/uganda_sample.xls' test_file = os.path.abspath(filepath) uganda.load_files(filename=test_file, commit_every=10) model.Session.commit() model.Session.remove() @classmethod def teardown_class(self): model.repo.delete_all() model.Session.commit() model.Session.remove() # check dataset exists def test_01_dataset(self): out = (model.Session.query(model.Dataset) .filter_by(name=self.name) ).first() assert out, out # Get our keys, and check values exist for them. def test_02_classification(self): for key_name in [u'from', u'time', u'uganda_id', u'gou_vote', u'vote_name', u'project_code', u'project_name', u'funded_by_donor', u'funded_by_govt', u'mtef_sector', u'mtef_reference', u'swg', u'sector_objective', u'peap1_pillar', u'peap2_objective', u'peap3_area']: key = model.Session.query(model.Key).filter_by(name=key_name).first() assert key, key_name count = (model.Session.query(model.ClassificationItem) .join(model.EnumerationValue) .filter_by(key=key) ).count() assert count, (key_name, count) # Check there are some entries and none of them are null def test_03_entry(self): dataset_ = (model.Session.query(model.Dataset) .filter_by(name=self.name) ).one() count = (model.Session.query(model.Entry) .filter_by(dataset_=dataset_) ).count() assert count, 'There are no Entries' assert not (model.Session.query(model.Entry) .filter_by(dataset_=dataset_) .filter_by(amount=None) ).first(), 'Some Entries have NULL amounts' # Look for a 'to' field on the first entry in the dataset. def test_04_entry_to(self): dataset_ = (model.Session.query(model.Dataset) .filter_by(name=self.name) ).one() txn = (model.Session.query(model.Entry) .filter_by(dataset_=dataset_) ).first() classif = txn.classification_as_dict() print classif['to'] assert classif['to'] == 'uganda-society' EE....EEE == ERROR: test suite for -- Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py", line 208, in run self.setUp() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py", line 291, in setUp self.setupContext(ancestor) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py", line 314, in setupContext try_run(context, names) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/util.py", line 478, in try_run return func() File "/Users/bteeuwen/Sites/wdmmg/wdmmg/tests/functional/test_aggregate.py", line 8, in setup_class Fixtures.setup() File "/Users/bteeuwen/Sites/wdmmg/wdmmg/lib/cli.py", line 101, in setup from wdmmgext.load import cofog ImportError: No module named wdmmgext.load >> begin captured logging << pylons.configuration: DEBUG: Initializing configuration, package: 'wdmmg' pylons.configuration: DEBUG: Pushing process configuration pylons.configuration: DEBUG: Adding mako engine with alias None and {'myghty.data_dir': '/Users/bteeuwen/Sites/wdmmg/pylons_data/templates', 'mako.directories': ['/Users/bteeuwen/Sites/wdmmg/wdmmg/templates'], 'myghty.component_root': [{'templates': '/Users/bteeuwen/Sites/wdmmg/wdmmg/templates'}], 'kid.encoding': 'utf-8
[Tutor] Script for Parsing string sequences from a file
Hello, I'm doing a biomedical degree and am taking a course on bioinformatics. We were given a raw version of a public database in a file (the file is in simple ASCII) and need to extract only certain lines containing important information. I've made a script that does not work and I am having trouble understanding why. when I run it on the python shell, it prompts for a protein name but then reports that there is no such entry. The first while loop nested inside a for loop is intended to pick up all lines beginning with "gc;", chop off the "gc;" part and keep only the text after that (which is a protein name). Then it scans the file and collects all lines, chops the "gc;" and stores in them in a tuple. This tuple is not built correctly, because as I posted when the program is run it reports that it cannot find my query in the tuple I created and it is certainly in the database. Can you detect what the mistake is? Thank you in advance! Spyros myParser.py Description: Binary data ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Script for Parsing string sequences from a file
On Fri, Apr 15, 2011 at 8:41 AM, Spyros Charonis wrote: > Hello, > > I'm doing a biomedical degree and am taking a course on bioinformatics. We > were given a raw version of a public database in a file (the file is in > simple ASCII) and need to extract only certain lines containing important > information. I've made a script that does not work and I am having trouble > understanding why. > > when I run it on the python shell, it prompts for a protein name but then > reports that there is no such entry. The first while loop nested inside a > for loop is intended to pick up all lines beginning with "gc;", chop off the > "gc;" part and keep only the text after that (which is a protein name). > Then it scans the file and collects all lines, chops the "gc;" and stores > in them in a tuple. This tuple is not built correctly, because as I posted > when the program is run it reports that it cannot find my query in the tuple > I created and it is certainly in the database. Can you detect what the > mistake is? Thank you in advance! > > Spyros > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > import os, string printsdb = open('/users/spyros/folder1/python/PRINTSmotifs/prints41_1.kdat', 'r') lines = printsdb.readlines() # find PRINTS name entries you need to have a list to collect your strings: protnames = [] for line in lines: # this gets you each line #while line.startswith('gc;'): this is wrong if line.startswith('gc;'); # do this instead protnames.append(line.lstrip('gc;')) # this adds your stripped string to the protnames list if not protnames: print('error in creating tuple') # check if tuple is true or false #print(protnames) break query = input("search a protein: ") query = query.upper() if query in protnames: print("\nDisplaying Motifs") else: print("\nentry not in database") # Parse motifs def extract_motifs(query): motif_id = () motif = () while query in lines: for query, get motif_ids and motifs while line.startswith('ft;'): motif_id = line.lstrip('ft;') motif_ids = (motif_id) #print(motif_id) while line.startswith('fd;'): motif = line.lstrip('fd;') motifs = (motif) #print(motif) return motif_id, motif if __name__ == '__main__': final_motifs = extract_motifs('query') -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Script for Parsing string sequences from a file
sorry, I hit send too soon on last message On Fri, Apr 15, 2011 at 8:54 AM, Joel Goldstick wrote: > > > On Fri, Apr 15, 2011 at 8:41 AM, Spyros Charonis wrote: > >> Hello, >> >> I'm doing a biomedical degree and am taking a course on bioinformatics. We >> were given a raw version of a public database in a file (the file is in >> simple ASCII) and need to extract only certain lines containing important >> information. I've made a script that does not work and I am having trouble >> understanding why. >> >> when I run it on the python shell, it prompts for a protein name but then >> reports that there is no such entry. The first while loop nested inside a >> for loop is intended to pick up all lines beginning with "gc;", chop off the >> "gc;" part and keep only the text after that (which is a protein name). >> Then it scans the file and collects all lines, chops the "gc;" and stores >> in them in a tuple. This tuple is not built correctly, because as I posted >> when the program is run it reports that it cannot find my query in the tuple >> I created and it is certainly in the database. Can you detect what the >> mistake is? Thank you in advance! >> >> Spyros >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > import os, string > > printsdb = > open('/users/spyros/folder1/python/PRINTSmotifs/prints41_1.kdat', 'r') > lines = printsdb.readlines() > > # find PRINTS name entries > you need to have a list to collect your strings: > protnames = [] > for line in lines: # this gets you each line > #while line.startswith('gc;'): this is wrong > if line.startswith('gc;'); # do this instead > protnames.append(line.lstrip('gc;')) # this adds your stripped > string to the protnames list > # try doing something like: print protnames # this should give you a list of all your lines that started with 'gc;' # this block I don't understand > if not protnames: > print('error in creating tuple') # check if tuple is true or > false > #print(protnames) > break > > Now, you have protnames with all of your protein names see if above helps. then you have below to figure out query = input("search a protein: ") > query = query.upper() > if query in protnames: > print("\nDisplaying Motifs") > else: > print("\nentry not in database") > > # Parse motifs > def extract_motifs(query): > motif_id = () > motif = () > while query in lines: for query, get motif_ids and motifs > while line.startswith('ft;'): > motif_id = line.lstrip('ft;') > motif_ids = (motif_id) > #print(motif_id) > while line.startswith('fd;'): > motif = line.lstrip('fd;') > motifs = (motif) > #print(motif) > return motif_id, motif > > if __name__ == '__main__': > final_motifs = extract_motifs('query') > > > > -- > Joel Goldstick > > -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help to explain commenting
Hello everybody, I could finally complete succesfully the code I was working with. As I'm quite new to python, many of the things I have in my code are copied from different sources, and I do not undertand all of them, well, I have to deliver this code for a project, and in the best documented way that I could, I already commented all that I know, and I suppouse wrongly in some parts. So the request is, if you can take a look at the code, comment the parts that are not yet commented, correct the errors, and propouse some improvement in the parts you think diserves it. I attach the code in a tgz file, if the attached can not be seen then this link: http://www.chandia.net/compart/NMT-2.4-20110415.tar.gz Thanks in advance to all of you and to the people that already helped me. ___ andrés chandía P No imprima innecesariamente. ¡Cuide el medio ambiente! NMT-2.4-20110415.tar.gz Description: GNU Zip compressed data ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python on TV
"bob gailer" wrote The show should be here - Pause at 1 minute 20 for the Python screnshot: http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 I am told "the video ... cannot be viewed from your currrent country ..." I don't know if YouTube will be any more obliging but try this: http://www.youtube.com/watch?v=oDNZP1X30WE&list=SL Python can be seen at around 29 mins 45 secs... Enjoy (I hope) Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help - accumulator not working (Lea)
Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can't work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help - accumulator not working (Lea)
On Fri, Apr 15, 2011 at 5:52 PM, Lea Parker wrote: > Hello > > > > I am trying to create this program for a uni assignment. I cannot get it to > add the expenses to the accumulator I have set. Would you mind having a look > and letting me know if I have something in the wrong place or indented > incorrectly. Perhaps I am missing something. > > > > There could be other things wrong but I need to fix this first and then I > can focus on the next thing. I have difficulty trying to fix lots of things > at once so if you could just comment on the problem and I will ask again if > I can’t work out the next problem I have. I like to have a go myself first. > J > > > > My code is: > > > > """This program is to calculate if the user is over or under budget > > for the month""" > > > > > > def main(): > > > > # Create an accumulator > > total_expense = 0.0 > > > > # Ask user for the monthly budget > > budget = float(raw_input('Enter the amount of your budget for the > month: $')) > > > above here is good > > > # Calculate a series of expenses > > expense = float(raw_input('Enter your first expense $')) > > > I would remove the input above and move it to your loop. > # Accumlate expense > > total_expense = total_expense + expense > > above you don't need this since you haven't added anything yet (see below) > > I set expense to 1 just to get the loop started. It could be anything but 0 > # Continue processing as long as the user > > # does not enter 0 > > while expense != 0: > > > > #Get another expense > > expense = float(raw_input('Enter the next expense or 0 to finish > $')) > > > > #Calculate surplus > > surplus = budget - total_expense > > > > #Display results > > print 'Your total expenses for the month $', total_expense > > print 'Your surplus amount after expenses $', surplus > > > > # Call the main function. > > main() > > > > Thank you. > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) expense = 1 total_expense = 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus total_expense = total_expense + expense surplus = budget - total_expense print budget, total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus main() Good luck with your course -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help - accumulator not working (Lea)
Hi Lea, how are you today? Well please keep in mind that nothing is "wrong" with your code, its doing exactly what you asked it to do. But I would call your attention to your while loop, you want to accumulate things, but may I ask exactly what are you accumulating in your loop? Also quite by accident I entered 00 as my budget and I got a negative surplus, lol. Perhaps you should implement something that ensures that a (stupid) user like myself does not enter a 0- or negative value for the budget. Just a thought... To help me attempt to understand the small programs I write, I pretend that I'm the computer and I literally compute the program as if I was the interpreter, I follow each line of my code to truly understand it. Perhaps with these gentle nudges you will solve your problem :) What is it about you... that intrigues me so? From: Lea Parker To: tutor@python.org Sent: Fri, April 15, 2011 5:52:22 PM Subject: [Tutor] Help - accumulator not working (Lea) Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can’t work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you.___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help - accumulator not working (Lea)
"Lea Parker" wrote I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. You have to write the code to add each value to the accumulator Your loop does not do that """This program is to calculate if the user is over or under budget for the month""" Wow! Thats a lot of whitespace. It is good to separate code blocks into logical segments with whitespace, but too much of it just makes the code flow hard to see. In the old days of green screen terminals on mainframes they used to say that a function should all fit on a single screen - 24 lines. Nowadays we don't need to be quite so penny pinching, but the concept of seeing the whole flow in one place is a good one. I'll remove some excess space below... def main(): # Create an accumulator Oh, and if you can use a good variable name to describe the variable you don't need a comment either - It's just more distracting wasted space. Comments are to explain *why* (and occasionally, for the really obscure, how), but good names describe what. total_expense = 0.0 budget = float(raw_input('Enter the amount of your budget for the month:')) # Calculate a series of expenses I left this comment because it explains why we have a loop... expense = float(raw_input('Enter your first expense $')) total_expense = total_expense + expense while expense != 0: expense = float(raw_input('Enter the next expense or 0 to finish')) surplus = budget - total_expense print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus main() Hopefully that makes it easier to see what you missed out? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] than "Re: Contents of Tutor digest..." Tutor Digest, Vol 86, Issue 56
Thank you message 4 this has solved my problem I can now work out the next part of my program. Thank you so much. -Original Message- From: tutor-bounces+lea-parker=bigpond@python.org [mailto:tutor-bounces+lea-parker=bigpond@python.org] On Behalf Of tutor-requ...@python.org Sent: Saturday, 16 April 2011 8:47 AM To: tutor@python.org Subject: Tutor Digest, Vol 86, Issue 56 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Help to explain commenting (Andr?s Chand?a) 2. Re: Python on TV (Alan Gauld) 3. Help - accumulator not working (Lea) (Lea Parker) 4. Re: Help - accumulator not working (Lea) (Joel Goldstick) -- Message: 1 Date: Fri, 15 Apr 2011 18:21:43 +0200 From: "Andr?s Chand?a" Subject: [Tutor] Help to explain commenting Message-ID: <957d7e2abbfe95f19b83cef056261697.squir...@mail.chandia.net> Content-Type: text/plain; charset="iso-8859-1" Hello everybody, I could finally complete succesfully the code I was working with. As I'm quite new to python, many of the things I have in my code are copied from different sources, and I do not undertand all of them, well, I have to deliver this code for a project, and in the best documented way that I could, I already commented all that I know, and I suppouse wrongly in some parts. So the request is, if you can take a look at the code, comment the parts that are not yet commented, correct the errors, and propouse some improvement in the parts you think diserves it. I attach the code in a tgz file, if the attached can not be seen then this link: http://www.chandia.net/compart/NMT-2.4-20110415.tar.gz Thanks in advance to all of you and to the people that already helped me. ___ andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -- next part ------ A non-text attachment was scrubbed... Name: NMT-2.4-20110415.tar.gz Type: application/x-gzip Size: 4177 bytes Desc: not available URL: <http://mail.python.org/pipermail/tutor/attachments/20110415/937a8c20/attach ment-0001.bin> -- Message: 2 Date: Fri, 15 Apr 2011 20:35:14 +0100 From: "Alan Gauld" To: tutor@python.org Subject: Re: [Tutor] Python on TV Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "bob gailer" wrote >> The show should be here - Pause at 1 minute 20 for the Python >> screnshot: >> >> http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special >> -part-4 > > I am told "the video ... cannot be viewed from your currrent country > ..." I don't know if YouTube will be any more obliging but try this: http://www.youtube.com/watch?v=oDNZP1X30WE&list=SL Python can be seen at around 29 mins 45 secs... Enjoy (I hope) Alan G. -- Message: 3 Date: Sat, 16 Apr 2011 07:52:22 +1000 From: "Lea Parker" To: Subject: [Tutor] Help - accumulator not working (Lea) Message-ID: <01cbfbb7$666bd140$334373c0$@bigpond.com> Content-Type: text/plain; charset="us-ascii" Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can't work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense
Re: [Tutor] Contents of Tutor digest Vol 86 Issue 57
Hi Michael Scott Thank you and yes I agree there is room for user error. I am going to add a validator but I wanted to get the first part right. I appreciate your comment on the white space too. Being a beginner I find it easier to write the main thing I want the code to do and then add extra to make it work efficiently. Perhaps not what a programmer does but it helps me this way. Thanks so much. Leonie -Original Message- From: tutor-bounces+lea-parker=bigpond@python.org [mailto:tutor-bounces+lea-parker=bigpond@python.org] On Behalf Of tutor-requ...@python.org Sent: Saturday, 16 April 2011 9:43 AM To: tutor@python.org Subject: Tutor Digest, Vol 86, Issue 57 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: Help - accumulator not working (Lea) (michael scott) 2. Re: Help - accumulator not working (Lea) (Alan Gauld) 3. Re: than "Re: Contents of Tutor digest..." Tutor Digest, Vol 86, Issue 56 (Lea Parker) -- Message: 1 Date: Fri, 15 Apr 2011 15:46:32 -0700 (PDT) From: michael scott To: tutor@python.org Subject: Re: [Tutor] Help - accumulator not working (Lea) Message-ID: <670739.27615...@web130203.mail.mud.yahoo.com> Content-Type: text/plain; charset="utf-8" Hi Lea, how are you today? Well please keep in mind that nothing is "wrong" with your code, its doing exactly what you asked it to do. But I would call your attention to your while loop, you want to accumulate things, but may I ask exactly what are you accumulating in your loop? Also quite by accident I entered 00 as my budget and I got a negative surplus, lol. Perhaps you should implement something that ensures that a (stupid) user like myself does not enter a 0- or negative value for the budget. Just a thought... To help me attempt to understand the small programs I write, I pretend that I'm the computer and I literally compute the program as if I was the interpreter, I follow each line of my code to truly understand it. Perhaps with these gentle nudges you will solve your problem :) What is it about you... that intrigues me so? From: Lea Parker To: tutor@python.org Sent: Fri, April 15, 2011 5:52:22 PM Subject: [Tutor] Help - accumulator not working (Lea) Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can?t work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you. -- next part -- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110415/d62c34c3/attach ment-0001.html> -- Message: 2 Date: Sat, 16 Apr 2011 00:27:22 +0100 From: "Alan Gauld" To: tutor@python.org Subject: Re: [Tutor] Help - accumulator not working (Lea) Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Lea Parker" wrote > I am trying to create this program for a uni ass
[Tutor] os.chdir() will not accept string variable
I cannot get os.chdir() to accept inputData[0]. os.chdir() works as expected in the interpreter when I put the little 'r' before the exact same string but as a literal, e.g.: r"F:\Music\Siouxsie and the Banshees\the rapture" When I try to run it I get the following error in reference to the os.chdir() line: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect 'F:\\Music\\Siouxsie and the Banshees\\the rapture\n' Why is it doubling the backslashes and adding '\n' to the end? How do I make it stop? What does the little 'r' mean before a string literal and how do I do the same for a string variable? # mdf -- mp3datafixer import glob, os def mdf(): inputFile = open( 'mdfinputs.txt', 'r' ) inputData = inputFile.readlines() inputFile.close() os.chdir( r'%s' % inputData[0] ) newNames = [] oldNames = glob.glob( '*.*' ) for index, item in enumerate( oldNames ): print index, item if __name__ == '__main__': mdf() raw_input( "\nPress 'enter' to close console window:" ) # Keeps console window open in Windows Thanks! -- Rodney Lewis Please Visit My Homepage: http://www.squidoo.com/dotcomboy ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.chdir() will not accept string variable
On 15-Apr-11 18:00, Rodney Lewis wrote: I cannot get os.chdir() to accept inputData[0]. os.chdir() works as expected in the interpreter when I put the little 'r' before the exact same string but as a literal, e.g.: r"F:\Music\Siouxsie and the Banshees\the rapture" It's because the string in inputData[0] has a trailing newline. WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect 'F:\\Music\\Siouxsie and the Banshees\\the rapture\n' Why is it doubling the backslashes and adding '\n' to the end? How do The actual string value is: F:\Music\Sousie and the Banshees\the rapture When printing it out to you in the error message, Python REPRESENTED that string TO YOU with extra backslash codes so you could see what was in the sring: F:\\Music\\Sousie and the Banshees\\the rapture\n The extra backslashes aren't really in the string. Your problem is that readlines() retains the end-of-line character in the lines it reads, which is not actually part of the filename, so os.chdir() doesn't like it. You'll need to strip off the newlines from the strings you read before giving them to os.chdir(). I make it stop? What does the little 'r' mean before a string literal and how do I do the same for a string variable? It means not to interpret (most) backslash codes in the string as it's compiled from your source code into the internal string data managed by the program. If you wanted to put that string literally in your source code, you could do either of these: 'F:\\Music\\Sousie and the Banshees\\the rapture' or r'F:\Music\Sousie and the Banshees\the rapture' But that's not your problem in this case. You don't need this when reading in lines of data from another source, since they wouldn't get the same backslash interpretation as source lines do. # mdf -- mp3datafixer import glob, os def mdf(): inputFile = open( 'mdfinputs.txt', 'r' ) inputData = inputFile.readlines() inputFile.close() os.chdir( r'%s' % inputData[0] ) newNames = [] oldNames = glob.glob( '*.*' ) for index, item in enumerate( oldNames ): print index, item if __name__ == '__main__': mdf() raw_input( "\nPress 'enter' to close console window:" ) # Keeps console window open in Windows Thanks! -- Steve Willoughby / st...@alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python on TV
On 4/15/2011 3:35 PM, Alan Gauld wrote: "bob gailer" wrote The show should be here - Pause at 1 minute 20 for the Python screnshot: http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 I am told "the video ... cannot be viewed from your currrent country ..." I don't know if YouTube will be any more obliging but try this: http://www.youtube.com/watch?v=oDNZP1X30WE&list=SL Nope. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help - 2nd validator won't work
Hello I now need to get the validator to work on my expense input. If the user puts in a negative I want an error to come up. I have managed it for the budget input but cannot seem to get it to work for the expense. Thanks in advance again for your wonderful help. """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.00 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: ')) # Validation variable for budget while budget <0: print 'ERROR: the budget cannot be a negative amount' budget = float(raw_input('Enter the correct budget for the month: ')) # Ask user for expense expense = float(raw_input('Enter your first expense ')) total_expense += expense # Continue processing as long as the user does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter expense or 0 to finish ')) total_expense += expense # Validation variable for expense while expense <0: print 'ERROR: the budget cannot be a negative amount' expense = float(raw_input('Enter the correct budget for the month: ')) total_expense += expense #Calculate surplus budget_difference = budget - total_expense #Display results print 'Your total expenses for the month ', total_expense if budget_difference>=0: print 'You are under budget by ', budget_difference, 'dollars.' else: print 'You are over budget by ', budget_difference, 'dollars.' # Call the main function. main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor