[Tutor] something relevant to array
Hi, 1] How to input some column in idle like: a a a 2] I want to combine a series of files like a.txt 1 a 2 a 3 a b.txt 1 b 2 b 3 b into one as: a b a b a b The work-in-progress code as following, #!/usr/bin/python3 import os INFILEEXT = ".xvg" NUM_OF_FILE = 10 if __name__=="__main__": result = [0]*NUM_OF_FILE for i in range(NUM_OF_FILE): filename = "A_mindist_" + str(i+1) + INFILEEXT #text = open(filename,"r").readlines() with open(filename,"r") as f: for line in f: parts = f.readline().strip() if len(parts) == 26: dist = parts.split()[1] print(dist) result[i].append(dist) print(result) $ cat A_mindist_1.xvg 4.64e+05 3.169008e-01 4.68e+05 4.319328e-01 4.72e+05 5.126960e-01 $ cat A_mindist_2.xvg 4.64e+05 5.237660e-01 4.68e+05 2.352828e-01 4.72e+05 2.280239e-01 I wish result[0] = 3.169008e-01 4.319328e-01 5.126960e-01 result[1] = 5.237660e-01 2.352828e-01 2.280239e-01 Thanks with best regards, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list mail formatting
Alexander Etter wrote: Ah I know of what you mentioned. On an GNU Emacs mailing list I was advised to avoid anything but plaintext. It just seems so archaic. But I'm a novice and will learn why eventually. There's a number of reasons. In no particular order, and in all cases "you" is generic you, not you personally. * Mastery of your tools. Are you the master of your tools, or are they the master of you? If the writer can't turn off HTML mail in common mail clients, there is little hope that he can control a compiler, an editor, source control, etc. And if he *won't* turn it off, that shows laziness and carelessness to others that reflects badly. Especially in the open source coding community, including here, your reputation is worth more than gold. * Code is plain text. Editors sometimes use colour and formatting to highlight parts of the code, but fundamentally, programming is about reading and writing code. If you need fancy fonts and formatting and dancing paperclips to get your message across, chances are you will never be more than a mediocre programmer. * Mail client independence. The people you are writing to use a wide variety of mail clients, under many different circumstances. They might be logged into a Unix server with only a primitive command-line mail app; they might be using mutt, or Thunderbird, or Outlook, or possibly not even reading it via mail at all, but via a newsgroup on Usenet. All of these programs may display your message differently. You have no control over the presentation that the user will see -- best to make the fewest assumptions, namely, plain text, and not rely on features which may be missing. * Your readers may be colour blind, and your red and green lines may look identical. Or they may be completely blind, and using a screen reader. Or they might prefer to disable HTML emails, and avoid all the dangers and problems with it (security vulnerabilities, privacy breaches, and the rest). Or they might be sick and tired of straining to reading crappy emails with light blue text on a slightly darker blue background. Either way, your formatting is lost. Don't expect people to turn on HTML display just for you. * Layout of code (especially Python code) is special. Your mail client may mangle the layout. It is very common to see code posted where all indentation is lost, or even line breaks, so everything is squashed into a single line: def func(a, b): while b < 100: print b b += 1 print a-b Or every line is separated by a blank line, which makes it a PITA to paste into the interactive interpreter. Even if the reader can fix the mangling, they shouldn't have to. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] something relevant to array
On 23 December 2011 10:01, lina wrote: > Hi, > > 1] How to input some column in idle > > like: > > a > a > a > > 2] I want to combine a series of files like > > a.txt > > 1 a > 2 a > 3 a > > b.txt > > 1 b > 2 b > 3 b > > into one as: > a b > a b > a b > > The work-in-progress code as following, > > > #!/usr/bin/python3 > > import os > > INFILEEXT = ".xvg" > > NUM_OF_FILE = 10 > > if __name__=="__main__": > result = [0]*NUM_OF_FILE > for i in range(NUM_OF_FILE): > > filename = "A_mindist_" + str(i+1) + INFILEEXT > #text = open(filename,"r").readlines() > with open(filename,"r") as f: > for line in f: > parts = f.readline().strip() > if len(parts) == 26: > dist = parts.split()[1] > print(dist) > result[i].append(dist) > print(result) > > $ cat A_mindist_1.xvg > 4.64e+05 3.169008e-01 > 4.68e+05 4.319328e-01 > 4.72e+05 5.126960e-01 > > > $ cat A_mindist_2.xvg > 4.64e+05 5.237660e-01 > 4.68e+05 2.352828e-01 > 4.72e+05 2.280239e-01 > > > I wish > result[0] = > 3.169008e-01 > 4.319328e-01 > 5.126960e-01 > > result[1] = > 5.237660e-01 > 2.352828e-01 > 2.280239e-01 > > > Thanks with best regards, > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You can't append to an int, you need to initialise your result list with lists. Instead of result = [0]*NUM_OF_FILE you need result= [ [] for i in range(NUM_OF_FILES) ] In the future, please include the error message you receive when trying to run the program. -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T. Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] something relevant to array
On 23/12/11 10:01, lina wrote: with open(filename,"r") as f: for line in f: parts = f.readline().strip() Are you sure you want to do this? You are already reading a line from the file in the for loop. This will read the next line. So parts will comprise every second line in the file. Is that what you want? if len(parts) == 26: dist = parts.split()[1] print(dist) result[i].append(dist) print(result) $ cat A_mindist_1.xvg 4.64e+05 3.169008e-01 4.68e+05 4.319328e-01 4.72e+05 5.126960e-01 $ cat A_mindist_2.xvg 4.64e+05 5.237660e-01 4.68e+05 2.352828e-01 4.72e+05 2.280239e-01 I wish result[0] = 3.169008e-01 4.319328e-01 5.126960e-01 result[1] = 5.237660e-01 2.352828e-01 2.280239e-01 This suggests you want each line so i'd expect your code to look more like with open(filename,"r") as f: for line in f: result[i].append(line.strip().split()[1]) -- 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
Re: [Tutor] something relevant to array
On Fri, Dec 23, 2011 at 6:42 PM, Alan Gauld wrote: > On 23/12/11 10:01, lina wrote: > >> with open(filename,"r") as f: >> for line in f: >> parts = f.readline().strip() > > > Are you sure you want to do this? > You are already reading a line from the file in the for loop. > This will read the next line. So parts will comprise every second line in > the file. Is that what you want? No. that's why I am so confusing now. why the results so un-expected. did not print the even line out (if the first line is odd line). > > > >> if len(parts) == 26: >> dist = parts.split()[1] >> print(dist) >> result[i].append(dist) >> print(result) >> >> $ cat A_mindist_1.xvg >> 4.64e+05 3.169008e-01 >> 4.68e+05 4.319328e-01 >> 4.72e+05 5.126960e-01 >> >> >> $ cat A_mindist_2.xvg >> 4.64e+05 5.237660e-01 >> 4.68e+05 2.352828e-01 >> 4.72e+05 2.280239e-01 >> >> >> I wish >> result[0] = >> 3.169008e-01 >> 4.319328e-01 >> 5.126960e-01 >> >> result[1] = >> 5.237660e-01 >> 2.352828e-01 >> 2.280239e-01 > > > This suggests you want each line so i'd expect your code to look more like > > > with open(filename,"r") as f: > for line in f: > result[i].append(line.strip().split()[1]) > > > -- > 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] something relevant to array
#!/usr/bin/python3 import os INFILEEXT = ".xvg" NUM_OF_FILES = 2 if __name__=="__main__": result = [ [] for i in range(NUM_OF_FILES)] for i in range(NUM_OF_FILES): filename = "A_mindist_" + str(i+1) + INFILEEXT #text = open(filename,"r").readlines() with open(filename,"r") as f: for line in f: if len(line.strip()) == 26: result[i].append(line.strip().split()[1]) for i in range(len(result)): for j in range(len(result[i])): print(result[i][j]) still have a little problem about print out, I wish to get like a a b b c c which will show in the same line, not as a b c a b c Thanks, cat A_dist_1.xvg @ legend loctype view @ legend 0.78, 0.8 @ legend length 2 @ s0 legend "r_24-r_29" 0.00e+00 2.109407e-01 4.00e+03 2.263405e-01 8.00e+03 3.234825e-01 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] something relevant to array
On 23/12/11 11:02, lina wrote: for i in range(len(result)): for j in range(len(result[i])): print(result[i][j]) You don't need all the indexing. Use Pythons for loop to get the items: for group in result: for item in group: print item, # comma prevents auto newline It's easier to read and less processing for the computer. -- 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
Re: [Tutor] something relevant to array
On Fri, Dec 23, 2011 at 3:31 PM, lina wrote: > > Hi, > [SNIPPED] > 2] I want to combine a series of files like > > a.txt > > 1 a > 2 a > 3 a > > b.txt > > 1 b > 2 b > 3 b > > into one as: > a b > a b > a b > Is this ok? a = [line.split()[1] for line in open('a.txt') if len(line.strip()) == 26] b = [line.split()[1] for line in open('b.txt') if len(line.strip()) == 26] both = zip(a, b) Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] something relevant to array
On 2011-12-23 12:02, lina wrote: for i in range(len(result)): for j in range(len(result[i])): print(result[i][j]) still have a little problem about print out, I wish to get like a a b b c c which will show in the same line, not as a b c a b c So you wish to print all the first elements from your sublists on the first line, all the second elements on the second line, and so on, right? Python 3.2 (r32:88445, Mar 25 2011, 19:28:28) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> result = [["a1", "b1", "c1"],["a2", "b2", "c2"],["a3", "b3", "c3"]] >>> for i in zip(*result): ... print(" ".join(i)) ... a1 a2 a3 b1 b2 b3 c1 c2 c3 Explanation: "zip()" takes an arbitrary number of iterables and "returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables." (see the docs on http://docs.python.org/py3k/library/functions.html#zip): >>> print(list(zip([1, 2, 3], [4, 5, 6]))) [(1, 4), (2, 5), (3, 6)] In your case, you would have to call "zip()" with zip(result[0], result[1], result[2], ... result[x]) depending on how many files you process. But using the *-operator you can unpack "result" (which is a list of sublists), so that "zip" will see all the sublists as separate arguments. See also http://docs.python.org/py3k/tutorial/controlflow.html#unpacking-argument-lists For printing you just join all the elements of one tuple to a string. HTH, Andreas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Unable to remove three libs from XP
I have three py libs and the python program itself, 2.52, installed on an 6 year old HP Laptop. I decided to remove them, and removed Python with the Control Panel Add/Remove icon. Worked fine. When I tried to remove any of the remaining libs, press the add/remove button does nothing but blink. How do I get around this problem? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39° 15' 7" N, 121° 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] possibly a version error
On 22/12/2011 18:13, Cranky Frankie wrote: I got it to work: Use this for the import - import urllib.request the use this: dom = minidom.parse(urllib.request.urlopen(url)) Here's the code that works in 3.2: from pprint import pprint import urllib.request from xml.dom import minidom WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s' WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' def weather_for_zip(zip_code): url = WEATHER_URL % zip_code dom = minidom.parse(urllib.request.urlopen(url)) forecasts = [] for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'): forecasts.append({ 'date': node.getAttribute('date'), 'low': node.getAttribute('low'), 'high': node.getAttribute('high'), 'condition': node.getAttribute('text') }) ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0] return { 'current_condition': ycondition.getAttribute('text'), 'current_temp': ycondition.getAttribute('temp'), 'forecasts': forecasts, 'title': dom.getElementsByTagName('title')[0].firstChild.data } pprint(weather_for_zip(12303)) Hello, I tried it and it works fine (Python 3.2, Windows XP (5.1.2600) ) Here's what I got: {'current_condition': 'Light Rain', 'current_temp': '37', 'forecasts': [{'condition': 'AM Rain/Snow', 'date': '23 Dec 2011', 'high': '39', 'low': '16'}, {'condition': 'Partly Cloudy', 'date': '24 Dec 2011', 'high': '31', 'low': '20'}], 'title': 'Yahoo! Weather - Schenectady, NY'} I'll probably tinker with it to make it show the weather here in Algiers (Algeria, North Africa). Thanks, -- ~Jugurtha Hadjar, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] something relevant to array
On Fri, Dec 23, 2011 at 8:19 PM, Andreas Perstinger wrote: > On 2011-12-23 12:02, lina wrote: >> >> for i in range(len(result)): >> for j in range(len(result[i])): >> print(result[i][j]) >> >> still have a little problem about print out, >> >> I wish to get like >> a a >> b b >> c c >> which will show in the same line, >> >> not as >> a >> b >> c >> a >> b >> c > > > So you wish to print all the first elements from your sublists on the first > line, all the second elements on the second line, and so on, right? yes. > > Python 3.2 (r32:88445, Mar 25 2011, 19:28:28) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. result = [["a1", "b1", "c1"],["a2", "b2", "c2"],["a3", "b3", "c3"]] for i in zip(*result): > ... print(" ".join(i)) > ... > a1 a2 a3 > b1 b2 b3 > c1 c2 c3 > > Explanation: > "zip()" takes an arbitrary number of iterables and "returns an iterator of > tuples, where the i-th tuple contains the i-th element from each of the > argument sequences or iterables." (see the docs on > http://docs.python.org/py3k/library/functions.html#zip): > print(list(zip([1, 2, 3], [4, 5, 6]))) > [(1, 4), (2, 5), (3, 6)] > > In your case, you would have to call "zip()" with > > zip(result[0], result[1], result[2], ... result[x]) > > depending on how many files you process. > > But using the *-operator you can unpack "result" (which is a list of > sublists), so that "zip" will see all the sublists as separate arguments. > See also > http://docs.python.org/py3k/tutorial/controlflow.html#unpacking-argument-lists > > For printing you just join all the elements of one tuple to a string. > > HTH, Andreas Thanks for all. really good suggestions. Best regards and have a weekend. > > ___ > 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 challenge and decryption
Hi again list! I've been trying to implement the feedback I got. So far, I removed the print statements from the function, limited the range (just for the z at the moment) and tried to get all printing in one or two lines... but without success... I don't know if I'm doing the join as it should... The new list I ended up trying to populate it with 2 different ways, but without success when joined... This is the new (and a improved) code: import string def decrypt(cypheredText, shiftedCypherNumber): ''' This function will take two arguments. The first is the cyphered text, the second is the number of characters we need to shift the text so we can decrypt it. This is a Caesar cypher. ''' for letter in cypheredText: asciiValue = ord(letter) if asciiValue in range(97, 123): asciiValue += shiftedCypherNumber if asciiValue > 122: asciiValue -= 26 newLetter = chr(asciiValue) text = list() text.append(newLetter) joinedText = ' '.join(text) return joinedText text = 'g fmnc wms bgblr rpylqjyrc gr zw fylb' a = decrypt(text, 2) print a For the new list (text), I initially tried to do it like this -> text = list(newLetter) and only now resorted to the append... which way is more correct? Or which is not correct at all? And why is the return giving me just one letter? (the last one...) Thanks for all the tips so far. The maketrans like suggested probably would be faster but I didn't knew about it and now that I'm trying to grind this on my own I kind of prefer it... I'm learning more then if I used a function or something... The ASCII table was invaluable in making me rethink my approach! Merry Christmas to all in the list! In case someone doesn't believe in it, have a very nice weekend and all the best! Joaquim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python challenge and decryption
Posting as HTML caused your indentation to be all wrong. Try to post as plain text to remove those errors. Thankfully your program is not very complicated. import string def decrypt(cypheredText, shiftedCypherNumber): ''' This function will take two arguments. The first is the cyphered text, the second is the number of characters we need to shift the text so we can decrypt it. This is a Caesar cypher. ''' for letter in cypheredText: asciiValue = ord(letter) if asciiValue in range(97, 123): asciiValue += shiftedCypherNumber if asciiValue > 122: asciiValue -= 26 newLetter = chr(asciiValue) text = list() text.append(newLetter) joinedText = ' '.join(text) return joinedText text = 'g fmnc wms bgblr rpylqjyrc gr zw fylb' a = decrypt(text, 2) print a You have very little range checking which means that it is very likely to not work (or behave oddly) for unexpected values. The biggest flaw I see is that your list is created at the wrong level. It should be outside the for loop. The problem with list creation being in the for loop is that you create a new list each iteration of the for loop and what happens to the old list? You lose it. If you created the list outside the for loop and my indentation above is incorrect then you created and appended to it after finishing your for loop. This would be incorrect because what would happen to all the values calculated inside the for loop? They would be lost. Either way, it is incorrect. You should declare text before the for loop and then append to it inside the for loop. The above is why you only get one letter and also why text=list(newLetter) is incorrect for your problem. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python challenge and decryption
On 23/12/11 16:58, Joaquim Santos wrote: Thanks for all the tips so far. The maketrans like suggested probably would be faster but I didn't knew about it That's exactly the point. Very few people know about maketrans before they take the Python Challenge. But that's the whole point of the challenge, as you go through it you will discover new and powerful tools in the Python library that save you from having to invent your own. (Look out for the hints and pointers in the challenge!) If you try to complete the Python challenge without using new modules you will have a very long project in front of you!! -- 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
Re: [Tutor] Unable to remove three libs from XP
This is a laugher. The Add/Remove screen was hiding a dialog that wanted to know if I really wanted to remove the program. Argh. On 12/23/2011 4:56 AM, Wayne Watson wrote: I have three py libs and the python program itself, 2.52, installed on an 6 year old HP Laptop. I decided to remove them, and removed Python with the Control Panel Add/Remove icon. Worked fine. When I tried to remove any of the remaining libs, press the add/remove button does nothing but blink. How do I get around this problem? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39° 15' 7" N, 121° 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unable to remove three libs from XP
>This is a laugher. The Add/Remove screen was hiding a dialog that >wanted to know if I really wanted to remove the program. Argh. This is why I try and avoid pop-ups when I create a GUI app. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Television simulation
Im trying to create a 'Television simulation' program. Heres the code ive written for it: #television simulation #a program that simulates a television #the user can turn the television on or off, change the volume or change the channel #create the television class class Television(object): """A virtual television simulation""" def __init__(self): print("The television is off.") def power_button(self, power = "off"): if power == "off": power = "on" print("The power is now on.") else: power = "off" print("The power is now off.") def volume_button(self, volume = 0): up_or_down = input("Do you want to increase or decrease the volume? (up/down): ") if up_or_down == "up": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume > 10: volume = 10 print("The volume is now",volume) elif up_or_down == "down": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume < 0: volume = 0 print("The volume is now",volume) else: print("That is not a valid choice.") def channel_button(self, channel = 1): new_channel = int(input("What channel do you want to watch? (Enter a number between 1 and 10.): ")) if new_channel < 1 or new_channel > 10: print("That is not a valid channel!") else: channel = new_channel print("The channel is now",channel) #create the main part of the program, the television simulation def main(): tv = Television() choice = None while choice != "0": print \ (""" Television simulation 0 - Quit 1 - Turn the television on or off 2 - Change the volume 3 - Change the channel """) choice = input("Choice: ") print() #exit if choice == "0": print("Good-bye.") #turn the television on or off elif choice == "1": tv.power_button() #increase or decrease the volume elif choice == "2": tv.volume_button() #change the channel elif choice == "3": tv.channel_button() else: print("\nInvalid choice!") main() ("\n\nPress the enter key to exit.") It works fine but the problem im having is that when volume, channel or power are changed inside of their methods, their values dont change in the program if that makes sense. So i was just wondering if there was a way around this. Thanks in advance, Myles Broomes ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Television simulation
On 12/23/2011 04:21 PM, myles broomes wrote: Im trying to create a 'Television simulation' program. Heres the code ive written for it: #television simulation #a program that simulates a television #the user can turn the television on or off, change the volume or change the channel #create the television class class Television(object): """A virtual television simulation""" def __init__(self): print("The television is off.") def power_button(self, power = "off"): if power == "off": power = "on" The above line does nothing useful, as the value is thrown out when the method returns. Same is true in several other places below. print("The power is now on.") else: power = "off" print("The power is now off.") def volume_button(self, volume = 0): up_or_down = input("Do you want to increase or decrease the volume? (up/down): ") if up_or_down == "up": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume> 10: volume = 10 print("The volume is now",volume) elif up_or_down == "down": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume< 0: volume = 0 print("The volume is now",volume) else: print("That is not a valid choice.") def channel_button(self, channel = 1): new_channel = int(input("What channel do you want to watch? (Enter a number between 1 and 10.): ")) if new_channel< 1 or new_channel> 10: print("That is not a valid channel!") else: channel = new_channel print("The channel is now",channel) #create the main part of the program, the television simulation def main(): tv = Television() choice = None while choice != "0": print \ (""" Television simulation 0 - Quit 1 - Turn the television on or off 2 - Change the volume 3 - Change the channel """) choice = input("Choice: ") print() #exit if choice == "0": print("Good-bye.") #turn the television on or off elif choice == "1": tv.power_button() #increase or decrease the volume elif choice == "2": tv.volume_button() #change the channel elif choice == "3": tv.channel_button() else: print("\nInvalid choice!") main() ("\n\nPress the enter key to exit.") It works fine but the problem im having is that when volume, channel or power are changed inside of their methods, their values dont change in the program if that makes sense. So i was just wondering if there was a way around this. Normally when such values are changed in the method, you want a corresponding attribute of the instance to 'remember' the value. In your particular program you have one instance, called tv. Each time you call a method on that instance, such as tv.power_button(), you are implicitly passing that instance to the method, as the value 'self'. That's what you're not writing to correctly. Inside a method, you usually refer to such instance attributes as self.attribname. So let's try just one of them, the power button. def power_button(self): if self.power == "off": self.power = "on" else: self.power = 'off' print "Power is now ", self.power Notice I got rid of the unused parameter, since it was never referenced. One other thing we must do here: In the __init__() method, you need to initialize the state of the Television instance. You can't just print a statement saying it's initialized, you have to create each of the attributes comprising its initial state. In our case, we'd add a line self.power = "off" I'll leave the other two attributes to you. There are other things I could critique, but I want to give you the minimum push to make something that could run. -- DaveA __
Re: [Tutor] Television simulation
On 12/23/2011 04:43 PM, Dave Angel wrote: On 12/23/2011 04:21 PM, myles broomes wrote: Im trying to create a 'Television simulation' program. Heres the code ive written for it: #television simulation #a program that simulates a television #the user can turn the television on or off, change the volume or change the channel #create the television class class Television(object): """A virtual television simulation""" def __init__(self): print("The television is off.") def power_button(self, power = "off"): if power == "off": power = "on" The above line does nothing useful, as the value is thrown out when the method returns. Same is true in several other places below. print("The power is now on.") else: power = "off" print("The power is now off.") def volume_button(self, volume = 0): up_or_down = input("Do you want to increase or decrease the volume? (up/down): ") if up_or_down == "up": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume> 10: volume = 10 print("The volume is now",volume) elif up_or_down == "down": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume< 0: volume = 0 print("The volume is now",volume) else: print("That is not a valid choice.") def channel_button(self, channel = 1): new_channel = int(input("What channel do you want to watch? (Enter a number between 1 and 10.): ")) if new_channel< 1 or new_channel> 10: print("That is not a valid channel!") else: channel = new_channel print("The channel is now",channel) #create the main part of the program, the television simulation def main(): tv = Television() choice = None while choice != "0": print \ (""" Television simulation 0 - Quit 1 - Turn the television on or off 2 - Change the volume 3 - Change the channel """) choice = input("Choice: ") print() #exit if choice == "0": print("Good-bye.") #turn the television on or off elif choice == "1": tv.power_button() #increase or decrease the volume elif choice == "2": tv.volume_button() #change the channel elif choice == "3": tv.channel_button() else: print("\nInvalid choice!") main() ("\n\nPress the enter key to exit.") It works fine but the problem im having is that when volume, channel or power are changed inside of their methods, their values dont change in the program if that makes sense. So i was just wondering if there was a way around this. Normally when such values are changed in the method, you want a corresponding attribute of the instance to 'remember' the value. In your particular program you have one instance, called tv. Each time you call a method on that instance, such as tv.power_button(), you are implicitly passing that instance to the method, as the value 'self'. That's what you're not writing to correctly. Inside a method, you usually refer to such instance attributes as self.attribname. So let's try just one of them, the power button. def power_button(self): if self.power == "off": self.power = "on" else: self.power = 'off' print "Power is now ", self.power Notice I got rid of the unused parameter, since it was never referenced. One other thing we must do here: In the __init__() method, you need to initialize the state of the Television instance. You can't just print a statement saying it's initialized, you have to create each of the attributes comprising its initial state. In our case, we'd add a line self.power = "off" I'll leave the other two attributes to you. There are other things I could critique, but I want to give you the minimum push to make something that could run. Bah - It lined up when I typed it, but I pasted some of the original, and typed the rest. Probably your em
Re: [Tutor] possibly a version error
> Date: Fri, 23 Dec 2011 14:04:17 +0100 > From: jugurtha.had...@gmail.com > To: tutor@python.org > Subject: Re: [Tutor] possibly a version error > > On 22/12/2011 18:13, Cranky Frankie wrote: > > I got it to work: > > > > Use this for the import - import urllib.request > > > > the use this: dom = minidom.parse(urllib.request.urlopen(url)) > > > > Here's the code that works in 3.2: > > > > from pprint import pprint > > import urllib.request > > from xml.dom import minidom > > > > WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s' > > WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' > > > > def weather_for_zip(zip_code): > > url = WEATHER_URL % zip_code > > dom = minidom.parse(urllib.request.urlopen(url)) > > forecasts = [] > > for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'): > > forecasts.append({ > > 'date': node.getAttribute('date'), > > 'low': node.getAttribute('low'), > > 'high': node.getAttribute('high'), > > 'condition': node.getAttribute('text') > > }) > > ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0] > > return { > > 'current_condition': ycondition.getAttribute('text'), > > 'current_temp': ycondition.getAttribute('temp'), > > 'forecasts': forecasts, > > 'title': dom.getElementsByTagName('title')[0].firstChild.data > > } > > > > pprint(weather_for_zip(12303)) > > > > Hello, > > I tried it and it works fine (Python 3.2, Windows XP (5.1.2600) ) > > Here's what I got: > > {'current_condition': 'Light Rain', > 'current_temp': '37', > 'forecasts': [{'condition': 'AM Rain/Snow', > 'date': '23 Dec 2011', > 'high': '39', > 'low': '16'}, > {'condition': 'Partly Cloudy', > 'date': '24 Dec 2011', > 'high': '31', > 'low': '20'}], > 'title': 'Yahoo! Weather - Schenectady, NY'} > > > I'll probably tinker with it to make it show the weather here in Algiers > (Algeria, North Africa). > > Thanks, > > > -- > ~Jugurtha Hadjar, I'm a newbie, but I played around with your code to see if I could get it to work in 2.7 and it required changing the same line to: dom = minidom.parse(urllib.URLopener().open(url)) Just in case someone here were to find that helpful. Mike Harleman ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] insert queries into related tables referencing foreign keys using python
So... most python-sqlite tutorials concentrate on single tables. The few that deal with multiple tables and that mention foreign keys and such seem to demonstrate mainly using hard-coded data instead of parameterized insert queries into tables with auto-increment primary keys. For the most part I'm able to figure things out as I go using a variety of documents both print and electronic... but when I don't *know* the pk number (because its automatically assigned) it makes it tough to supply it as a foreign key for another insert query into related tables. Whats the 'right' way to do this sort of record insert or update query? Insert into the main table first, then do a select query to find the last rowid and store it in a python variable and then use that as a parameter for the rest of the insert queries to related tables? Pull the value from the seq column of the sqlite-sequence table for the table with the primary key, and use that (not sure how robust that would be down the road, or how portable it would be if I later moved to MySQL for the DB)? Or is this something an ORM like SQLalchemy would smooth over for me? In part I'm (also) wondering if this may be an artificial problem, as I'm trying to import data from a csv file i.e. one big table and then break it up and insert it into multiple tables in the sqlite database... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python challenge and decryption
> That's exactly the point. > Very few people know about maketrans before they take the Python Challenge. > > But that's the whole point of the challenge, as you go through it you will > discover new and powerful tools in the Python library that save you from > having to invent your own. (Look out for the hints and pointers in the > challenge!) > > If you try to complete the Python challenge without using new modules you > will have a very long project in front of you!! > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ Exactly. That's how I found out about it - after solving the challenge the other way! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] insert queries into related tables referencing foreign keys using python
On 12/24/2011 11:07 AM, Monte Milanuk wrote: So... most python-sqlite tutorials concentrate on single tables. The few that deal with multiple tables and that mention foreign keys and such seem to demonstrate mainly using hard-coded data instead of parameterized insert queries into tables with auto-increment primary keys. For the most part I'm able to figure things out as I go using a variety of documents both print and electronic... but when I don't *know* the pk number (because its automatically assigned) it makes it tough to supply it as a foreign key for another insert query into related tables. In sqlite, if a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID (http://www.sqlite.org/autoinc.html). In python-sqlite, the rowid of the last insert operation can be queried using cursor.lastrowid. Therefore, you can query the lastrowid, right after the insert, to find the primary key of the value you had just inserted. So, in code: ... cur = conn.execute('INSERT ... ') pk = cur.lastrowid ... or even: ... pk = conn.execute('INSERT ... ').lastrowid ... Be careful that in multithreaded program, each thread should have their own cursors, or otherwise another thread could possibly do another insert before you can query the lastrowid. Whats the 'right' way to do this sort of record insert or update query? Insert into the main table first, then do a select query to find the last rowid and store it in a python variable and then use that as a parameter for the rest of the insert queries to related tables? Pull the value from the seq column of the sqlite-sequence table for the table with the primary key, and use that (not sure how robust that would be down the road, or how portable it would be if I later moved to MySQL for the DB)? Or is this something an ORM like SQLalchemy would smooth over for me? In part I'm (also) wondering if this may be an artificial problem, as I'm trying to import data from a csv file i.e. one big table and then break it up and insert it into multiple tables in the sqlite database... In general, despite the superficial similarities, most database engine wrappers have their own ways of doing stuffs. Generally, you need a full-blown ORM to smooth out the differences. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A few Python Mysteries [Reset]
On 12/23/2011 03:20 PM, Wayne Watson wrote: Hi, I found it, but not in a place I would expect. It's under my username, Wayne. It is a folder and has three files: breakpoints.lst recent-files.lst ZZrecent-files.lst The last one has the odd ZZ, but is empty. breakpoints.lst is empty too. That certainly is curious, have you tried renaming ZZrecent-files.lst to recent-file.lst? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor