Re: [Tutor] Python help
[Tutor] Python help IDN3 iradn3777 at gmail.com Thu Aug 13 03:01:12 CEST 2015 Previous message (by thread): [Tutor] revisiting a puzzle about -3**2 vs (-3)**2 Next message (by thread): [Tutor] Python help Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] To whom it may concern, I am having a problem solving the below question. I have used every resource that I could find to help me, but I'm seeing nothing. Can someone out there please help me understand the below question and learn how to accomplish this task in Python? I would really appreciate any help that someone could afford. *Problem 1:* Write a program that will calculate the problem and stop after the condition has been met. a=number of loops (start with zero) b=a+1 c=a+b Condition: If c is less than 5, then the loop will continue; else, it will end. 3. *Problem 2:*Print a string variable that states the number of loops required to meet the condition for Problem 1. My attempt below. I used a while loop even though the question is saying IF/THEN/ELSE. To my knowledge loops in Python have to be while/for. Also, it seems like the question is missing some direction, but I could be wrong. Thank you for your help. a = 0 b = a + 1 c = a + b while (c < 5): print(c) c = c + 1 Yes, I agree the wording of the question is confusing. But I think the following solution makes sense for it. My solution is close to yours, with a few differences: . 1) the variable a will count the number of times the loop goes around. 2) variable a has to be incremented inside the while loop 3) both a and c have to be initialized to zero before the loop starts. 4) after the loop ends, print a string with the variable to tell how many times the loop went a = 0 #increments with each loop c = 0 while (c<5): b = a+1 c = a+b a += 1 print(c) print("Number of loops until c >= 5:", a) I think that is all that is being asked here. HTH! -William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hello there I'm using Python 3.4 running on Ubuntu 14.04LTS I'm new to programming and also new to linux I'm trying to learn the pygame library I was reading : http://programarcadegames.com/index.php?chapter=introduction_to_graphics&lang=en#section_5 On the section on how to draw text the writer has the following code | font ||=||pygame.font.SysFont(||'Calibri'||, ||25||, ||True||, ||False||)| |text ||=||font.render(||"My text"||,||True||,BLACK) ||screen.blit(text, [||250||, ||250||]) When I run the code using the IDLE the Python shell gives me the following error Traceback (most recent call last): File "/home/william/Desktop/Pygame/Python 3X/Drawing_Shapes.py", line 48, in font = pygame.font.SysFont('Calibri', 25, True, False) File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line 614, in SysFont return constructor(fontname, size, set_bold, set_italic) File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line 537, in font_constructor font = pygame.font.Font(fontpath, size) pygame.error: font not initialized I think the problem is that the fonts in Ubuntu are probably stored in a different location than in Windows OS.And therefore python can not find it using the SysFont method Can anyone give me any suggestion on how to edit the code so that I can write text on my graphics? Thank you. | ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Upgrade to 2.4
I compiled Python 2.3.4 from source, but now I would like to upgrade to 2.4. There doesn't seem to be a "make uninstall" target for 2.3.4. Will compiling 2.4 overwrite the older version, or will I have two versions of Python on my system? Thanks, Will ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Upgrade to 2.4
Danny Yoo wrote: On Sat, 4 Dec 2004, William Allison wrote: I compiled Python 2.3.4 from source, but now I would like to upgrade to 2.4. There doesn't seem to be a "make uninstall" target for 2.3.4. Will compiling 2.4 overwrite the older version, or will I have two versions of Python on my system? Hi Will, According to the README, you can install Python 2.4 in a way that doesn't overwrite your older version of Python. Here's a snippet from the README: """ If you have a previous installation of Python that you don't want to replace yet, use make altinstall This installs the same set of files as "make install" except it doesn't create the hard link to "python" named "python" and it doesn't install the manual page at all. """ This should install '/usr/local/bin/python2.4', but otherwise, it should leave the rest of your Python 2.3.4 installation intact. Hope this helps! Yeah, I saw that, but didn't want two versions of Python hanging around. I went ahead and did "make install" for 2.4 and it replaced the previous version. Thanks, Will ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime, time zones, and ISO time
On Wed, Feb 17, 2010 at 12:44:02PM -0600, David Perlman wrote: >I have been really scratching my head over this, it seems like there >*should* be a nice easy way to do what I want but I can't find it for >the life of me. ... >But a) I don't know how to stick the offset info into a datetime >object, and the documentation doesn't seem to say anything about >this; and b) the offset line doesn't work anyway: I think that you need to push in a tzinfo object, rather than a value: http://docs.python.org/library/datetime.html#datetime.tzinfo I get that from here: For applications requiring more, datetime and time objects have an optional time zone information member, tzinfo, that can contain an instance of a subclass of the abstract tzinfo class. These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether Daylight Saving Time is in effect. Note that no concrete tzinfo classes are supplied by the datetime module. Supporting timezones at whatever level of detail is required is up to the application. The rules for time adjustment across the world are more political than rational, and there is no standard suitable for every application.[1] I suspect that it'll take some fooling around to see how it works though - use the interpreter or ipython to test things out. [1] http://docs.python.org/library/datetime.html -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime, time zones, and ISO time
On Wed, Feb 17, 2010 at 03:24:26PM -0600, David Perlman wrote: >But this doesn't help, because then you still don't know whether it's >dst or not. You then would have to jump through whatever >convolutions to do that calculation. > >All I want to know is the *current* offset between local time and >utc. I know the system has this information already; it doesn't >require any kind of fancy calculations about global politics or >anything. Well, does time.timezone help? It returns time offset from UTC in seconds. -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What Editori?
On Wed, Feb 24, 2010 at 04:40:07PM +0100, Giorgio wrote: >And, what about more powerful editors? I mean editors with features like SVN/ >GIT management and so on. I think you'll find that there is extensive version control integration in most/all of the "less powerful" editors. Certainly you would find many who would (perhaps strenuously) refute a suggestion that vi[m]|emacs are not "powerful". Of the many editors mentioned in this thread at least vim, emacs and geany have integration available for any version control system. -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] has it gone quiet or is it just me?
On Wed, Jul 21, 2010 at 06:55:25PM +0100, Alan Gauld wrote: >I haven't had any tutor messages in 2 days. >Do I have a problem or are things just very quiet suddenly? >The archive isn't showing anything either which makes me suspicious. It's not just you. I've been hearing crickets as well. -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Scrabble Help
I'd like to write a program to help find words for Scrabble but I've been having trouble right from the beginning. tiles = 'aeirstw' dictionary = ['aardvark', 'cat', 'dog', 'taste', 'stare', 'wrist'] for word in range(len(dictionary)): for letter in range(len(dictionary[word])): if dictionary[word][letter] in tiles: nothing here quite works I guess what I'm trying to do is step through every letter of every word in my dictionary and if that letter is in my tiles set it aside and compare it back to the dictionary. So in the dictionary above, 'aardvark' would not be included because there is only 1 'a' in my tiles, but 'stare' and 'wrist' should be even though there are letters left over in the tiles. Am I going about this wrong? Should I be looking at some module or a regular expression? Of course any advice is appreciated. Thanks, Will ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Long list error
Hello, I was working on a sieve of eratosthenes and ran into an error I don't understand. >>> size = 100 >>> l = [0,1]*(size/2) Traceback (most recent call last): File "", line 1, in OverflowError: cannot fit 'long' into an index-sized integer Is there a type or something that I can do to prevent this error? Or am I on the wrong track for such large primes? Thanks, William Stephens ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tokenizing Help
I need to be able to decompose a formatted text file into identifiable, possibly named pieces. To tokenize it, in other words. There seem to be a vast array of modules to do this with (simpleparse, pyparsing etc) but I cannot understand their documentation. The file format I am looking at (it is a bibliographic reference file) looks like this: <1> # the references are enumerated AU - some text perhaps across lines AB - some other text AB - there may be multiples of some fields UN - any 2-letter combination may exist, other than by exhaustion, I cannot anticipate what will be found What I am looking for is some help to get started, either with explaining the implementation of one of the modules with respect to my format, or with an approach that I could use from the base library. Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tokenizing Help
On Wed, Apr 22, 2009 at 09:23:30PM +0200, spir wrote: >> I need to be able to decompose a formatted text file into identifiable, >> possibly named pieces. To tokenize it, in other words. There seem to >> be a vast array of modules to do this with (simpleparse, pyparsing etc) >> but I cannot understand their documentation. > >I would recommand pyparsing, but this is an opinion. It looked like a good package to me as well, but I cannot see how to define the grammar - it may be that the notation just doesn't make sense to me. >Regular expressions may be enough, depending on your actual needs. Perhaps, but I am cautious, because every text and most websites discourage regexes for parsing. >The question is: what do you need from the data? What do you expect as result? >The best is to provide an example of result matching sample data. E.G. I wish >as result a dictionary looking like >{ >'AU': 'some text\nperhaps across lines' >'AB': ['some other text', 'there may be multiples of some fields'] >'UN': 'any 2-letter combination may exist...' >... >} I think that a dictionary could work, but it would have to use lists as the value, to prevent key collisions. That said, returning a list of dictionaries (one dictionary per bibliographic reference) would work very well in the large context of my program. >From this depends the choice of an appropriate tool and hints on possible >algorithms. I hope this helps. I spent quite some time with pyparsing, but I was never able to express the rules of my grammar based on the examples on the website. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tokenizing Help
On Wed, Apr 22, 2009 at 05:16:56PM -0400, bob gailer wrote: >> <1> # the references are enumerated >> AU - some text >> perhaps across lines >> AB - some other text >> AB - there may be multiples of some fields >> UN - any 2-letter combination may exist, other than by exhaustion, I >> cannot anticipate what will be found >> >> What I am looking for is some help to get started, either with >> explaining the implementation of one of the modules with respect to my >> format, or with an approach that I could use from the base library. >> > > What is your ultimate goal? These references will populate a django model. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tokenizing Help
On Wed, Apr 22, 2009 at 11:23:11PM +0200, Eike Welk wrote: >How do you decide that a word is a keyword (AU, AB, UN) and not a part >of the text? There could be a file like this: > ><567> >AU - Bibliographical Theory and Practice - Volume 1 - The AU - Tag >and its applications >AB - Texts in Library Science ><568> >AU - Bibliographical Theory and Practice - Volume 2 - The >AB - Tag and its applications >AB - Texts in Library Science ><569> >AU - AU - AU - AU - AU - AU - AU - AU - AU - AU - AU - >AU - AU - AU - AU - AU - AU - AU - AU - AU - AU - AU >AB - AU - AU - AU - AU - AU - AU - AU - AU - AU - AU - >AU - AU - AU - AU - AU - AU - AU - AU - AU - AU - AU >ZZ - Somewhat nonsensical case This is a good case, and luckily the files are validated on the other end to prevent this kind of collision. >To me it seems that a parsing library is unnecessary. Just look at the >first few characters of each line and decide if its the start of a >record, a tag or normal text. You might need some additional >algorithm for corner cases. If this was the only type of file I'd need to parse, I'd agree with you, but this is one of at least 4 formats I'll need to process, and so a robust methodology will serve me better than a regex-based one-off. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Having trouble with a dictionary of lists
I am trying to create a CSV file of sorted similar lists, arranged so that differences are easily compared in a spreadsheet. I am encountering the following error, however: IndexError: list assignment index out of range On the indicated line below. I understand the error, but I don't understand why I am getting it. Can anyone shed some light on this? Thanks. #!/usr/bin/python """ Take a collection of lists, combine them into one list, deleting duplicates. Sort the list and use it as the leftmost column of a table. Then put each lists contents into the table, one per column, with the elements aligned with the leftmost (index) column. """ import os, sys, csv def cmpss(filename,*sslists): """Write a CSV file from the collection of lists.""" if os.path.exists(filename): print("%s exists: please choose another filename." % filename) sys.exit(1) else: try: fn = csv.writer(open(filename, "w")) except IOError: print("There is a problem opening the requested file. Sorry.") sys.exit(1) termdict = {} for sslist in sslists: for term in sslist: termdict[term] = "" termlist = termdict.keys() termlist.sort() sortedtermdict = {} number_of_commas = 1 - len(sslists) for term in termlist: sortedtermdict[term] = ["" for x in range(number_of_commas)] for sslist in sslists: counter = 0 for term in sslist: # The line below is where my program barfs. sortedtermdict[term][counter] = term counter = counter + 1 for row in sortedtermdict: fn.writerow(row) -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Having trouble with a dictionary of lists
On Thu, Sep 03, 2009 at 11:26:35AM -0700, Emile van Sebille wrote: Thanks to Emile for pointing out the error. There were several other errors - initiating the counter in the loop (d'oh!), premature sorting of the dictionary by keys, not providing an index row for the output file, not returning anything from my function, and probably others. Here is how it looks now - any pointers, stylistic or otherwise, are welcome. It does, however, work. #!/usr/bin/python """ Take a collection of lists, combine them into one list, deleting duplicates. Sort the list and use it as the leftmost column of a table. Then put each lists contents into the table, one per column, with the elements aligned with the leftmost (index) column. """ import os, sys, csv def cmpss(filename,*sslists): """Write a CSV file from the collection of lists.""" if os.path.exists(filename): print("%s exists: please choose another filename." % filename) sys.exit(1) else: try: fn = csv.writer(open(filename, "w")) except IOError: print("There is a problem opening the requested file. Sorry.") sys.exit(1) toprow = [x for x in range(len(sslists))] toprow.insert(0, "index") fn.writerow(toprow) termdict = {} number_of_columns = len(sslists) for sslist in sslists: for term in sslist: termdict[term] = ["" for x in range(number_of_columns)] sortedtermlist = termdict.keys() sortedtermlist.sort() counter = 0 for sslist in sslists: for term in sslist: #debug print(counter) #debug print(term) termdict[term][counter] = term counter = counter + 1 for term in sortedtermlist: row = [term] row.extend(termdict[term]) fn.writerow(row) return termdict -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Having trouble with a dictionary of lists
On Fri, Sep 04, 2009 at 09:54:20AM -0700, Emile van Sebille wrote: >On 9/4/2009 9:09 AM William Witteman said... >>On Thu, Sep 03, 2009 at 11:26:35AM -0700, Emile van Sebille wrote: >> >>Thanks to Emile for pointing out the error. There were several other >>errors - initiating the counter in the loop (d'oh!), premature sorting >>of the dictionary by keys, not providing an index row for the output >>file, not returning anything from my function, and probably others. >> >>Here is how it looks now - any pointers, stylistic or otherwise, are >>welcome. It does, however, work. > >That's normally when I stop looking at it. If I'm lucky, I'll never >need to work on it again. If and when I do, that's when I clean it >up in the area that needs attention. It's way to easy IMHO to turn >one-off projects into time-sinks. > >Anyway, some notes interspersed below... Thanks! >> toprow = [x for x in range(len(sslists))] > >This looks like toprow is simply range(len(sslists))... Yes, until this next row... >> toprow.insert(0, "index") >> termdict[term] = ["" for x in range(number_of_columns)] > >this might also be said [""]*number_of_columns I was concerned that this would give me this: [""],[""],[""] rather than this: ["","",""] I see now that it doesn't but the list comprehension seems really fast compared to the multiplication. Is that true? -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Recursive user input collection problem
I need to collect a couple of integers from a user, but I want to make sure that I actually get integers. I tried this, but subsequent calls to the function don't update variable. I'm not sure this is terribly clear - here's the code: num_of_articles = 0 num_of_reviewers = 0 def getinput(variable,prompt): """ Get the input by prompting the user and collecting the response - if it is a non-integer, try again. """ variable = 0 variable = raw_input(prompt) try: int(variable) return variable except ValueError: print("We need an integer (number) here.") getinput(variable,prompt) num_of_articles = getinput(num_of_articles,"Enter number of articles: ") num_of_reviewers = getinput(num_of_reviewers,"Enter number of reviewers: ") print(num_of_articles) print(num_of_reviewers) This works fine if I put in good input, but not if I pass in a bad value. Can anyone show me where I have gone astray? Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursive user input collection problem
Thanks to all who responded. There were several good points about the code itself, all of which both helped and work. I will likely use Alan's example because I find it the most lucid, but the other suggestions are good signposts to other ways to do the same thing (but right, as opposed to how I was doing it). Lie's suggestion that I didn't understand the calling structure of Python was right on the money, and his included link helps with that, too. Thanks again. -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursive user input collection problem
On Thu, Oct 15, 2009 at 07:54:23AM -0400, Dave Angel wrote: >William Witteman wrote: >>Thanks to all who responded. There were several good points about the >>code itself, all of which both helped and work. >> >>I will likely use Alan's example because I find it the most lucid, but >>the other suggestions are good signposts to other ways to do the same >>thing (but right, as opposed to how I was doing it). >> >>Lie's suggestion that I didn't understand the calling structure of >>Python was right on the money, and his included link helps with that, >>too. Thanks again. >You need a loop, and putting a while True: around the whole thing >solves it nicely. Don't *call* the function again, just loop back >and do the operation again. That's what loops are for. True, that's why my code currently looks like this: def getinput(prompt): """ Get the input by prompting the user and collecting the response - if it is a non-integer, try again. """ while True: try: return int(raw_input(prompt)) except ValueError: print("We need an integer (number) here.") >Incidentally, learning about recursion is a very good thing, and >useful. I just don't think it's the right answer here. I wasn't learning about recursion - I have to use it fairly often, but you are right that it isn't the right approach here. -- yours, William ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] database applications with Python - where to start
On Thu, May 05, 2005 at 02:03:30PM +0100, Barnaby Scott wrote: >Hi, this is one of those difficult questions about where to start! > >I want to create a book-keeping/accounting application for my own use >1. because I can't find any that suits me, and >2. because I want to improve and extend my knowledge of Python. Good reasons for doing something - just remember that, as you are discovering, this is a pretty extensive project, and the reasons need to be good enough if you are to finish. >Clearly this is going to be a database application - the trouble is, that >despite reading loads of stuff (including previous posts here on the topic), >I get a Catch-22 feeling that I need to be an expert with 'the big picture' >before I can even take my first stumbling steps towards becoming that >expert! This is a very reasonable response when you look at a project and begin to appreciate its complexities. I am the opposite of a Python expert (most of the code I read leaves me with questions and confusion - that's why I'm lurking here), but I know something about problem-solving. Here is an approach that may help: Programming is, by definition, something that can be decomposed into smaller problems. When you are thinking about your project, write everything you think of down. Once it is written down, attempt to break up your notes into categories - features, behaviours, functional activities of the finished product. This does not need to take a long time. Once you think you have a collection of things you need from your project (these are called Requirements by many), try to organize them by type: data storage, data manipulation, human interfaces, computer systems interfaces, etc. Now, take one of these aspects at a time, and try to quantify what exactly this piece of the project needs to do - for example, write data into a database. Once you have in your head a clear picture of one activity of your program, write a small piece of code that does what you want. If it doesn't work, ask for help - small problems are easier to solve (generally) than big ones, and always easier to ask for help about. Something that helps is to make each proof of concept script with a name that relates back to your Requirements document - so you know by the file name how it fits in the whole project. At some point you will have to commit to which tools you are going to use (database, language, interface, etc.). For your first major project, try to use what you know, or what you have the best support systems in place for - local gurus, lists, user groups etc. Even while you commit to one set of tools, try to think of your program as a set of interacting pieces that can be abstracted from one another, so if you need to change one piece the whole structure doesn't collapse (this is called "loose coupling"). >how/where to start. I'm tempted to try to put together a 'kit' of tools (as >visual as possible) to emulate what I'm used to - but is this a good idea? >and if so, which tools? Tool kits are very worthwhile - once you have code that works, you'll reuse it a lot. Which tools comes down to an optimization of your ability and comfort, your support network and features. > What on earth is my application's model going to >look like? should I get involved with object-relational mapping? If it will gain you something yes, if you don't understand what the gains are or how to implement them, probably not. >how much work should I delegate to the RDBMS, and how much logic should >I code in Python? If you decide at some other point to change databases, delegating core functions to the database may hurt. If you decide to re-write your project in C later, you may regret not handing some things to the database. In all cases, try not to reinvent the wheel habitually, but only where it serves a purpose (learning how it works is a purpose). >Should I even be thinking radically and ditch the RDBMS in favour of >something like a 'Prevalence Layer' that I have read about? what should >inform these decisions? What do you *really* understand, and what can you implement without having an aneurysm. >I just don't know where to start! A book perhaps, but then, which one? Or >maybe an example app for me to pick apart and learn from? Look for an Open Source app that almost works the way you need it to, and look at how it's done. You may find that getting involved with an existing project will get you the features you need sooner than building something from scratch, and by getting involved you can learn a lot. >Sorry it is such a vague question, but any pointers gratefully received. Vague questions are hard to answer specifically, but they are often worth asking. You may find more success decomposing your vague questions into specific sub-questions - they ar
[Tutor] Python versions and Debian?
I am just beginning to experiment with Python, and I'm looking for advice about versions. Debian testing provides version 2.3 by default, (/usr/bin/python is linked to /usr/bin/python2.3) but I am able to install 2.4 as well. What gains do I realize by using the more modern version? Are there gotchas based on that minor-version change? Your insight is appreciated, thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] *nix-specific Python Scripting
I am trying to learn Python by translating some of my Perl scripts. One thing that is eluding me is assigning the results of system calls to variables. Here's what I want to do in Perl: $isxrunning = `ps -C startx | grep "startx"`; if ($isxrunning =~ "startx") { do something; } else { do something else; } It is a simple check to see if the X server is running (this is inelegant, but it works - if you have a better way, I'd love to know about it, but I would like to be able to do things like this in Python - so I might better write scripts with it). My experiments have lead me to the os.exec* collection of methods, and they seem fine, but they don't (as far as I understand them, which isn't very far) allow me to string piped commands or complex collections of switches together in the way that Perl's backticks does. Don't get me wrong, I'm in this to find out how things of this ilk are done in *Python* (if I wanted to know how this was done in Perl, I'd be asking somewhere else), I'm not whining for features. Does Python have a means of doing what I want, or do I construct my command lines in pieces and hand them to os.execl one at a time? Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] *nix-specific Python Scripting
On Thu, May 12, 2005 at 09:37:03PM +0200, Roel Schroeven wrote: >William O'Higgins wrote: >> It is a simple check to see if the X server is running (this is >> inelegant, but it works - if you have a better way, I'd love to know >> about it, but I would like to be able to do things like this in Python - >> so I might better write scripts with it). > >Checking for startx doesn't work if the server is started via xdm (or >kdm or gdm). Another solution would be to check for the DISPLAY >environment variable, though that solution has problems of it's own. Absolutely true. However, in this context I can be assured that if X is running, it was started by startx. More importantly, the DISPLAY environment variable is not usually imported into the shell/process running a script - exporting ENV willy-nilly into sub-processes and spawned shells is, from a security standpoint, very, very bad. I could just as easily look for X itself, which is more foolproof, but I am only looking to stump a small sub-set of possible fools. The set of all fools is said to be unbounded, making proof against them non-trivial. Still, I appreciate the advice and suggestions. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Perl to Python phrasebook
On Fri, May 13, 2005 at 10:39:55AM -0700, Terry Carroll wrote: >A "Perl-to-Python phrasebook," showing a number of common tasks in Perl, >and how to do the equivalent in Python, is at ><http://llama.med.harvard.edu/~fgibbons/PerlPythonPhrasebook.html>. > >I'll bet a lot of readers know about it already, but I just stumbled on it >and thought that some readers might also find it useful. That's excellent, thank you Terry! My hovercraft is no longer full of eels! -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Testing for commandline args
I am writing a tiny commandline utility (re-writing it from Perl) and I want the behaviour to change based on the presence of arguments. The conditional in Perl looks like this: if (defined $ARGV[0]) { do stuff } else { do different stuff In Python I've nearly been successful, but something's wonky. Here's the code: if sys.argv[1]: do stuff else: do different stuff If I have arguments, the "different stuff" happens beautifully, thank you very much. If I don't have arguments I get this: if sys.argv[1]: IndexError: list index out of range] So I'm doing something wrong. I looked at getopt, but that seemed to be doing what I was already doing, except in a way I could not follow :-( Any tips would be appreciated, thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Lists of files
Here's the problem - I want a list (array) of the files in a directory, and then I want to iterate over the list testing for image-ness (with imghdr.what()) and put all the image filenames in a global list. What I've tried is this: files = glob.glob('*.*') for file in files: global pics pics = [] if imghdr.what(file): # so far so good - file is a list of files in the directory pics.append(file) # I this this is the problem - my list only has the last # alphabetical entry in it So there's two questions - is there a better way to create a list of files in a directory? And, how do I populate my list to get all of the filenames. I've also tried "pics + [file]", but that gave me an empty list. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists of files
Thanks to all who helped me with my questions regarding testing for commandline arguments and list assignment. I have finished my first Python program (included below). It is slightly more secure than the Perl program I rewrote, but also about a tenth of a second slower (0.6 seconds for Perl on average (100 trials) and 0.7 seconds for Python). Is that typical of Python programs? I like Python so far, and I'm not going to go crazy optimizing working code, but I am curious. Any pointers, suggestions, etc. are welcome. One last thing - is there an equivalent of the "use strict" and "use warnings" pragmas in Python? Thanks. -- yours, William #!/usr/bin/python import os, sys, random, imghdr # This is a little program I call via cron to change my desktop every # few minutes. With no arguments it goes to my directory of backdrop # images and picks a valid image at random. If I specify a path and a # file the program will put it up as the display. # I don't want to fill up my inbox with emails from cron telling me that # X isn't running, so I check first. xisrunning = os.popen("pidof /usr/bin/X11/X").read() def changebackdrop(): # The below command works for transparent Eterm or Urxvt terminals, # populating their backgrounds with the image they occlude. xli or # xsetroot can be called, but they don't work as desired for # transparent terminals. command = "/usr/bin/Esetroot" # If I was logging into X remotely, this would change. commandargs = " -display :0.0 " # This is where my backdrops live picdir = "/home/willyyam/misc/bmps/" if sys.argv[1:]: doit = command + commandargs + sys.argv[1] os.popen(doit, 'r') else: files = os.listdir(picdir) os.chdir(picdir) pics = [] for file in files: # This is a test for valid images - it includes rgb files, # which are not supported by my image software, but the # error thrown is not terrible - the image software knows # what it can and cannot run. if imghdr.what(file): pics.append(file) randpic = random.choice(pics) doit = command + commandargs + picdir + randpic os.popen(doit, 'r') if xisrunning: changebackdrop() else: exit signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] dictionary values in strings
I am trying to discover the syntax for call on a dictionary of lists by key and index. The data structure looks like this: dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ 'key3':['li1'li2,'li3','']} The keys are passed to a function as arguments, and I want the value of the specified list index. This is what I *thought* it would look like: dol.key(argument)[0] # would return li1 when argument equals key1 But that's wrong. The error I get is this: AttributeError: 'dict' object has no attribute 'key' I don't know how to interpret that error (well, I know I screwed up, but ... :-) Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary values in strings
On Thu, May 19, 2005 at 09:47:50PM +0100, Max Noel wrote: > >On May 19, 2005, at 20:49, William O'Higgins wrote: > >>I am trying to discover the syntax for call on a dictionary of >>lists by >>key and index. >> >>The data structure looks like this: >> >>dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ >>'key3':['li1'li2,'li3','']} >> >>The keys are passed to a function as arguments, and I want the >>value of >>the specified list index. This is what I *thought* it would look >>like: >> >>dol.key(argument)[0] # would return li1 when argument equals key1 >What you are looking for can be achieved like this: > >>>> dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ >... 'key3':['li1', 'li2','li3','']} >>>> dol['key1'][0] >'li1' Ah, of course, it makes sense that an associative array, referenced one array at a time, would use array notation. Ah, crap, I'm speaking Perl again. Make that "it makes sense that a linked list, referenced one list at a time, would use list notation". Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] creating files on open()
When I am open()-ing a file, I sort of expect that if the file doesn't exist that it would be created, but it doesn't, it whines about it instead. So, how do I create a file with Python? I've looked all over, but I'm obviously missing something. Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating files on open()
On Fri, May 20, 2005 at 01:48:19PM -0500, Kristian Zoerhoff wrote: >On 5/20/05, William O'Higgins <[EMAIL PROTECTED]> wrote: >> When I am open()-ing a file, I sort of expect that if the file doesn't >> exist that it would be created, but it doesn't, it whines about it >> instead. So, how do I create a file with Python? I've looked all over, >> but I'm obviously missing something. Thanks. > >How are you opening the file? It will be created if you open in write >or append mode (w or a), but not in read-only (r) mode. Fascinating. I was opening the file read-write (r+) and it didn't work. Are there only the few file-access methods (read (r), write (w), append (a) and read-write (r+))? Sometimes I like to prepend or to clobber or to address in binary mode - are these things possible, or do I have to seek() to prepend and delete to clobber? Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] strip is deprecated, so what do I use?
As the subject says, I was looking for an analog to chomp, and found strip() and friends (rstrip() and lstrip()), but they are deprecated. I'm happy to forgo their use in preparation for 3.0 (I figure we're going to live the rest of our lives in the future, we might as well be ready) but I need an alternative syntax today, and I haven't been able to see what I should use instead. Anyone have a suggestion? -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Wizards in Tkinter
I am writing a small application that takes a user through a set of steps - like a wizard. What I need is an idea how I can start with a window, have the use click "Next" and get another window. My understanding is that it is undesirable to have more than one mainloop per program. Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] strip is deprecated, so what do I use?
On Tue, May 24, 2005 at 01:16:21PM -0400, Michael P. Reilly wrote: > On 5/24/05, William O'Higgins <[EMAIL PROTECTED]> wrote: > > As the subject says, I was looking for an analog to chomp, and found > strip() and friends (rstrip() and lstrip()), but they are deprecated. > I'm happy to forgo their use in preparation for 3.0 (I figure we're > going to live the rest of our lives in the future, we might as well be > ready) but I need an alternative syntax today, and I haven't been able > to see what I should use instead. Anyone have a suggestion? > > William, > > These were all changed to object-oriented syntax on the string value > itself. > Old way string.strip(' abcd ') > New way ' abcd '.strip() > > It may take a little getting used to, but the functionality is the same > and it is more in keeping with how we should be treating the built-in data > values as objects just like we do with class instances. Perfect, and it make a lot of sense. Heck, I find this much more readable in terms of nested calls. Thank you. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Expression order problem
I am running into problems with script evaluation order - specifically, the Python interpreter seems to read and execute scripts line by line. This is a problem if you are used to Perl, where the whole script is parsed first (Perl also auto-vivifies variables, but that's a different problem for a different day). Here is a test script: #!/usr/bin/python import sys class test: variable = "is this a variable" + other_argument if sys.argv[1:]: argument = sys.argv[1] other_argument = sys.argv[2] instance = test() print instance.variable else: sys.exit() I am only beginning to get my head around OO programming, so please bear with me. In Perl, I would define all of my subs (functions or classes) at the end of the program, because the Perl parser will read the whole program, and then execute it. So I'm having trouble from the start because I can't do that - the interpreter whines about undefined calls when things are defined further down the page. In my example though - I want to use variables from one code block in another, but whichever one is first, something is undefined. I'm not necessarily looking for a fix, but pointers as to technique to avoid this would be appreciated. Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Where to start?
Here's what I'm trying to accomplish; I track statistics at work. E.g. calls out, $ collected etc.. The graph has a rough guess of highest possible at the top and the lowest number in the past 3 months at the bottom. It's a simple line graph, week after week. I need to be able to add names of various statistics. I.e. calls out, money collected, proposals sent etc.. It then needs to create the graph, store the names, be able to take the week's numbers and store them along with being able to print. The highest and lowest points also need to also be inputed and changed if needed. Ideally this would be a GUI driven app for the sake of simplicity. What I'm looking for is advice on where to start, a middle ground and an end. I'm new to Python and programming and took this as the 1st thing I'd to create. I've been studying for a bit now and knowing where I'm going would be very helpful. -- "Microsoft isn't evil, they just make really crappy operating systems." -Linus Torvalds ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 48, Issue 2
Thanks! I'll get to work! "Microsoft isn't evil, they just make really crappy operating systems." -Linus Torvalds [EMAIL PROTECTED] wrote: > 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 > [EMAIL PROTECTED] > > You can reach the person managing the list at > [EMAIL PROTECTED] > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > >1. matrix-vector multiplication errors (Dinesh B Vadhia) >2. Where to start? (William Kilmartin) >3. Re: Where to start? (Alan Gauld) > > > -- > > Message: 1 > Date: Fri, 1 Feb 2008 14:13:00 -0800 > From: "Dinesh B Vadhia" <[EMAIL PROTECTED]> > Subject: [Tutor] matrix-vector multiplication errors > To: > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="iso-8859-1" > > I've posted this on the Scipy forum but maybe there are answers on Tutor too. > I'm performing a standard Scipy matrix* vector multiplication, b=Ax , (but > not using the sparse module) with different sizes of A as follows: > > > Assuming 8 bytes per float, then: > 1. matrix A with M=10,000 and N=15,000 is of approximate size: 1.2Gb > 2. matrix A with M=10,000 and N=5,000 is of approximate size: 390Mb > 3. matrix A with M=10,000 and N=1,000 is of approximate size: 78Mb > > The Python/Scipy matrix initialization statements are: > >> A = scipy.asmatrix(scipy.empty((I,J), dtype=int)) >> x = scipy.asmatrix(scipy.empty((J,1), dtype=float)) >> b = scipy.asmatrix(scipy.empty((I,1), dtype=float)) >> > > I'm using a Windows XP SP2 PC with 2Gb RAM. > > Both matrices 1. and 2. fail with INDeterminate values in b. Matrix 3. works > perfectly. As I have 2Gb of RAM why are matrices 1. and 2. failing? > > The odd thing is that Python doesn't return any error messages with 1. and 2. > but we know the results are garbage (literally!) > > Cheers! > > Dinesh > -- next part -- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20080201/5c3abb34/attachment-0001.htm > > > -- > > Message: 2 > Date: Fri, 01 Feb 2008 20:52:39 -0800 > From: William Kilmartin <[EMAIL PROTECTED]> > Subject: [Tutor] Where to start? > To: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Here's what I'm trying to accomplish; > > I track statistics at work. E.g. calls out, $ collected etc.. > > The graph has a rough guess of highest possible at the top and the > lowest number in the past 3 months at the bottom. > > It's a simple line graph, week after week. > > I need to be able to add names of various statistics. I.e. calls out, > money collected, proposals sent etc.. > > It then needs to create the graph, store the names, be able to take the > week's numbers and store them along with being able to print. The > highest and lowest points also need to also be inputed and changed if > needed. > > Ideally this would be a GUI driven app for the sake of simplicity. > > What I'm looking for is advice on where to start, a middle ground and an > end. I'm new to Python and programming and took this as the 1st thing > I'd to create. > > I've been studying for a bit now and knowing where I'm going would be > very helpful. > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Guess my number game
I have been trying to write a guess my number game (using Michael Dawsons book), where the computer guesses the number that I thought of. Here is my code so far,#The Guess My Number Game ##The computer picks a random number between 1 and 50#The player tries to guess it and the computer lets#the player know if the guess is too high, too low#or right on the money#If the player fails to guess the number after 5 tries #the game ends and the computer prints a chastising message#print "\t\t\tWelcome to \"Guess My Number\"!"import randomprint "\nThink of a number between 1 and 50." print "I will try to guess it in as few attempts as possible.\n"number = input ("Enter the number: ")#the computer guesses the number using the random functionguess = random.randrange (50) + 1tries = 1#FIXMEwhile (guess != number): if (guess > number): print "You chose", guess, "the number is Lower ..." else: print "You chose", guess, "the number is Higher ..." guess = random.randrange (50) + 1 tries += 1print "You guessed it! The number was", numberprint "And it only took you", tries, "tries!\n"raw_input ("Press to exit.") The program works ok, but the computer sometimes repeats the same numbers when asked to guess. How can I rewrite it so that it guesses like what a human being does i.e. if the number is less than 20, you do not guess numbers above 20. Thanks for your help. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python app and UNIX commands
Hello, I have come up with an idea of an app that I would like to write using python but I need some guidance. I would like to write an app for Linux/Unix that fetches a gzipped or bzipped file from a remote server by http or ftp. The file will be downloaded to a temporary directory, unzipped and its contents copied to specific directory. If the process has gone well, the files in the temporary directory are cleaned up. To do this, I guess I would have to mingle python with some UNIX commands. How do I intermingle python and unix commands? I have read most of Michael Dawsons book but unfortunately it doesn't have this kind of stuff. I have just bought Magnus Lie Hetland's book and just started going through it. Any other recommendations will be appreciated. Thanks. Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Invoking bash from python
I'd like to write an app that helps a user install a program on Linux after fetching it from a remote site. The program is packaged as a bin file and when run from bash, the user has to agree to a licence agreement by entering "y" or "n" and enter a path for installation. It seems like I need to find a way for my program to invoke bash so that the user can enter the input required. So far, I've figured out that I can use urllib to fetch the file and the commands module to execute some system commands. Any ideas on how I can envoke bash and pass on the users input to bash. Thanks for your input.Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Invoking bash from python
I think I found a solution to my problem and thats to use the os module (os.system function). I'm still open to any suggestions you may have.--WillOn 8/7/06, William Mhlanga <[EMAIL PROTECTED]> wrote: I'd like to write an app that helps a user install a program on Linux after fetching it from a remote site. The program is packaged as a bin file and when run from bash, the user has to agree to a licence agreement by entering "y" or "n" and enter a path for installation. It seems like I need to find a way for my program to invoke bash so that the user can enter the input required. So far, I've figured out that I can use urllib to fetch the file and the commands module to execute some system commands. Any ideas on how I can envoke bash and pass on the users input to bash. Thanks for your input.Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] <> and chomp
Hi, I'm new to programming and started with Perl but have been reading a lot of good things about Python. Thought I would switch before I have too much time invested in Perl. Anyway, my question is, is there something in Python similar to the diamond operator and chomp from Perl? I'm trying to read in from a file line by line and get rid of the '\n' at the end of each line. Thanks, Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] <> and chomp
Thanks for all the responses guys. I was actually able to figure out the infile = open('infilename.txt', 'r') for line in infile: Just wasn't sure if it was Pythonic or not. Had no clue about the line = line.rstrip('\n') so thanks again. I'll get to reading those links. P.S. David, I'm sure you're right. I'll eventually learn both. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Better way to substitute text?
Hi, Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, on to the question. Is there a better way to implement the code below? It scans a saved html file and highlights certain keywords is a bold, red font. It works, but I suppose I'm wondering if it's the "Pythonic" way. Thanks, Will #!/usr/bin/env python in_put = open('test.html', 'r') out_put = open('test_highlight.html', 'a') for line in in_put: line = line.replace("TWY", "TWY") line = line.replace("RWY", "RWY") line = line.replace("WIP", "WIP") out_put.write(line) in_put.close() out_put.close() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better way to substitute text?
Shantanoo Mahajan wrote: > +++ William Allison [29-09-06 18:55 -0400]: > | Hi, > | Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, on to > | the question. Is there a better way to > | implement the code below? It scans a saved html file and highlights > | certain keywords is a bold, red font. It works, > | but I suppose I'm wondering if it's the "Pythonic" way. > | Thanks, > | Will > | > | #!/usr/bin/env python > | > | in_put = open('test.html', 'r') > | out_put = open('test_highlight.html', 'a') > > = > | for line in in_put: > | line = line.replace("TWY", " | color='#FF'>TWY") > | line = line.replace("RWY", " | color='#FF'>RWY") > | line = line.replace("WIP", " | color='#FF'>WIP") > | out_put.write(line) > = > | > | in_put.close() > | out_put.close() > > > replace_words = ['TWY', 'RWY', 'WIP'] > for line in in_put: > for replace_word in replace_words: > out_put.write(line.replace(replace_word," color='#FF'>"+replace_word+"")) > > You can furthur reduce for loops. > > Shantanoo > Thanks Shantanoo, I like that a lot better. Had to modify it just a little. replace_words = ['TWY', 'RWY', 'WIP'] for line in in_put: for replace_word in replace_words: line = line.replace(replace_word, "" + replace_word + "") out_put.write(line) I can never quite get when to use a nested loop. Thanks again, Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better way to substitute text?
Thanks David, I like that better than my original. I'll remember to NOT split the input file into lines in the future. Will David Heiser wrote: > You can make it simpler by not splitting the input file into lines. > Treat it as a single string. > > in_put = open('test.html', 'r').read() > > replace_words = ['TWY', 'RWY', 'WIP'] > for replace_word in replace_words: > in_put = in_put.replace(replace_word, " color='#FF'>" + replace_word + "") > > open('test_highlight.html', 'a').write(in_put) > > > > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On > Behalf Of William Allison > Sent: Saturday, September 30, 2006 8:10 AM > To: tutor@python.org > Subject: Re: [Tutor] Better way to substitute text? > > > Shantanoo Mahajan wrote: > >> +++ William Allison [29-09-06 18:55 -0400]: >> | Hi, >> | Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, >> | on to >> | the question. Is there a better way to >> | implement the code below? It scans a saved html file and highlights >> > > >> | certain keywords is a bold, red font. It works, >> | but I suppose I'm wondering if it's the "Pythonic" way. >> | Thanks, >> | Will >> | >> | #!/usr/bin/env python >> | >> | in_put = open('test.html', 'r') >> | out_put = open('test_highlight.html', 'a') >> >> = >> | for line in in_put: >> | line = line.replace("TWY", "> | color='#FF'>TWY") >> | line = line.replace("RWY", "> | color='#FF'>RWY") >> | line = line.replace("WIP", "> | color='#FF'>WIP") >> | out_put.write(line) >> = >> | >> | in_put.close() >> | out_put.close() >> >> >> replace_words = ['TWY', 'RWY', 'WIP'] >> for line in in_put: >> for replace_word in replace_words: >> out_put.write(line.replace(replace_word,"> color='#FF'>"+replace_word+"")) >> >> You can furthur reduce for loops. >> >> Shantanoo >> >> > > Thanks Shantanoo, > I like that a lot better. Had to modify it just a little. > > replace_words = ['TWY', 'RWY', 'WIP'] > for line in in_put: >for replace_word in replace_words: > line = line.replace(replace_word, " color='#FF'>" + replace_word + "") > out_put.write(line) > > I can never quite get when to use a nested loop. > Thanks again, > Will > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question
Caicedo, Richard IT2 NSWC wrote: > > I am trying to get the $ python promt I can't seem to get it. I can > get the python shell but when I press enter I don't get the $ python? > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > The $ is probably referring to the BASH prompt at which you would type the command python to bring up the interactive interpreter. Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] datetime.timedelta Output Format
Is there a way to have the output of "print tis" in the same format as "print now" and "print tafmsd" in the code below? Thanks, Will savage:~ wallison$ python Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> now = datetime.date.today() >>> print now 2007-04-01 >>> tafmsd = datetime.date(1994, 2, 23) >>> print tafmsd 1994-02-23 >>> tis = now - tafmsd >>> print tis 4785 days, 0:00:00 >>> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime.timedelta Output Format
Alan Gauld wrote: > "R. Alan Monroe" <[EMAIL PROTECTED]> wrote > > >>> Is there a way to have the output of "print tis" in the same format >>> as >>> "print now" and "print tafmsd" in the code below? >>> > > >>> >>> now = datetime.date.today() >>> >>> print now >>> 2007-04-01 >>> >>> tis = now - tafmsd >>> >>> print tis >>> 4785 days, 0:00:00 >>> > > >> That's kind of like asking how to say "128 shopping days left until >> Christmas" in the format of "2007-04-01 shopping days left until >> Christmas". It doesn't work, somehow. >> > > I assume that what Will really means is how does he > get the number of days expressed as a number of > years/months and days. > > As in: There are 4 months, 8 days to Xmas. > Yes, that's correct. Sorry I didn't express myself clearly. Thanks again, Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime.timedelta Output Format
Kent Johnson wrote: > > It looks like Gustavo Niemeyer's dateutil module will at least do the > year/month/day calculation if not the formatting: > > In [1]: from datetime import date > In [2]: from dateutil import relativedelta > In [3]: now = date.today() > In [9]: rd = relativedelta.relativedelta(now, tafmsd) > In [10]: rd > Out[10]: relativedelta(years=+13, months=+1, days=+10) > > http://labix.org/python-dateutil > > Kent > Thank you, seems to be just what I was looking for! Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need a Clean Start
Keegan Johnson wrote: > I need to get the pygames, py2app, etc on my computer > (I have a Macintosh). Is there any way to clean up all these files > that I've accrued trying to get things to work? I've been able to do > a little bit but nothing more than that. Also, what should I use? > There's lots of different versions different sites recommend. Anyone > willing to authoritatively decide? > Thanks a million for any help at all, > Keegan > Not sure what you've accrued trying to get things to work so can't tell you how to clean them all up. But sounds like you might want to check out easy_install, it lets you install, upgrade, and uninstall Python packages. You can even have a "custom installation location" such as in your home directory. http://peak.telecommunity.com/DevCenter/EasyInstall As far as which version to use, I think I read somewhere that the latest version of Python is typically the best version of Python. Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How Compute # of Days between Two Dates?
Wayne Watson wrote: > That's the question in Subject. For example, the difference between > 08/29/2008 > and 09/03/2008 is +5. The difference between 02/28/2008 and 03/03/2008 is 4, > leap year--extra day in Feb. I'm really only interested in years between, > say, > 1990 and 2050. In other words not some really strange period of time well > outside our current era of history. I've used the datetime module to do something similar. Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> today = datetime.date.today() >>> print today 2008-09-01 >>> last_year = datetime.date(2007, 9, 1) >>> print today - last_year 366 days, 0:00:00 >>> HTH, Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] New user Knows nothing about python I Need HELP
hello I am trying to make a math functions program which includes ADDITION: 2+2=4 SUBTRACTION: 4-2=2 MULTIPLICATION: 4*2=8 DIVISION: 4/2=2 EXPONENT: 2**3=8 REMAINDER: 5%2=1 I have no Idea how to start this task I have never used ANY programming programs before And I dont Know the language either The online help files from python Did not help a bit please help thank you___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question on how to do exponents
Hello everyone, I am making a calculator and I need to know how to make it do exponents and remainders How can I input this info in python? Any help would be appreciated Thanks --- On Mon, 2/6/12, Steven D'Aprano wrote: From: Steven D'Aprano Subject: Re: [Tutor] Sandbox Game To: "tutor" Date: Monday, February 6, 2012, 7:50 PM On Mon, Feb 06, 2012 at 09:13:48AM -0500, Nate Lastname wrote: > Hello List, > > I am quite sorry for my attitude. I will look more thoroughly into the > search results. Thanks for the link to Epik. I had found this, but I > didn't realize that it was Python. I apologize once again, and thank you > for your help. I did give you a link to a sandbox game (powdertoy.co.uk) > as an example of what I wanted, but that must not have been delivered > properly. Thank you for the gracious apology, and welcome to the group! Don't worry about asking stupid questions, we don't mind them so long as you make an effort to solve them yourself first, and that you learn from them as you go. -- Steven ___ 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
[Tutor] string integers?
I am trying to get 2 string variables and 2 integer variables to be able to be multiplied can anyone tell me what I did wrong str1 = raw_input("Type in a String: ") str2 = raw_input("Type in a String: ") int1 = raw_input("Type in a integer variable: ") int2 = raw_input("Type in a integer variable: ") print str1 + str2 + int1 + int2 import math print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * int 2 and it wont let me write int2 I know this may look stupid to most people but I am just new at this so dont laugh :)___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string integers?
this is the code I have str1 = raw_input("Type in a String: ") str2 = raw_input("Type in a String: ") int1 = raw_input("Type in a integer variable: ") int2 = raw_input("Type in a integer variable: ") print str1 + str2 + int1 + int2 import math int1 = int(raw_input("")) print str1, print str2, print int1, "*", int2 print "=" and it does not give me an error message when I run it, the program runs fine except its did not multiply the 2 integer variables i entered it looks like this Type in a String: hello Type in a String: hi Type in a integer variable: 4 Type in a integer variable: 5 hellohi45 This part is exactly what I want it to look like except I want it to multply the 2 numbers I inputed (4 & 5 in this example) thanks again for your time and sorry if I seem rude I just dont have alot of time these days I know you all dont have alot of time either and thats why I am extremely appreciative of everyones help --- On Sun, 2/12/12, Dave Angel wrote: From: Dave Angel Subject: Re: [Tutor] string integers? To: "William Stewart" Date: Sunday, February 12, 2012, 5:07 PM On 02/12/2012 02:41 PM, William Stewart wrote: > hello thank you for your reply That was a post to the list; you replied privately, but I'm going to just elaborate my earlier points. Try again, but use reply-all to one of the messages in the thread. You've got a new version of stuff, but no indication what the code now looks like, or what is "not working". Be explicit when requesting help. I and others pointed out a few things wrong; there are others. So don't make us guess what state you're in. Hopefully you're here to learn, and that happens best when you make clear questions, and get good responses. Show your code, show the error,and use cut&paste for the error you get. "It's not working" is not an error message. You either get an error message: quote the entire traceback Or it doesn't do what you expect: tell what you expected, and show what you got instead. > I fixed the error the only problem now is how do i get the 2 spereate > integers to multiply? but I still need the 2 strings to print > > I tried > > print str1, > print str2, > print int1, "*", int2 > print "=" > > I think I am missing something > I know the * is to multiply but its not working > thank you > > > > --- On Sun, 2/12/12, Dave Angel wrote: > > > From: Dave Angel > Subject: Re: [Tutor] string integers? > To: "William Stewart" > Cc: tutor@python.org > Date: Sunday, February 12, 2012, 9:51 AM > > > On 02/12/2012 08:25 AM, William Stewart wrote: >> I am trying to get 2 string variables and 2 integer variables to be able to >> be multiplied >> can anyone tell me what I did wrong >> str1 = raw_input("Type in a String: ") >> str2 = raw_input("Type in a String: ") >> int1 = raw_input("Type in a integer variable: ") >> int2 = raw_input("Type in a integer variable: ") >> print str1 + str2 + int1 + int2 >> import math >> print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * int 2 >> >> and it wont let me write int2 >> I know this may look stupid to most people but I am just new at this so >> dont laugh :) >> > > That's who this list is targeted at, people who are just learning Python. > Are you new to programming, or just to Python? Anyway, welcome to > Python-Tutor list. > > If these 7 lines are in a file, and you try to run them, you get a specific > error, pointing to a specific line. When asking questions about Python error > messages, please post the actual message, as it generally contains lots of > clues as to what's wrong. > > davea@think:~/temppython$ python william.py > File "william.py", line 7 > print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * >int 2 > ^ > SyntaxError: invalid syntax > > So now we both know the error is a syntax error, and it occurs on line 7, > which is conveniently redisplayed with a caret pointing at where the error > was discovered (notice that in many email systems a proportional font may > hide the correct column. So trust what you saw on your own terminal > window). Sometimes the actual syntax error is a few characters earlier, but > this is as fine-tuned as most compilers can manage. > > That print line has 4 errors that I can immediately spot, and the compiler > told you about the first one. That error was in omitting the c
Re: [Tutor] string integers?
Thank you for the reply It worked fine ! --- On Sun, 2/12/12, Steven D'Aprano wrote: From: Steven D'Aprano Subject: Re: [Tutor] string integers? To: tutor@python.org Date: Sunday, February 12, 2012, 6:50 PM William Stewart wrote: > this is the code I have > str1 = raw_input("Type in a String: ") > str2 = raw_input("Type in a String: ") > int1 = raw_input("Type in a integer variable: ") > int2 = raw_input("Type in a integer variable: ") > print str1 + str2 + int1 + int2 > import math > int1 = int(raw_input("")) > print str1, > print str2, > print int1, "*", int2 > print "=" > > and it does not give me an error message when I run it, the program runs fine > except its did not multiply the 2 integer variables i entered But you haven't asked it to multiply anything. You asked it to PRINT the two variables with an asterisk between them. And further more, you don't have two integers. You have two strings that merely happen to contain digits. Before you can do maths on them, you have to tell Python to treat them as integers, not strings. You use the int() function (int being short for integer, in case it isn't obvious) for that: py> x = raw_input("Enter a number: ") Enter a number: 42 py> type(x) py> x * 10 '42424242424242424242' py> py> x + 1 Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects Before you can do maths on x, you have to turn it into a number: py> x = int(x) py> x * 10 420 py> x + 1 43 P.S. Does your computer have a Delete or Backspace key? Please trim your replies, there is no need to quote page after page after page of old conversation that you don't directly address. -- Steven ___ 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
[Tutor] how to rewrite area.py
hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this import math print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: selection = raw_input("Please select an option from the menu.: ") python area.py print "Calculate information about a rectangle" length = input("Length:") width = input("Width:") print "Area",length*width print "Perimeter",2*length+2*width print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') h = input('Height: ') while h <= 0: print 'Must be a positive number' h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h)___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to rewrite area.py
On 2/21/2012 6:51 PM, William Stewart wrote: hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). "Need to"" - why? Is this a homework assignment? I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this Did you run this program? What results did you get? How did they differ from what you expected? Yes it wont run tdue to some problems in my indents but I am working on it What does being "horrible at mat" have to do with this? I dont know What do you know about defining functions? Not much Did you write this program yourself? this is new to me it a beginners computer class, but I think this may be too advanced for me , I havent learned anything about python before starting except some basic tutorials If you are taking a Python class and don't know what to do either the class is poorly designed or you are in the wrong class. Please say more about this. We are glad to help, but won't write your homework for you. Someone game me some help but Im not sure if I piut it in right it looks like this import math from math import pi print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: selection = raw_input("Please select an option from the menu.: ") def get_area_of_square(): print "Please enter the width of a square" area = width**2 return area def get_area_of_rectangle(): Print "please enter the width of a rectangle" area = width*height return area def get_radius_of_circle(): print "please enter the radius of a circle" radius = pi**2 retrun radius SQUARES: area = width*width = width**2 perimeter = width+width+width+width = 4*width RECTANGLES: area = width*height perimeter = width+height+width+height = 2*(width+height) CIRCLES: area = pi*radius**2 circumference = 2*pi*radius thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to rewrite area.py
so I copied your format except I changed shape 3 to circle, Did I do the circle part right? and would this be considered seperate functions? Thanks for your help import math from math import pi menu = """ Pick a shape(1-3): 1) Square 2) Rectangle 3) Triangle 4) Quit """ shape = int(input(menu)) while shape != 4: if shape == 1: length = float(input("Length: ")) print( "Area of square = ", length ** 2 ) elif shape == 2: length = float(input("Length: ")) width = float(input("Width: ")) print( "Area of rectangle = ", length * width ) elif shape == 3: area = float(input("Radius: ")) circumference = float(input("radius: ")) print( "Area of Circle = ", pi*radius**2 ) shape = int(input(menu)) OR would this work better? import math from math import pi print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: selection = raw_input("Please select an option from the menu.: ") def get_area_of_square(): print "Please enter the width of a square" area = width**2 return area def get_area_of_rectangle(): Print "please enter the width of a rectangle" area = width*height return area def get_radius_of_circle(): print "please enter the radius of a circle" radius = pi**2 retrun radius SQUARES: area = width*width = width**2 perimeter = width+width+width+width = 4*width RECTANGLES: area = width*height perimeter = width+height+width+height = 2*(width+height) CIRCLES: area = pi*radius**2 circumference = 2*pi*radius --- On Tue, 2/21/12, Alan Gauld wrote: From: Alan Gauld Subject: Re: [Tutor] how to rewrite area.py To: tutor@python.org Date: Tuesday, February 21, 2012, 7:46 PM On 21/02/12 23:51, William Stewart wrote: > I need to rewrite area.py program so that it has separate functions for > the perimeter and area of a square, a rectangle, and a circle (3.14 * > radius**2). You will find something similar in my tutorial in the topic Branching. Look under the heading "Python multi-selection" and there is some code you should be able to include as template. Have a go and come back with questions. > I am horrible at math and I cannot even figure out what I need to do for > this Steven has done the math bit for you, so just plug it into the python code you need. -- Alan G 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 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python web script to run a command line expression
I'm not sure if this is what you are looking for or if this will work on WAMP but python has a virtual terminal emulator called Vte or python-vte. I use it to display the terminal and run commands. I'm using it on Linux by adding "from gi.repository import Vte". Hope it helps. On 18-05-2013 04:20, Ahmet Anil Dindar wrote: Hi, I have a WAMP running in my office computer. I wonder how I can implement a python script that runs within WAMP and execute a command line expression. By this way, I will able to run my command line expressions through web page in intranet. I appreciate your suggestions. ++Ahmet ___ 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
[Tutor] library:
I am reading posts and watching videos. I am following along with the shell, i am retaining the info. But WHAT is a library? Thanks, everyone. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] New dealing with Pythong and programming
Hello My name is Will, I live in Costa Rica and I really want to learn how to program. In the past, a friend said to me that was really cool but I did not feel the call to learn, but now I was talking to a new friend and he said to me code was really great then I ask what was the best language and he said, well find the best language, find Python which I did. But now here comes the question, I do not know anything about programming, I heard about Integer, float and a bunch of this thing but I do not have a clue what they are. Can you please guide me to find what they are (I know of course there are more). I have installed Python version 2.7.8, my computer is running windows 7 64 bits and I was recommended to install a work editor which I did (DreamPie Python 2.7), this is just in case you think I need to change something. Are all of this things a constant for all the programming languages or are there specific for Python? I would like to start by understanding this concepts otherwise I will be confused I guess. Thank you for your time, this system really rocks, I do appreciate all what you do for us the beginners. Thank you ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
I'm new to programming. Started reading the book 'How to think like a computer Scientist-learning with python'. I'm now in chapter 3 sub-chapter 3.4 Math functions. When I write the following code: import maths; decibel = math.log10 (17.0); angle = 1.5; height = math.sin(angle); print height; I get the following error: Traceback (most recent call last): File "C:/Python27/test", line 1, in import maths; ImportError: No module named maths I don't know what I'm doing wrong? >From what I've read the maths module is supposed to come with the python installation package. I'm using a windows 8 operating system python 2.7.8 please help? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
It is working now. Thank you everyone. It was very helpfull. On Fri, Oct 10, 2014 at 2:36 AM, Alan Gauld wrote: > On 09/10/14 19:38, William Becerra wrote: > > import maths; >> > > Python, like most languages speaks American English > so its math not maths. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] keyword colors disappear
Hey, I'm new to programming. Only have about 2 weeks of experience. Using Python 2.7.8 and running Windows 8 I'm having the following problem. I open Python shell press file, new file and write my code(any code) then all the Python keywords appear in their different *colors*, for example print appears in orange, strings in green numbers in blue, etc. Now here is the problem, after I press F5 and i run my code. Then i try go back to my code and add some more code or change the code. Now all ll the colors of the Python keywords are gone. Everything appears in normal black and white text. Note: weather the code is correct or there is any errors I still have the same problem. What i want to know is. Is there something i can do to keep the colors of the keywords? because it makes it easier for me to keep track of my code. Hope what i asked is clear. Thank You ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Infinite Recursion
Hey, I'm new to programming. Using python 2.7.8 and running windows8 OS I'm reading 'How to think like a computer scientist, learning with Python' I'm in chapter 4 sub-chapter 4.11 Infinite recursion According to the book if I write def recurse(): recurse() I should get the following error File"", line2, in recurse ( 98 repetitions omittted) File "", line 2, in recurse RuntimeError: Maximum recursion depth exceeded. I don't get that error, instead the Python shell prints out two blank lines. >From what i understand if i don't get the error the infinite recursion is not been tried by the shell. Am I missing anything in the code? and If anything is wrong. How can I write a easy Infinite recursion to help me grasp the concept? Thank You. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Return Statement error
Hello, I'm new to programming. I'm using Python 2.7.8 and Windows 8 OS I was making an application to see if I understand how the return statement works I want my application to compare x and y and return either 1, -1 or 0. I'm using IDLE Here is my code: print"Please write a value for x" x = raw_input() print "Please write a value for y" y = raw_input() if x > y: return 1 elif x < y: return -1 elif x == y: return 0 else: return "Please insert a Valid character" When I press F5 to run my code a new window called syntax error appears The window says the following There's an error in your program: ***'return' outside function (C:/Users/William/Desktop/Python Files/Function compare.py, line6) What am I doing Wrong? I noticed that if i substitute all the return keywords with print the code runs correctly. However I want to use return as I am trying to learn how it works. Thank You. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Return Statement error
I am familiar with funtions, i didn't realize i had to write the return statement inside a function...Thank you all..that was very helpful On 13 Oct 2014 01:03, "Steven D'Aprano" wrote: > On Sun, Oct 12, 2014 at 04:38:54PM +0200, William Becerra wrote: > > Hello, I'm new to programming. I'm using Python 2.7.8 and Windows 8 OS > > I was making an application to see if I understand how the return > statement > > works > > The `return` statement can only be used inside a function. That means > you have to start off with a `def` line, and indent your code. > > Have you learned about functions yet? If not, perhaps you might prefer > to forget about `return` until you do. Otherwise, if you take the code > you wrote, indent it, and put a function declaration at the top, you > should be able to use `return` successfully: > > def compare(): > print "Please write a value for x" > x = raw_input() > print "Please write a value for y" > y = raw_input() > if x > y: > return 1 > elif x < y: > return -1 > elif x == y: > return 0 > else: > return "this will never happen" > > > Then, once you have defined your function, you can call it: > > result = compare() # don't forget the parentheses () > print "And the result is", result > > > > -- > Steven > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Differentiating vowels from consonants
Hello, I'm new to programming Running Python 2.7.8 on Windows 8 OS I was reading http://www.sthurlow.com/python/lesson07/ Here there is an example of the for loop with a Cheerleader program but the program is not able to print grammatically correct. word = raw_input("Who do you go for? ") for letter in word: call = "Gimme a " + letter + "!" print call print letter + "!" print "What does that spell?" print word + "!" I tried changing the code so that the program can recognize vowels from consonants and write the correct article (a or an) here is my code. word = raw_input("Who do You Support: ") vowels = ('a', 'e', 'i', 'o', 'u') for letter in word: if letter == vowels: call = 'Give me an ' + letter + '!' print call print letter + '!' else : call = 'Give me a ' + letter + '!' print call print letter + '!' print 'What does that say' print word + '!!' My code also isn't able to recognise vowels. For example if i write Manchester as the raw_input i get : give me a M give me a a etc. I would like it to say give me a M give an a So here is my question. What is wrong with my code and how can I change it to get the result I want. Thank You ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Flow of execution of execution
hey, I'm new to programming. running Python 2.7.8 on windows 8 OS Im on chapter 6 of a book called 'How to Think Like a Computer Scientist-Learning with Python' here is the code: def printMultiples(n, high): i = 1 while i<=high: print n*i, "\t", i = i + 1 print def multipleTable(high): i = 1 while i<=high: printMultiples(i, i) i = i + 1 print print multipleTable(6) when i run this code the result i get is 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 None Can someone please explain why does it print a triangular table and not a square table like this one: 1 2 3 4 5 6 2 4 6 8 10 12 3 6 9 12 15 18 4 8 12 16 20 24 5 10 15 20 25 30 6 12 18 24 30 36 None is there any documentation i can read on tables? Thank You ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Flow of execution of execution
Thank you guys On Mon, Nov 3, 2014 at 11:26 PM, Alan Gauld wrote: > On 03/11/14 18:04, William Becerra wrote: > > def printMultiples(n, high): >> i = 1 >> while i<=high: >> print n*i, "\t", >> i = i + 1 >> print >> > > def multipleTable(high): >> i = 1 >> while i<=high: >> printMultiples(i, i) >> i = i + 1 >> print >> > > print multipleTable(6) >> >> when i run this code the result i get is >> >> 1 >> 2 4 >> 3 6 9 >> 4 8 12 16 >> 5 10 15 20 25 >> 6 12 18 24 30 36 >> > > Can someone please explain why does it print a triangular table and not >> a square table like this one: >> > > Because you call print Multiples() from within multipleTable() > Each time the loop executes the value of i increases so each line printed > gets longer. The first line is printed by printMultiples(1,1) > The second is called with printMultiples(2,2) and so on up to > printMultiples(6,6). > > This yields a triangular printout. > > is there any documentation i can read on tables? >> > > Not really, there's no such thing as a table in Python programming, its > just a structure you create. In practice its usually composed of a list of > lists. > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Strings
Hey, I'm new to programming running Python 2.7.8 Windows 8.1 I was reading 'How to Think Like a Computer Scientist- Learning with Python' chapter 7 sub-chapter 7.7 I have the following code: names = "John, Cindy, Peter" def find(str, ch, s): index = 0 while index < len(str): if s==1: for char in names[:4]: if str[index] == ch: return index + 1 index = index + 1 if s==2: for char in names[6:11]: if str[index] == ch: return index + 1 index = index + 1 if s==3: for char in names[13:]: if str[index] == ch: return index + 1 index = index + 1 return -1 print find(names,"n", 2) and my problem is: I intend for the parameter s to tell the interpreter which name to look at so that i get the index return value related to that name. for example: John and Cindy both have a letter 'n' but when I call the function with an s value of 2 I want it to return the index value of the letter n in Cindy and not in John. Can Someone Please tell me why my code isn't working like I intend it to? Thank you ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Strings
Thank you guys On Thu, Nov 6, 2014 at 3:39 AM, Dave Angel wrote: > William Becerra Wrote in message: > > > > have the following code: > names = "John, Cindy, Peter" > def find(str, ch, s): > index = 0 > while index < len(str): > if s==1: > for char in names[:4]: > if str[index] == ch: > return index + 1 > index = index + 1 > if s==2: > for char in names[6:11]: > if str[index] == ch: > return index + 1 > index = index + 1 > if s==3: > for char in names[13:]: > if str[index] == ch: > return index + 1 > index = index + 1 > return -1 > print find(names,"n", 2) > > > > and my problem is: > I intend for the parameter s to tell the interpreter which name to > look at > so that i get the index return value related to that name. > for example: > John and Cindy both have a letter 'n' but when I call the function > with an s value of 2 I want it to return the index value of the > letter n in Cindy and not in John. > > Your most immediate problem is that you're using index to fetch > characters from the original string, and that's only reasonable > for John. You could make a slice of the original, and search that > slice. Or you could change the comparison to: >if char == ch: > > The loop could also be cleaner with enumerate. > > Your second big problem is that you've hard coded the sizes of the > first two names in the slice expressions. The magic [6:11] for > example certainly doesn't belong inside the function. > > > Third is your while loop makes no sense. Each of the if clauses > won't finish till you're done with the selected substring, so > you might as well return right away. Drop that line entirely. > > > Anyway, I say you're trying to do too much in the one function. If > possible change the data structure of names to eliminate one of > the two tasks, or write two functions, a few lines > each. > > I'd make > names = ["John", "Cindy", "Peter"] > And start the function with > name = names [s-1] > > And now the task of the remainder of the function is to search a > name for a particular character. > > -- > DaveA > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] hexodecimal to decimal form
Hello, I'm new to programming using Python 2.7.8 and Windows 8 OS I'm reading How to Think Like a Computer Scientist - learning with python on chapter 12.2 theres the following code: class Point: pass blank = point() blank.x = 3.0 blank.y = 4.0 >>print blank.x 3.0 >>print blank.y 4.0 >>print blank <__main__.point instance at 0x02B38E40> the author says the the < 0x02B38E40> is in hexadecimal form heres is my question: How can i convert from hexodecimal form to decimal form? is there any source i can read on it? basically what i want is to use the attributes blank.x and blank.y as a single point like in the mathematics format (x, y) co-ordinates so that i can workout distance thank you ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hexodecimal to decimal form
Thank you for your time On 11 Nov 2014 15:02, "Dave Angel" wrote: > William Becerra Wrote in message: > > Hello, I'm new to programming using Python 2.7.8 and Windows 8 OSI'm > reading How to Think Like a Computer Scientist - learning with pythonon > chapter 12.2theres the following code: class Point: passblank = > point()blank.x = 3.0blank.y = 4.0 > >>>print blank.x > > 3.0>>print blank.y4.0 > >>>print blank<__main__.point instance at 0x02B38E40> > > > > the author says the the < 0x02B38E40> is in hexadecimal form > > heres is my question:How can i convert from hexodecimal form to decimal > form? > > You don't care about that 0x02.. number, except to distinguish > this object from another. And in code you'd do that with the 'is' > operator. > That hex number happens to be an address in memory for one of the > python implementations. > > > is there any source i can read on it?basically what i want is to use the > attributes blank.x and blank.y as a single point like in the mathematics > format (x, y) co-ordinates so that i can workout distance > > thank you > > > > > > > If you want a tuple of the coordinates, you could do (blank.x, > blank.y) And if you need to do arithmetic, go right ahead. > Like > > x, y = blank.x, blank.y > dist_from_org = sqrt(x*x + y*y) > > > > -- > DaveA > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble creating a pygame.font.SysFont, was Re: (no subject)
It seems I forgot to write pygame.init() Thank you guys for your time it is much appreciated. On Saturday, 29 November 2014, 15:31, Peter Otten <__pete...@web.de> wrote: William wrote: Hello William; please provide a meaningful subject line so that your readers get a hint whether your question is in their area of expertise. > Hello there I'm using Python 3.4 running on Ubuntu 14.04LTS > I'm new to programming and also new to linux > I'm trying to learn the pygame library > I was reading : > > http://programarcadegames.com/index.php?chapter=introduction_to_graphics&lang=en#section_5 > > On the section on how to draw text the writer has the following code > | > font ||=||pygame.font.SysFont(||'Calibri'||, ||25||, ||True||, ||False||)| > |text ||=||font.render(||"My text"||,||True||,BLACK) > ||screen.blit(text, [||250||, ||250||]) That is very hard to read. If you have to post Python code please do it in plain text without those funny "|". Thank you. > When I run the code using the IDLE the Python shell gives me the > following error > > Traceback (most recent call last): > File "/home/william/Desktop/Pygame/Python 3X/Drawing_Shapes.py", line > 48, in > font = pygame.font.SysFont('Calibri', 25, True, False) > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 614, in SysFont > return constructor(fontname, size, set_bold, set_italic) > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 537, in font_constructor > font = pygame.font.Font(fontpath, size) > pygame.error: font not initialized > > > I think the problem is that the fonts in Ubuntu are probably stored in a > different > location than in Windows OS.And therefore python can not find it using > the SysFont > method > Can anyone give me any suggestion on how to edit the code so that I can > write text > on my graphics? Quoting the page you link to: """ The first code a Pygame program needs to do is load and initialize the Pygame library. Every program that uses Pygame should start with these lines: Importing and initializing Pygame # Import a library of functions called 'pygame' import pygame # Initialize the game engine pygame.init() """ Did you follow that advice? If you did and your script is reasonably short please post it here so that we can have a look or try to run it ourselves. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fahrenheit to Celsius Conversion with if else statements
Good day Everybody, I am practicing coding when I encountered a problem with the if and else statements in my code. Hope someone can help me understand my mistake. The following is my code to convert Fahrenheit to Celsius and vice-versa: print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.') unit = input('Enter C or F:') temp = int(input('Enter temperature:')) if unit == 'C': f = (temp + 32) * 9 / 5 print(str(temp) + ' C is equivalent to ' + "%.2f" % f + ' F.') else: c = (temp - 32) * 5 / 9 print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.') OUT: Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius. Enter C or F:f Enter temperature:212 212 F is equivalent to 100.00 C. However, when I entered C, the else block was executed instead. The if block was skipped. Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius. Enter C or F:c Enter temperature:100 100 F is equivalent to 37.78 C. I could not figure out my mistake. For advice, please. Thank you. Best regards william ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fahrenheit to Celsius Conversion with if else statements
Good day Alan, Very much thanks for your guidance. I have added or 'c' to the if statement. That is resolved. Through that correction I discovered my C to F code was wrong. The + 32 is supposed to be executed at the end. Thanks again. Cheers -Original Message- From: Alan Gauld [mailto:alan.ga...@yahoo.co.uk] Sent: Tuesday, June 13, 2017 1:36 AM To: tutor@python.org Subject: Re: [Tutor] Fahrenheit to Celsius Conversion with if else statements On 12/06/17 15:17, William Gan wrote: > print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to > Celsius.') unit = input('Enter C or F:') temp = int(input('Enter > temperature:')) > > if unit == 'C': Note this only t5ests for 'C' - ie capital C. You might want to force the input to be uppercase first? if unit.upper() == 'C': > f = (temp + 32) * 9 / 5 > print(str(temp) + ' C is equivalent to ' + "%.2f" % f + ' F.') > else: > c = (temp - 32) * 5 / 9 > print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.') > > However, when I entered C, the else block was executed instead. The if block > was skipped. > > Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius. > > Enter C or F:c Note you entered lowercase 'c' not 'C'. Very different. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm
Good day Everyone, I am seeking help on two issues. ISSUE 1: Yesterday I posted a problem on this tiny script I wrote for temperature conversion (as practice for a newbie). My error was pointed out to me that there is a difference in upper and lowercase letters. After correcting that error, I remember the tests I ran produced the correct outputs. However, today I modified only the print instruction a little to try to print out ℃ (in the second print clause). When I subsequently ran the script all the outputs were executed from the if clause, even when I input other letters (Please see below. I have removed the code to print degree C). print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.') unit = input('Enter C or F: ') temp = int(input('Enter temperature: ')) if unit == 'C' or 'c': f = temp * 9 / 5 + 32 print(str(temp) + ' C is equivalent to ' + '%.2f' % f + ' F.') elif unit == 'F' or 'f': c = (temp - 32) * 5 / 9 print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.') else: print('Please enter C or F in upper- or lowercase.') The if statement block is to convert Celsius to Fahrenheit. When I entered ‘C’ or ‘c’ and 100 for temperature, the output is correct: 100 C is equivalent to 212.00 F. The elif statement block is to convert Fahrenheit to Celsius. When I entered ‘f’ or another letter, in this case ‘z’ and ‘g’, and 212 for temperature, I got: 212 C is equivalent to 413.60 F. I have looked at it many times today and could not see the error. Please advise. ISSUE 2: The second issue relates to the last statement above “I have looked at it many times today and could not see the error”. I was hoping that someone, perhaps one with pedagogical experience and knowledge, could advise the following: 1. Is it possible that I may not have the right aptitude or mental paradigm to do computer programming? I think I don’t. My background is in finance, accounting and economics. When I have difficulty in certain concepts in these fields I could figure it out eventually, in reasonable time. However, I am having difficulty learning it. I have been learning for a few months already and I am not learning fast enough. 2. Nevertheless, I intend to keep learning and practicing, but wonder if there is an effective way to get a breakthrough into the programming paradigm? If so, kindly advise how and direct me to a suitable resource to do it. Many thanks. Best regards. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm
Hi Alan, Very much thanks again for your help. Your elucidation helped me gain better understanding on this issue. I have resolved that error. Thank you also for your counsel on this second issue. Best regards. -Original Message- From: Alan Gauld [mailto:alan.ga...@yahoo.co.uk] Sent: Thursday, June 15, 2017 2:15 AM To: tutor@python.org Subject: Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm On 14/06/17 15:20, William Gan wrote: > print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to > Celsius.') > > if unit == 'C' or 'c': You have hit a common error for beginners. reading this as a human it is quite clear what is meant but the computer sees it differently. It sees: if (unit == 'C') or 'c': Now, a non empty string like 'c' is always considered True in a boolean context so, the interpreter interprets it as: if (unit == 'C') or True: And since any 'or' test where one element is True is evaluated to True it reads as if True: and so the 'if' part is always executed. How to avoid this? There are several options: if unit == 'C' or unit == 'c': But that gets cumbersome if more than two values. Better is: if unit in ('C','c'): This is best if there are multiple true options not just upper/lower case or if unit.lower() == 'c': This is best is the strings are longer than a single letter. (You can use unit.upper() too, that's just an arbitrary choice) > 1. Is it possible that I may not have the right aptitude or mental paradigm to do computer programming? Possible, but unlikely, most folks with a basic math ability can pick up programming. You may not be a natural, and may never be a programming guru, but you should be able to get to the stage of competence. > However, I am having difficulty learning it. It is difficult, despite what some books would have you believe. If it wasn't difficult there would be no need to teach it as a university subject! You have to train your mind to think like a computer (as in the case above) and to break things down into often painfully detailed steps. But that is just practice. > I have been learning for a few months already and I am not learning > fast enough. Says who? I've been programming for over 40 years and am still learning new things every week. Don't give up, and keep asking questions. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm
Hi David, Very much thanks for taking time to help. Your explanation has helped me understand that syntax issue better. I have resolved that error. Your counsel on the second issue has given me encouragement. Thank you. Best regards. -Original Message- From: David Rock [mailto:da...@graniteweb.com] Sent: Thursday, June 15, 2017 2:04 AM To: tutor@python.org Subject: Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm > On Jun 14, 2017, at 09:20, William Gan wrote: > > However, today I modified only the print instruction a little to try to print > out ℃ (in the second print clause). When I subsequently ran the script all > the outputs were executed from the if clause, even when I input other letters > (Please see below. I have removed the code to print degree C). > > > if unit == 'C' or 'c': > >f = temp * 9 / 5 + 32 > >print(str(temp) + ' C is equivalent to ' + '%.2f' % f + ' F.') > > elif unit == 'F' or 'f': > >c = (temp - 32) * 5 / 9 > >print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.') The problem is your if statement is flawed. if unit == 'C' or 'c’: This is not doing what you think it is. You are expecting: if unit == ‘C’ or unit == ‘c’ When doing an ‘or’ statement, each part of the logic on each side of the ‘or’ is evaluated, so if unit == ‘C’ is true, or if ‘c’ is true is what’s actually being checked. a bare character, ‘c’ will always evaluate to True, so the if is always true. What you actually want (checking if unit is ‘C’ or ‘c’) can be done a few ways. The most common are: if unit == ‘C’ or unit ==‘c’: or if unit in [‘C’, ‘c’]: > ISSUE 2: > > The second issue relates to the last statement above “I have looked at it > many times today and could not see the error”. > > > > I was hoping that someone, perhaps one with pedagogical experience and > knowledge, could advise the following: > > 1. Is it possible that I may not have the right aptitude or mental > paradigm to do computer programming? Unlikely. Programming is not about aptitude, it’s more about spending time understanding the rules. The above is a prime example of getting to understand the rules. Logic rules are notoriously specific; they check exactly what you tell them to check, which is not always what you think you are asking. It just takes time. > > 2. Nevertheless, I intend to keep learning and practicing, but wonder > if there is an effective way to get a breakthrough into the programming > paradigm? If so, kindly advise how and direct me to a suitable resource to do > it. Really, just keep trying things. When you run into something like this, the most effective way to troubleshoot is narrow it down to the essential issue. In this case, “why is the if statement always evaluating to true?” Look at the parts and re-read what each does (eg, reread how the ‘or’ operator works). You are doing fine. :-) — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm
Hi Sebastian, Very much thanks for your help. Your explanation and illustrations is clear. I was not aware of that syntax. I now understand and the issue is resolved. Thanks again. Cheers. -Original Message- From: Sebastian Silva [mailto:sebast...@fuentelibre.org] Sent: Thursday, June 15, 2017 1:53 AM To: William Gan ; tutor@python.org Subject: Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm Hi William, Glad to see the tutor list is being of help in your learning. On 14/06/17 09:20, William Gan wrote: > if unit == 'C' or 'c': In this case, it will always be true, because there are two conditions, either: * unit == 'C' or * 'c' As you can see, the second condition is not a comparison, but a string expression, that Python always evaluates to True (except for '' empty string). Thus, the combined condition is always true because the second expression is always True. The correct condition would be: if unit=='C' or unit=='c': Or perhaps more clear, also correct: if unit in ('C', 'c'): Or shorter: if unit in 'Cc': Hope it's useful, Regards, Sebastian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] UTF-8 filenames encountered in os.walk
I have several programs which traverse a Windows filesystem with French characters in the filenames. I have having trouble dealing with these filenames when outputting these paths to an XML file - I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 ... etc. That happens when I try to convert to UTF-8. I know what os will give me UFT-8 if I give it UTF-8, and I am trying to do that, but somewhere down the line it seems like it reverts to ASCII, and then I get these errors. Has anyone found a silver bullet for ensuring that all the filenames encountered by os.walk are treated as UTF-8? Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UTF-8 filenames encountered in os.walk
On Tue, Jul 03, 2007 at 06:04:16PM -0700, Terry Carroll wrote: > >> Has anyone found a silver bullet for ensuring that all the filenames >> encountered by os.walk are treated as UTF-8? Thanks. > >What happens if you specify the starting directory as a Unicode string, >rather than an ascii string, e.g., if you're walking the current >directory: > > for thing in os.walk(u'.'): > >instead of: > > for thing in os.walk('.'): This is a good thought, and the crux of the problem. I pull the starting directories from an XML file which is UTF-8, but by the time it hits my program, because there are no extended characters in the starting path, os.walk assumes ascii. So, I recast the string as UTF-8, and I get UTF-8 output. The problem happens further down the line. I get a list of paths from the results of os.walk, all in UTF-8, but not identified as such. If I just pass my list to other parts of the program it seems to assume either ascii or UTF-8, based on the individual list elements. If I try to cast the whole list as UTF-8, I get an exception because it is assuming ascii and receiving UTF-8 for some list elements. I suspect that my program will have to make sure to recast all equivalent-to-ascii strings as UTF-8 while leaving the ones that are already extended alone. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UTF-8 filenames encountered in os.walk
On Wed, Jul 04, 2007 at 11:28:53AM -0400, Kent Johnson wrote: >FWIW, I'm pretty sure you are confusing Unicode strings and UTF-8 >strings, they are not the same thing. A Unicode string uses 16 bits to >represent each character. It is a distinct data type from a 'regular' >string. Regular Python strings are byte strings with an implicit >encoding. One possible encoding is UTF-8 which uses one or more bytes to >represent each character. > >Some good reading on Unicode and utf-8: >http://www.joelonsoftware.com/articles/Unicode.html >http://effbot.org/zone/unicode-objects.htm The problem is that the Windows filesystem uses UTF-8 as the encoding for filenames, but os doesn't seem to have a UTF-8 mode, just an ascii mode and a Unicode mode. >If you pass a unicode string (not utf-8) to os.walk(), the resulting >lists will also be unicode. > >Again, it would be helpful to see the code that is getting the error. The code is quite complex for not-relevant-to-this-problem reasons. The gist is that I walk the FS, get filenames, some of which get written to an XML file. If I leave the output alone I get errors on reading the XML file. If I try to change the output so that it is all Unicode, I get errors because my UTF-8 data sometimes looks like ascii, and I don't see a UTF-8-to-Unicode converter in the docs. >>I suspect that my program will have to make sure to recast all >>equivalent-to-ascii strings as UTF-8 while leaving the ones that are >>already extended alone. > >It is nonsense to talk about 'recasting' an ascii string as UTF-8; an >ascii string is *already* UTF-8 because the representation of the >characters is identical. OTOH it makes sense to talk about converting an >ascii string to a unicode string. Then what does mystring.encode("UTF-8") do? -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UTF-8 filenames encountered in os.walk
On Wed, Jul 04, 2007 at 02:47:45PM -0400, Kent Johnson wrote: >encode() really wants a unicode string not a byte string. If you call >encode() on a byte string, the string is first converted to unicode >using the default encoding (usually ascii), then converted with the >given encoding. Aha! That helps. Something else that helps is that my Python code is generating output that is received by several other tools. Interesting facts: Not all .NET XML parsers (nor IE6) accept valid UTF-8 XML. I am indeed seeing filenames in cp1252, even though the Microsoft docs say that filenames are in UTF-8. Filenames in Arabic are in UTF-8. What I have to do is to check the encoding of the filename as received by os.walk (and thus os.listdir) and convert them to Unicode, continue to process them, and then encode them as UTF-8 for output to XML. In trying to work around bad 3rd party tools and inconsistent data I introduced errors in my Python code. The problem was in treating all filenames the same way, when they were not being created the same way by the filesystem. Thanks for all the help and suggestions. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] gotoxy
hi folks, is there in python a gotoxy like in pascal so i can print stuff in other parts of the screen? what about some thing like it for the gui in windows? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question re Tutor List Etiquette
On Tue, Aug 14, 2007 at 08:11:33PM +0100, Tom Fitzhenry wrote: >On Tue, Aug 14, 2007 at 11:06:05AM -0700, Dick Moores wrote: >> Replying only to the list takes a bit of trouble. The default >> behavior seems to be that the "Reply" button addresses the author >> only and not the list; "Reply to all" addresses both the list, the >> author, and any others included in the To: or Cc: headers of the post >> being replied to. Or at least that's how Eudora and Gmail work. What I have done is to inject a Reply-To header into each email with procmail, so that hitting reply does what I expect. Here's the rule I use: :0 * ^(From|To|Cc)[EMAIL PROTECTED] { :0hf | /usr/bin/formail -A "Reply-To: tutor@python.org" :0 python/ } I like this approach because it does not require that the list change behaviour to what I consider to be the "right" thing (who cares what I think), but if the list decided to change their policy then nothing changes (the header would be changed to itself). -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Matching dictionary entries by partial key
I'm trying to traverse a dictionary looking for partial matches of the key, and I'm not sure how. Here's a sample dictionary: dict = {1234 : value1, 20051234 : value2, 20071234 : value3} Here's what I'm trying to do: for key in dict: if key == or key == 2005: do something with dict[key] The challenge is that I only care about the first four digits of the key for the purpose of this match - is there a way to express this? I could probably create a wrapper dictionary using just the first four digits of the key as they key, and containing the original key:value pair as a list within it, but that seems cumbersome. Any one have a suggestion? Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Matching dictionary entries by partial key
On Thu, Oct 06, 2005 at 10:28:23PM -0400, Kent Johnson wrote: >William O'Higgins Witteman wrote: >> I'm trying to traverse a dictionary looking for partial matches of the >> key, and I'm not sure how. Here's a sample dictionary: >> >> dict = {1234 : value1, 20051234 : value2, 20071234 : value3} >> >> Here's what I'm trying to do: >> >> for key in dict: >> if key == or key == 2005: > > if key.startswith('') or key.startswith('2005'): This is perfect! Where do I read about things like this? I've been spending a bunch of time with the python.org documentation, "A Byte of Python" and "Dive Into Python", but I didn't run across this. >or with a regular expresion: > if re.match('|2005', key): This is good too, and it shows me the syntax (which I had trouble with). >> do something with dict[key] >> >> The challenge is that I only care about the first four digits of the key >> for the purpose of this match - is there a way to express this? I could >> probably create a wrapper dictionary using just the first four digits of >> the key as they key, and containing the original key:value pair as a >> list within it, but that seems cumbersome. Any one have a suggestion? > >If you have a *lot* of keys and need more speed, that might be a good >optimization. For a small dict, just use startswith(). Should I compile the regex to further increase the speed? Thanks for the help. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Regex help
Hello all, I've been looking for an example of the regex I need, and so far, I haven't found anything. Here's what I need: I want a case-insensitive, verbose pattern. I have a long-ish list of match criteria (about a dozen distinct cases), which should be all "or", so I won't need to be clever with precedence. Any help you could provide with the syntax of this pattern would be greatly appreciated. Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex help
On Sat, Aug 26, 2006 at 09:45:04AM -0400, Kent Johnson wrote: >William O'Higgins Witteman wrote: >> I want a case-insensitive, verbose pattern. I have a long-ish list of >> match criteria (about a dozen distinct cases), which should be all "or", >> so I won't need to be clever with precedence. > >Vertical bar | is used to separate 'or' cases in a regex. To make it >case-insensitive and verbose you can compile with the flags re.VERBOSE >and re.IGNORECASE. Use the search method of the compiled regex to search >your string. For example, > >In [1]: import re > >In [2]: rx = re.compile('foo|bar|baz', re.VERBOSE | re.IGNORECASE) > >In [3]: rx.search('Foontastic') >Out[3]: <_sre.SRE_Match object at 0x00C40640> > >In [4]: rx.search('raise the BAR') >Out[4]: <_sre.SRE_Match object at 0x00E901A8> Thank you for this. The problem is apparently not my syntax, but something else. Here is a pared-down snippet of what I'm doing: In [1]: import re In [2]: pat = re.compile(''' ...:copy of ...:| ...:admin ...:''', re.IGNORECASE | re.VERBOSE) In [3]: pat.search('''\\some\unc\path\Copy of somedarnfilename.exn''') In [4]: I don't get my match, and I really think I should. Can anyone tell me what I'm missing? Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex help
On Mon, Aug 28, 2006 at 11:36:18AM -0400, Kent Johnson wrote: >William O'Higgins Witteman wrote: >> Thank you for this. The problem is apparently not my syntax, but >> something else. Here is a pared-down snippet of what I'm doing: >> >> In [1]: import re >> >> In [2]: pat = re.compile(''' >> ...:copy of >> ...:| >> ...:admin >> ...:''', re.IGNORECASE | re.VERBOSE) >> >> In [3]: pat.search('''\\some\unc\path\Copy of somedarnfilename.exn''') >> >> In [4]: >> >> I don't get my match, and I really think I should. Can anyone tell me >> what I'm missing? Thanks. >There are several problems here. > >First, when re.VERBOSE claims to ignore whitespace, it isn't kidding. >Space, tab and newline are all whitespace, so your re is equivalent to > > pat = re.compile('''copyof|admin''', re.IGNORECASE) [redacted] > >To get the space between 'copy' and 'of' to be included, you have to escape >it, e.g. 'copy\ of'. D'oh! I'm an idjit, thanks for your patience. >But even if you do escape the space, I'm not sure what you expect to match. >Colon is not special to regexes (except in non-grouping parentheses (?:...) ), >so your regex expects literal colons in the string, which you don't have. Um, that is the output of the iPython shell, which I thought you used. I just copied the output into the window. It indicates an indent. I didn't mean to muddy the waters. Sorry. >Finally, in your test string you use backslash characters which you mean to be >literal backslashes, not character escapes. You should use a raw string for >this: > pat.search(r'''\\some\unc\path\Copy of somedarnfilename.exn''') Excellent, thanks for that. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Injecting Data into XML Files
I am wrestling with the incredibly vast array of XML parsing and writing documentation, and I'm not seeing (or perhaps not understanding) what I'm looking for. Here's the situation: I have a large number of XML documents to add data to. They are currently skeletal documents, looking like this: http://www.w3.org/1999/02/22-rdf-syntax-ns#";> ... What I want is to open each document and inject some data between specific sets of tags. I've been able to parse these documents, but I am not seeing how to inject data between tags so I can write it back to the file. Any pointers are appreciated. Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Injecting Data into XML Files
On Mon, Sep 11, 2006 at 09:57:28AM -0700, Dave Kuhlman wrote: >On Mon, Sep 11, 2006 at 12:11:37PM -0400, William O'Higgins Witteman wrote: >> I have a large number of XML documents to add data to. They are >> currently skeletal documents, looking like this: >> >> >> >> http://www.w3.org/1999/02/22-rdf-syntax-ns#";> >> >> >> >> ... >> >> What I want is to open each document and inject some data between >> specific sets of tags. I've been able to parse these documents, but I am >> not seeing how to inject data between tags so I can write it back to the >> file. Any pointers are appreciated. Thanks. >*How* did you parse your XML document? If you parsed it and >produced a minidom tree or, better yet, an ElementTree tree, >you can modify the DOM tree, and then you can write that tree out >to disk. I have tried the common XML modules - minidom, sax and ElementTree. There are clear, easy-to-follow examples of parsing for each one. >Here is a bit of code to give you the idea with ElementTree (or >lxml, which uses the same API as ElementTree): > >from elementtree import ElementTree as etree >doc = etree.parse('content.xml') >root = doc.getroot() ># Do something with the DOM tree here. >o This is the bit I'm missing - I can't seem to find an existing element and change it's value. When I do so I just get an additional element. Here's the code I'm using: main = etree.SubElement(root,"rdf:Description") title = etree.SubElement(main,"title") title.text = "Example Title" >o ># Now write the tree back to disk. >f = open('tmp.xml', 'w') >doc.write(f) >f.close() > >Here is info on ElementTree -- Scroll down and look at the example >in the section titled "Usage", which seems to do something very >similar to what you ask about: > >http://effbot.org/zone/element-index.htm This is, I suspect, a fine module, but the documentation you mention is not helpful to me. Specifically, in the above-mentioned section, it reads like this: # if you need the root element, use getroot root = tree.getroot() # ...manipulate tree... What I need is an example or a clear description of what they mean when they write "manipulate tree". My problem is not "which tool to use?" but "how does it work?". Thanks for the help thusfar - one last push would be greatly appreciated. Thanks again. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Injecting Data into XML Files
On Mon, Sep 11, 2006 at 02:38:46PM -0400, Kent Johnson wrote: >>>On Mon, Sep 11, 2006 at 12:11:37PM -0400, William O'Higgins Witteman >>>wrote: >>>>What I want is to open each document and inject some data between >>>>specific sets of tags. I've been able to parse these documents, but I am >>>>not seeing how to inject data between tags so I can write it back to the >>>>file. Any pointers are appreciated. Thanks. >> >>>Here is a bit of code to give you the idea with ElementTree (or >>>lxml, which uses the same API as ElementTree): >>> >>> from elementtree import ElementTree as etree >>> doc = etree.parse('content.xml') >>> root = doc.getroot() >>> # Do something with the DOM tree here. >>> o >> >>This is the bit I'm missing - I can't seem to find an existing element >>and change it's value. >That's what SubElement does - it creates a new element. You need to find >the existing element. The section on Searching should point you in the >right direction: >http://effbot.org/zone/element.htm#searching-for-subelements > >Try something like >title = >root.find('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description/title') > >Note that ET uses the URI of the namespace, not the short name. That's a huge help, thank you. What would I do if there is no namespace for the given documents? I find that a great deal of "XML" content is just well-formed ad-hoc-ery, lacking formal definitions and namespaces, and so there is no URI to put in the find argument. Do I have to find a new module? Thanks again. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Excluding branches while walking directory tree
Hello all, I am looking for an approach for the following problem: I have to walk a directory tree and examine files within it. I have a set of directory names and filename patterns that I must skip while doing this walk. How do I create a set of rules to skip files or directory branches? I'm looking for something reasonably scalable, 'cause I'm sure to need to update these rules in the future. Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Excluding branches while walking directory tree
On Wed, Sep 13, 2006 at 11:34:25AM -0400, Kent Johnson wrote: >William O'Higgins Witteman wrote: >> I have to walk a directory tree and examine files within it. I have a >> set of directory names and filename patterns that I must skip while >> doing this walk. How do I create a set of rules to skip files or >> directory branches? I'm looking for something reasonably scalable, >> 'cause I'm sure to need to update these rules in the future. First, thanks to Kent and Dave for their thoughts - a big help and much appreciated. Notes and results below, for archival posterity (so at least *I'll* know where to look for it :-) >def matchesAny(name, tests): > for test in tests: > if fnmatch.fnmatch(name, test): > return True > return False fnmatch was a good choice for this in my case, because I have to do case-insensitive matching of very simple patterns, but re or glob would provide more power if needed. I originally put the return False inside the conditional with else - but that meant that unless my name matched on the last test in tests, it would always return False. Not what I wanted. The above works very nicely without the return False line. >for dirpath, dirnames, filenames in os.walk(baseDir): > # Note use of slice assignment - you have to modify the caller's list > dirnames[:] = [ name for name in dirnames if not matchesAny(name, >dirsToSkip) ] > > filenames = [name for name in filenames if not matchesAny(name, >filesToSkip) ] > > for name in filenames: > # whatever file processing you want to do goes here The above approach was not quite what I needed, because I had a list of exclusion criteria and a list of inclusion criteria, but both could be applied to the whole path. Therefore, I used this approach: for dirpath, dirnames, filenames in os.walk(fs_path): """Filter the list of filenames to exclude elements in ToSkip""" filenames[:] = [name for name in filenames if not matches(os.path.join(dirpath,name),ToSkip)] """Filter the list of filenames to exclude elements not in ToKeep""" filenames[:] = [name for name in filenames if matches(os.path.join(dirpath,name),ToKeep)] for fname in filenames: # do what needs to be done This is getting me just the results I was looking for, and I have to say, I'm pretty pleased. Thanks again. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor