From chris at chrisdown.name Sun Sep 1 00:13:12 2013 From: chris at chrisdown.name (Chris Down) Date: Sun, 1 Sep 2013 00:13:12 +0200 Subject: [Tutor] how to save variables after a user quits in python In-Reply-To: <1377984636.28529.YahooMailNeo@web124502.mail.ne1.yahoo.com> References: <1377984636.28529.YahooMailNeo@web124502.mail.ne1.yahoo.com> Message-ID: <20130831221312.GA4490@chrisdown.name> On 2013-08-31 14:30, Jack Little wrote: > I am coding a game and I want the player to be able to quit the game and > immediately take off right from where they started from. If you're asking how to store variables between sessions, look at the pickle module. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From steve at pearwood.info Sun Sep 1 02:07:02 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 01 Sep 2013 10:07:02 +1000 Subject: [Tutor] how to save variables after a user quits in python In-Reply-To: <1377984636.28529.YahooMailNeo@web124502.mail.ne1.yahoo.com> References: <1377984636.28529.YahooMailNeo@web124502.mail.ne1.yahoo.com> Message-ID: <52228526.40203@pearwood.info> On 01/09/13 07:30, Jack Little wrote: > I am coding a game and I want the player to be able to quit the game and immediately take off right from where they started from. That is trickier than it sounds. You have to save the internal state of the game, which means you first have to *identify* the internal state of the game. That means: * everything about the user: name, health, score, ammunition, treasure, etc.; * everything about every enemy: whether they are alive or dead, health, ammunition, etc.; * everything about the internal state of the game: which parts of the game have already been visited, which parts haven't been; * position of the user; * anything else I have forgotten. Once you have identified all of those things, then and only then can you start thinking about the best way to save that information to disk. Depending on what you need to save, you can then decide what module is best suited to that type of data. There are many choices: http://docs.python.org/2/library/persistence.html http://docs.python.org/2/library/fileformats.html http://docs.python.org/2/library/json.html http://docs.python.org/2/library/xml.html It is difficult to tell what would be best without knowing what you need to save. Possibly as little as a Windows-style INI file would be enough: [settings] key: value possibly you will need a custom solution that dumps the entire state of the Python interpreter to disk, then later restores it. -- Steven From eryksun at gmail.com Sun Sep 1 07:30:21 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 1 Sep 2013 01:30:21 -0400 Subject: [Tutor] myown.getfilesystemencoding() In-Reply-To: References: <1377875054.96190.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Sat, Aug 31, 2013 at 9:16 AM, Oscar Benjamin wrote: > Spyder has both an internal interpreter and an external interpreter. > One is the same interpreter process that runs the Spyder GUI. The > other is run in a subprocess which keeps the GUI safe but reduces your > ability to inspect the workspace data via the GUI. So presumable > Albert means the "external" interpreter here. I installed Spyder on Windows to look into this. It's using Qt QProcess to run the external interpreter in a child process. sys.stdin.isatty() confirms it's not a tty, and Process Explorer confirms that all 3 standard I/O handles (from msvcrt.get_osfhandle()) are pipes. The file encoding is None for piped standard I/O, so printing unicode falls back to the default encoding. Normally this is ASCII in 2.x, but Spyder uses sitecustomize to set the default encoding based on the default locale. It also sets the hidden console's codepage: if os.name == 'nt': # Windows platforms # Setting console encoding (otherwise Python does not # recognize encoding) try: import locale, ctypes _t, _cp = locale.getdefaultlocale('LANG') try: _cp = int(_cp[2:]) ctypes.windll.kernel32.SetConsoleCP(_cp) ctypes.windll.kernel32.SetConsoleOutputCP(_cp) except (ValueError, TypeError): # Code page number in locale is not valid pass except ImportError: pass http://code.google.com/p/spyderlib/source/browse/spyderlib/ widgets/externalshell/sitecustomize.py?name=v2.2.0#74 Probably this was added for a good reason, but I don't grok the point. Python isn't interested in the hidden console window at this stage, and the standard handles are all pipes. I didn't notice any difference with these lines commented out, running with Python 2.7.5. YMMV There's a design flaw here since sys.stdin.encoding is used by the parser in single-input mode. With it set to None, Unicode literals entered in the REPL will be incorrectly parsed if they use non-ASCII byte values. For example, given the input is Windows 1252, then u'?' will be parsed as u'\x80' (i.e. PAD, a C1 Control code). Here's an alternative to messing with the default encoding -- at least for the new version of Spyder that doesn't have to support 2.5. Python 2.6+ checks for the PYTHONIOENCODING environment variable. This overrides the encoding/errors values in Py_InitializeEx(): http://hg.python.org/cpython/file/70274d53c1dd/Python/pythonrun.c#l265 You can test setting PYTHONIOENCODING without restarting Spyder. Just bring up Spyder's "Internal Console" and set os.environ['PYTHONIOENCODING']. The change applies to new interpreters started from the "Interpreters" menu. Spyder could set this itself in the environment that gets passed to the QProcess object. From bgailer at gmail.com Sun Sep 1 23:57:59 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 01 Sep 2013 17:57:59 -0400 Subject: [Tutor] [Python-Help] Please help replace Long place-names with short place-names in many files with Python In-Reply-To: References: Message-ID: <5223B867.2050004@gmail.com> Welcome. We are a few volunteers who like to help you when you have tried something and are stuck. It is best to post to just one email list. Most of us monitor tutor and help. We don't write programs for you. Some of us would be happy to do that for a consulting fee. Why Python? What other programming experience do you have? Do you know the basics: getting a list of filenames in a directory? loops? opening and reading / writing files? searching for strings in larger strings? replacing strings? OMG I just wrote the outline of your program! Try writing a program to do some of the above then come back with questions. Start with something simple - process just one file. Or hire me as a consultant and I will write it for you. [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC From mcptrad at gmail.com Sun Sep 1 22:19:19 2013 From: mcptrad at gmail.com (mc UJI) Date: Sun, 1 Sep 2013 22:19:19 +0200 Subject: [Tutor] Please help replace Long place-names with short place-names in many files with Python Message-ID: Dear Pythonistas, I am totally new to Python. This means a know the basics. And by basics I mean the very, very basics. I have a problem with which I need help. in short, I need to: a) Open many files (in a dir) with an .html extension b) Find Long name-places (Austria) c) Replace them by short name.places (AT) d) In the context of the xml tags ( and ) At length: I have many xml files containing a day of speeches at the European Parliament each file. Each file has some xml-label for the session metadata and then the speakers (MPs) interventions. These interventions consist of my metadata and text. I include here a sample of two speeches (Please pay attention to xml labels and ): **************************************************************************************** SAMPLE OF INTERVENTIONS Knapman, Roger 19440220 Crediton NA male UK Independence Party on behalf of the group

Mr President, Mr Juncker's speech was made with all the passion that a civil servant is likely to raise.

Mr Juncker, you say that the Stability and Growth Pact will be your top priority, but your past statements serve to illustrate only the inconsistencies. Whilst I acknowledge that you played a key role in negotiating the pact's original rules, you recently said that the credibility of the pact had been buried and that the pact was dead. Is that still your opinion?

You also said that you have a window of opportunity to cut a quick deal on the EU budget, including the British rebate of some EUR 4 billion a year. Is that so, Mr Juncker? The rebate took five years to negotiate. If your comments are true and you can cut a deal by June, then Mr Blair must have agreed in principle to surrender the rebate. Is that the case? With whom in the British Government precisely are you negotiating? Will the British electorate know about this at the time of the British general election, probably in May?

Finally, the UK Independence Party, and in particular my colleague Mr Farage, has drawn attention to the criminal activities of more than one Commissioner. More details will follow shortly and regularly. Are you to be tainted by association with them, or will you be expressing your concerns and the pressing need for change?

Angelilli, Roberta 19650201 Roma NA female Alleanza nazionale on behalf of the group

Mr President, the Luxembourg Presidency?s programme is packed with crucial issues for the future of Europe, including the priorities on the economic front: the Lisbon strategy, reform of the Stability Pact and approval of the financial perspective up to 2013.

My first point is that it will soon be time for the mid-term review of the level of implementation of the Lisbon strategy. To give it a greater chance of success, the programme needs to make the individual Member States responsible for achieving the targets that were set. To that end, I consider the proposal to specify an individual at national level to be responsible for putting the strategy into practice to be a very useful idea.

Secondly, with regard to the review of the Stability Pact, it has also been emphasised this morning that a reform is needed which can propose a more flexible interpretation of the Pact during times of recession, without bypassing the Maastricht criteria and without giving up the commitment to reduce the debt. I am also convinced that steps could be taken to exclude certain specific types of investment from the calculation of the deficit in order to give a new boost to Europe?s growth and competitiveness.

Thirdly, I hope that we can really succeed in approving the financial perspective up to 2013 by June, so that the resources can be used to the full from the very beginning of the period in question. I especially hope that the proposals ? the Council?s and the Commission?s proposals on those important topics ? are adequately discussed in advance by Parliament which, let us recall, is the only European institution that directly represents the sovereignty of the people.

Lastly, I hope that a European civil protection agency will at last be set up during the Luxembourg Presidency so that natural disasters can be dealt with in an appropriate manner, with particular emphasis on prevention.

END OF SAMPLE OF INTERVENTIONS ************************************************************************************* Now, as you see, label: and Have long place-names. For instance and But I would like short place-names (UK instead of United Kingdom, for instance) The long-names I have are all the members of the European Union. ************************************************************************************ LIST OF LONG PLACE-NAMES AND EQUIVALENT SHORT PLACE-NAMES Austria = AT Belgium = BE Bulgaria = BG Croatia = HR Cyprus = CY Czech Republic = CS Denmark = DK Estonia = EE Finland = FI France = FR Germany = DE Greece = GR Hungary = HU Ireland = IE Italy = IT Latvia = LV Lithuania = LT Luxembourg = LU Malta = MT Netherlands = NL Poland = PL Portugal = PT Romania = RO Slovakia = SK Slovenia = SI Spain = ES Sweden = SE United Kingdom = GB ************************************************************************************* TO SUM UP I am in despair at this point. Is there a way to use Python (dictionaries and regular expressions or whatever is suitable to: a) Open many files with an .html extension b) Find Long name-places (Austria) c) Replace them by short name.places (AT) d) In the context of the xml tags mentioned above. Please i NEED YOUR HELP Many thanks for your patience. Mar?a -------------- next part -------------- An HTML attachment was scrubbed... URL: From nickwilson88 at hotmail.com Sun Sep 1 23:53:43 2013 From: nickwilson88 at hotmail.com (Nick Wilson) Date: Mon, 2 Sep 2013 09:53:43 +1200 Subject: [Tutor] input loop Message-ID: Hi, I am trying to create a portfolio of shares, each share is entered manually while checking it against a list of actual share codes.Its working mostly as intended at the moment, except when I print the table out at the end, I want all entered details printed as such Enter command: addEnter share code to add: tpwTPW = TrustPowerEnter share price: 2Enter share quantity: 5Enter command: print----------------------------------Code Price Quant Value----------------------------------TPW 2.00 5 10.00----------------------------------Total cost: 10.00================================== **(This is all even when displayed in Wing101) So thats all fine, but I'm wanting muiltiple more rows printed underneath with other shares and their prices etc. Getting stuck on that, I know i'll need a for loop to iterate over the input but still wanting to get some help. here's the rest of the code so far. PROMPT_FOR_COMMAND = 'Enter command: 'PROMPT_FOR_CODE = 'Enter share code to add: 'PROMPT_FOR_PRICE = 'Enter share price: 'PROMPT_FOR_QUANTITY = 'Enter share quantity: ' MESSAGE_UNKNOWN_COMMAND ='Unknown command - please try again.'MESSAGE_UNKNOWN_CODE = 'Unknown code - CANCELLING code entry.'MESSAGE_PORTFOLIO_EMPTY = 'No shares in portfolio.'MESSAGE_GOODBYE = 'Thankyou and goodbye.' TITLE_TEMPLATE = '{:<6}{:>8}{:>8}{:>12}'LINE_ITEM_TEMPLATE = '{:<6}{:>8.2f}{:>8}{:>12.2f}'LINE_TOTAL_TEMPLATE = '{:<20}{:>14.2f}'SPACER_LINE = 34 * '-'DBL_SPACE_LINE = 34 * "=" def print_portfolio_table(portfolio): """ Prints out a portfolio table as per specification. You can use the test_print_portfolio_table to test this function...""" print(SPACER_LINE) print(TITLE_TEMPLATE.format("Code", "Price", "Quant", "Value")) print(SPACER_LINE) print(LINE_ITEM_TEMPLATE.format(code, price, quant, (price * quant))) print(SPACER_LINE) print(LINE_TOTAL_TEMPLATE.format("Total cost:", (price * quant))) print(DBL_SPACE_LINE) def process_add_code(portfolio): """Receives a portfolio list. Asks for a share code. If it's in the exchange then prints code = fullname then gets price and quantity from the user then it appends the (code, price, quantity) to the portfolio""" global code code = input(PROMPT_FOR_CODE).upper() if shares.in_exchange(code) == True: print(code + " " + "=" + " " + shares.get_name(code)) global price price = float(input(PROMPT_FOR_PRICE)) global quant quant = int(input(PROMPT_FOR_QUANTITY)) portfolio = portfolio.append([code, price, quant]) main() else: print(MESSAGE_UNKNOWN_CODE) main() def main(): """This is the main function for the program, ie, this function is called first when the program is run""" # The portfolio list will contain tuples as (code, price, quantity) # Initially it is empty portfolio = [] command = input(PROMPT_FOR_COMMAND).lower() if command == 'add': return portfolio.append(process_add_code(portfolio)) if command == "print" and len(portfolio) <= 1: print_portfolio_table(portfolio) return main() if command == "quit": print(MESSAGE_GOODBYE) -------------- next part -------------- An HTML attachment was scrubbed... URL: From majeedkhn89 at gmail.com Sun Sep 1 19:06:47 2013 From: majeedkhn89 at gmail.com (Majeed Khan) Date: Sun, 1 Sep 2013 19:06:47 +0200 Subject: [Tutor] Tutor Digest, Vol 115, Issue 2 In-Reply-To: References: Message-ID: help On Sun, Sep 1, 2013 at 12:00 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: myown.getfilesystemencoding() (eryksun) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 1 Sep 2013 01:30:21 -0400 > From: eryksun > To: Oscar Benjamin , Albert-Jan Roskam > > Cc: Python Mailing List > Subject: Re: [Tutor] myown.getfilesystemencoding() > Message-ID: > < > CACL+1asFy+SO2bT3UbNdP7vJTkHMuMiLmDekf9NJtMJkjHKARQ at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Sat, Aug 31, 2013 at 9:16 AM, Oscar Benjamin > wrote: > > Spyder has both an internal interpreter and an external interpreter. > > One is the same interpreter process that runs the Spyder GUI. The > > other is run in a subprocess which keeps the GUI safe but reduces your > > ability to inspect the workspace data via the GUI. So presumable > > Albert means the "external" interpreter here. > > I installed Spyder on Windows to look into this. It's using Qt > QProcess to run the external interpreter in a child process. > sys.stdin.isatty() confirms it's not a tty, and Process Explorer > confirms that all 3 standard I/O handles (from msvcrt.get_osfhandle()) > are pipes. > > The file encoding is None for piped standard I/O, so printing unicode > falls back to the default encoding. Normally this is ASCII in 2.x, but > Spyder uses sitecustomize to set the default encoding based on the > default locale. It also sets the hidden console's codepage: > > if os.name == 'nt': # Windows platforms > > # Setting console encoding (otherwise Python does not > # recognize encoding) > try: > import locale, ctypes > _t, _cp = locale.getdefaultlocale('LANG') > try: > _cp = int(_cp[2:]) > ctypes.windll.kernel32.SetConsoleCP(_cp) > ctypes.windll.kernel32.SetConsoleOutputCP(_cp) > except (ValueError, TypeError): > # Code page number in locale is not valid > pass > except ImportError: > pass > > http://code.google.com/p/spyderlib/source/browse/spyderlib/ > widgets/externalshell/sitecustomize.py?name=v2.2.0#74 > > Probably this was added for a good reason, but I don't grok the point. > Python isn't interested in the hidden console window at this stage, > and the standard handles are all pipes. I didn't notice any difference > with these lines commented out, running with Python 2.7.5. YMMV > > There's a design flaw here since sys.stdin.encoding is used by the > parser in single-input mode. With it set to None, Unicode literals > entered in the REPL will be incorrectly parsed if they use non-ASCII > byte values. For example, given the input is Windows 1252, then u'?' > will be parsed as u'\x80' (i.e. PAD, a C1 Control code). > > Here's an alternative to messing with the default encoding -- at least > for the new version of Spyder that doesn't have to support 2.5. Python > 2.6+ checks for the PYTHONIOENCODING environment variable. This > overrides the encoding/errors values in Py_InitializeEx(): > > http://hg.python.org/cpython/file/70274d53c1dd/Python/pythonrun.c#l265 > > You can test setting PYTHONIOENCODING without restarting Spyder. Just > bring up Spyder's "Internal Console" and set > os.environ['PYTHONIOENCODING']. The change applies to new interpreters > started from the "Interpreters" menu. Spyder could set this itself in > the environment that gets passed to the QProcess object. > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 115, Issue 2 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Sep 2 01:19:37 2013 From: davea at davea.name (Dave Angel) Date: Sun, 1 Sep 2013 23:19:37 +0000 (UTC) Subject: [Tutor] input loop References: Message-ID: On 1/9/2013 17:53, Nick Wilson wrote: > Hi, Welcome. Please start over with a text message. Your html email is useless to me, and probably most people on this newsgroup.     5       10.00
----------------------------------
Total cost:                  10.00
==================================

**(This is all even when displayed in Wing101)

So thats all fine, but I'm wanting muiltiple more rows printed underneath with other shares and their prices etc. 
Getting stuck on that, I know i'll need a for loop to iterate over the input but still wanting to get some help.

here's the rest of the code so far.





PROMPT_FOR_COMMAND = 'Enter command: '
PROMPT_FOR_CODE = 'Enter share code to add: '
PROMPT_FOR_PRICE = 'Enter share price: -- DaveA From joel.goldstick at gmail.com Mon Sep 2 01:25:38 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 1 Sep 2013 19:25:38 -0400 Subject: [Tutor] Please help replace Long place-names with short place-names in many files with Python In-Reply-To: References: Message-ID: On Sun, Sep 1, 2013 at 4:19 PM, mc UJI wrote: > Dear Pythonistas, > > I am totally new to Python. This means a know the basics. And by basics I > mean the very, very basics. > > I have a problem with which I need help. > > in short, I need to: > > a) Open many files (in a dir) with an .html extension Do you know how to do this? Its not hard. Google 'python reading all files in a directory' to get started > b) Find Long name-places (Austria) > c) Replace them by short name.places (AT) In python strings are objects and they have the replace method (look here: http://docs.python.org/2/library/string.html#string.replace) If you figure out how to read each file into a string (see above), you just run the string.replace method on it for each long-short country pair. Then write the file. Try first to write this code. If you apply yourself, it will take you maybe an hour to get something working. Then come back with your code and tell us what went wrong. > d) In the context of the xml tags ( and > ) > > At length: > > I have many xml files containing a day of speeches at the European > Parliament each file. Each file has some xml-label for the session metadata > and then the speakers (MPs) interventions. These interventions consist of my > metadata and text. I include here a sample of two speeches (Please pay > attention to xml labels and country=".*?"/> ): > > **************************************************************************************** > SAMPLE OF INTERVENTIONS > > > Knapman, Roger > 19440220 > Crediton > NA > male > > > > > > > > UK Independence Party > > > on behalf of the group > > >

Mr President, Mr Juncker's speech was made with > all the passion that a civil servant is likely to raise.

>

Mr Juncker, you say that the Stability and > Growth Pact will be your top priority, but your past statements serve to > illustrate only the inconsistencies. Whilst I acknowledge > that you played a key role in negotiating the pact's original rules, you > recently said that the credibility of the pact had been buried and that the > pact was dead. Is that still your opinion?

>

You also said that you have a window of > opportunity to cut a quick deal on the EU budget, including the British > rebate of some EUR 4 billion a year. Is that so, Mr > Juncker? The rebate took five years to > negotiate. If your comments are true and you can cut a > deal by June, then Mr Blair must have agreed in principle to surrender the > rebate. Is that the case? With whom in > the British Government precisely are you negotiating? Will > the British electorate know about this at the time of the British general > election, probably in May?

>

Finally, the UK Independence Party, and in > particular my colleague Mr Farage, has drawn attention to the criminal > activities of more than one Commissioner. More details > will follow shortly and regularly. Are you to be tainted > by association with them, or will you be expressing your concerns and the > pressing need for change?

>
>
> > > > Angelilli, Roberta > 19650201 > Roma > NA > female > > > > > > > > Alleanza nazionale > > > on behalf of the group > > >

Mr President, the Luxembourg Presidency?s > programme is packed with crucial issues for the future of Europe, including > the priorities on the economic front: the Lisbon strategy, reform of the > Stability Pact and approval of the financial perspective up to 2013.

>

My first point is that it will soon be time for > the mid-term review of the level of implementation of the Lisbon > strategy. To give it a greater chance of success, the > programme needs to make the individual Member States responsible for > achieving the targets that were set. To that end, I > consider the proposal to specify an individual at national level to be > responsible for putting the strategy into practice to be a very useful > idea.

>

Secondly, with regard to the review of the > Stability Pact, it has also been emphasised this morning that a reform is > needed which can propose a more flexible interpretation of the Pact during > times of recession, without bypassing the Maastricht criteria and without > giving up the commitment to reduce the debt. I am also > convinced that steps could be taken to exclude certain specific types of > investment from the calculation of the deficit in order to give a new boost > to Europe?s growth and competitiveness.

>

Thirdly, I hope that we can really succeed in > approving the financial perspective up to 2013 by June, so that the > resources can be used to the full from the very beginning of the period in > question. I especially hope that the proposals ? the > Council?s and the Commission?s proposals on those important topics ? are > adequately discussed in advance by Parliament which, let us recall, is the > only European institution that directly represents the sovereignty of the > people.

>

Lastly, I hope that a European civil protection > agency will at last be set up during the Luxembourg Presidency so that > natural disasters can be dealt with in an appropriate manner, with > particular emphasis on prevention.

>
>
> > END OF SAMPLE OF INTERVENTIONS > ************************************************************************************* > > Now, as you see, label: > > and > > Have long place-names. For instance > > and > > But I would like short place-names (UK instead of United Kingdom, for > instance) > > The long-names I have are all the members of the European Union. > > ************************************************************************************ > LIST OF LONG PLACE-NAMES AND EQUIVALENT SHORT PLACE-NAMES > > Austria = AT > Belgium = BE > Bulgaria = BG > Croatia = HR > Cyprus = CY > Czech Republic = CS > Denmark = DK > Estonia = EE > Finland = FI > France = FR > Germany = DE > Greece = GR > Hungary = HU > Ireland = IE > Italy = IT > Latvia = LV > Lithuania = LT > Luxembourg = LU > Malta = MT > Netherlands = NL > Poland = PL > Portugal = PT > Romania = RO > Slovakia = SK > Slovenia = SI > Spain = ES > Sweden = SE > United Kingdom = GB > > ************************************************************************************* > > TO SUM UP > > I am in despair at this point. Is there a way to use Python (dictionaries > and regular expressions or whatever is suitable to: > > a) Open many files with an .html extension > b) Find Long name-places (Austria) > c) Replace them by short name.places (AT) > d) In the context of the xml tags mentioned above. > > Please i NEED YOUR HELP > > Many thanks for your patience. > > Mar?a > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Mon Sep 2 01:41:50 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 02 Sep 2013 00:41:50 +0100 Subject: [Tutor] input loop In-Reply-To: References: Message-ID: On 01/09/13 22:53, Nick Wilson wrote: > Enter command: print > ---------------------------------- > Code Price Quant Value > ---------------------------------- The bit above needs to be printed once, at the start > TPW 2.00 5 10.00 This bit needs to be repeated for each share type > ---------------------------------- > Total cost: 10.00 > ================================== And this bit needs to be printed once at the end after doing the calculations. > **(This is all even when displayed in Wing101) That will depend on fonts used etc. If you really need it aligned neatly I recommend using html and displaying it in a browser, but its a lot more work that way! > PROMPT_FOR_COMMAND = 'Enter command: ' > PROMPT_FOR_CODE = 'Enter share code to add: ' > PROMPT_FOR_PRICE = 'Enter share price: ' > PROMPT_FOR_QUANTITY = 'Enter share quantity: ' Were you ever a COBOL programmer by any chance? > def main(): > """This is the main function for the program, ie, this function is > called > first when the program is run""" There is nothing in Python that will run this first. You need to call it explicitly. This is often done inside a name test clause: if __name__ == "__main__": main() > command = input(PROMPT_FOR_COMMAND).lower() > if command == 'add': > return portfolio.append(process_add_code(portfolio)) Are you sure you want to return here? That will terminate the main function without saving portfolio. You may want to create a menu system where you repeatedly ask for input until quit is selected. > if command == "print" and len(portfolio) <= 1: > print_portfolio_table(portfolio) > return main() > if command == "quit": > print(MESSAGE_GOODBYE) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From learner404 at gmail.com Mon Sep 2 16:19:17 2013 From: learner404 at gmail.com (learner404) Date: Mon, 2 Sep 2013 16:19:17 +0200 Subject: [Tutor] os.system vs subprocess.Popen args problems Message-ID: Hello, I can't understand why the command below works with os.system but not with subprocess.Popen (on windows, recording video with FFMPEG.exe) cmd=('ffmpeg -f dshow -i video="%s" -f dshow -i audio="%s" -q 5 "%s"')%(videoinputName, audioinputName, videoFileOutput) os.system(cmd) *works* subprocess.Popen(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName,"-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5","%s"%videoFileOutput]) *don't work* >> [dshow @ 025984a0] Could not find video device. >> video="QuickCam Orbit/Sphere AF": Input/output error The reason I'm going with subprocess is to avoid to have the DOS window coming in the forefront. Any idea of what I'm doing wrong? Or any other way to hide or minimize the DOS window? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Sep 2 16:44:25 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 2 Sep 2013 15:44:25 +0100 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On 2 September 2013 15:19, learner404 wrote: > Hello, > > I can't understand why the command below works with os.system but not with > subprocess.Popen (on windows, recording video with FFMPEG.exe) > > cmd=('ffmpeg -f dshow -i video="%s" -f dshow -i audio="%s" -q 5 > "%s"')%(videoinputName, audioinputName, videoFileOutput) > os.system(cmd) > *works* > > subprocess.Popen(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName,"-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5","%s"%videoFileOutput]) I think you need additional quotes for the videoFileOutput part e.g. '"%s"' % videoFileOutput > *don't work* >>> [dshow @ 025984a0] Could not find video device. >>> video="QuickCam Orbit/Sphere AF": Input/output error I see that video has spaces in it. You'd think it was unnecessary to have those quotes since you've already split the command string into a list of strings. Unfortunately Windows has a fairly arcane way of handling arguments to subprocesses and Python tries to emulate that: http://docs.python.org/2/library/subprocess.html#converting-an-argument-sequence-to-a-string-on-windows > The reason I'm going with subprocess is to avoid to have the DOS window > coming in the forefront. > Any idea of what I'm doing wrong? Or any other way to hide or minimize the > DOS window? Another thing is that you shouldn't use Popen directly unless you're doing something fancy (which you're not if os.system does what you want). Use subprocess.check_call instead: subprocess.check_call(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName,"-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5",'"%s"'%videoFileOutput]) Oscar From i.sheeha at gmail.com Mon Sep 2 23:22:00 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Mon, 2 Sep 2013 23:22:00 +0200 Subject: [Tutor] help with postgreSQL and .csv Message-ID: hello. i wrote the following code, to insert some values from a csv file to my postgres table : * ****** *import psycopg2* *conn = psycopg2.connect("host = ***.***.***.*** user=******* dbname = ****** ")* *cur = conn.cursor()* *import csv* *with open('HotelImages.csv', 'rb') as f: * * mycsv = csv.reader(f, delimiter = '|')* * for row in mycsv:* * hotel_code = row[0]* * hotel_url = row[-1]* * sql = " UPDATE hotel SET path_picture = "+"';"+hotel_url+"' WHERE code LIKE '"+"%"+hotel_code+"'"* * print '--->'+sql* * cur.execute(sql)* * conn.commit()* *c.close()* *print '----->Complete'* * ******* the for loop iterates through the table, comparing the values from the csv line by line with the table column 'code'. example of csv lines: * ****** *94176|HAB|7|2|09/094176/094176a_hb_w_007.jpg* *94176|HAB|8|3|09/094176/094176a_hb_w_008.jpg* *94176|BAR|6|7|09/094176/094176a_hb_ba_006.jpg* *94176|RES|5|6|09/094176/094176a_hb_r_005.jpg* *94176|HAB|1|1|09/094176/094176a_hb_w_001.jpg* *94176|CON|4|8|09/094176/094176a_hb_k_004.jpg* *94176|COM|2|4|09/094176/094176a_hb_l_002.jpg* *94176|RES|3|5|09/094176/094176a_hb_r_003.jpg* * ****** example of the code column value : *GEN94176, XLK94176,KJK94176*.... the number before the first ' | ' gets just one hit in the database table column, inserts some random picture once.also, if the same numbers in some other 'code' column row are appearing, but in different order, it inserts the same picture. my goal is to make it write all the picture url values separated by a ';' in just one field and to input the data correctly. i'm new to python, as a matter of fact, just started to learn programming. i would really like to know where is my mistake.advice and help appreciated! Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bedachtm at gmail.com Tue Sep 3 03:32:33 2013 From: bedachtm at gmail.com (Max Bedacht) Date: Mon, 2 Sep 2013 22:32:33 -0300 Subject: [Tutor] Using tkinter for cross platform application Message-ID: Hello; I'm looking for a quick, if possible, solution to a problem I'm having. I have developed an application which I'm packaging to run on Windows, Linux and eventually OS-X. I have gone through myriad iterations, bouncing between Python 2.7 and 3.3 and between 32 and 64 bit Linux, Windows XP and Windows 8. At this point I can happily say that everything is working on all platforms except Apple, which I can not test at this time. The problem that I am now trying to resolve, which I hope is the last one, is the following: When running a packaged 'compiled' version on all windows platforms the screen, while complete, is reduced by about 20% from the Linux version, where the development was mostly done. Images seem all to be the same size, as is the main window, but all of the text, labels and buttons are reduced in size, not by much, but enough to be annoying. (Curiously, this size difference does not happen in my development environment (Eclipse/PyDev). There, if anything, the text in windows seems to be a bit larger than that in Linux). I seem to have 3 options at this point: 1. live with it; 2. adjust the image portion, which seems fixed in size, to be x% smaller in the Windows environment, making the overall window smaller but maintaining proportionality; 3. see if there is a magic bullet to resolve this issue. Any thoughts would be greatly appreciated. (Ubuntu 13.04 (64bit), Lubuntu 13.04(32Bit), Windows 8(64Bit), Windows 7(64Bit), Windows XP Python 2.7 and 3.3 64Bit on the Ubuntu box. Python 2.7 and 3.3 32Bit on the Windows boxes Thanks; Max Bedacht -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Tue Sep 3 04:35:46 2013 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 2 Sep 2013 22:35:46 -0400 Subject: [Tutor] help with postgreSQL and .csv In-Reply-To: References: Message-ID: <16110070470.20130902223546@columbus.rr.com> > my goal is to make it write all the picture url values separated by > a ';' in just one field and to input the data correctly. ? I haven't used postgresql much. Could it be you're just missing path_picture as part of your data value? i.e. UPDATE hotel SET path_picture = + hotel_url UPDATE hotel SET path_picture = path_picture + hotel_url Alternatively, you could read the entire csv file and generate the semicolon-separated strings as dictionary entries, then as a second step, insert all those dictionary entries into the database. Alan From eryksun at gmail.com Tue Sep 3 06:49:09 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 3 Sep 2013 00:49:09 -0400 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On Mon, Sep 2, 2013 at 10:19 AM, learner404 wrote: > > I can't understand why the command below works with os.system but not with > subprocess.Popen (on windows, recording video with FFMPEG.exe) > > cmd=('ffmpeg -f dshow -i video="%s" -f dshow -i audio="%s" -q 5 "%s"')% > (videoinputName, audioinputName, videoFileOutput) > os.system(cmd) > *works* > > subprocess.Popen(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName, > "-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5", > "%s"%videoFileOutput]) > *don't work* >>> [dshow @ 025984a0] Could not find video device. >>> video="QuickCam Orbit/Sphere AF": Input/output error Popen joins the list into a string, as required by Windows CreateProcess(). It assumes the tokenizing rules used by Microsoft's C runtime. If that assumption is wrong, just switch to using a string instead of a list, with whatever custom quoting is required. I'd first try it like this: args = ['ffmpeg', '-f', 'dshow', '-i', 'video=%s' % videoinputName, '-f', 'dshow', '-i', 'audio=%s' % audioinputName, '-q', '5', videoFileOutput] Here's a simple script to print the raw command line, and also sys.argv. test.py import sys from ctypes import * windll.kernel32.GetCommandLineW.restype = c_wchar_p print(windll.kernel32.GetCommandLineW()) print(' '.join(sys.argv)) system() vs Popen(): >>> exe = sys.executable >>> cmdstr = '%s test.py video="QuickCam Orbit"' % exe >>> os.system(cmdstr) C:\Python27\python.exe test.py video="QuickCam Orbit" test.py video=QuickCam Orbit 0 >>> cmdlst = [exe, 'test.py', 'video="QuickCam Orbit"'] >>> subprocess.call(cmdlst) C:\Python27\python.exe test.py "video=\"QuickCam Orbit\"" test.py video="QuickCam Orbit" 0 Automatic vs manual quoting: >>> cmdlst2 = [exe, 'test.py', 'video=QuickCam Orbit'] >>> subprocess.call(cmdlst2) C:\Python27\python.exe test.py "video=QuickCam Orbit" test.py video=QuickCam Orbit 0 >>> subprocess.call(cmdstr) C:\Python27\python.exe test.py video="QuickCam Orbit" test.py video=QuickCam Orbit 0 > The reason I'm going with subprocess is to avoid to have the DOS window > coming in the forefront. > Any idea of what I'm doing wrong? Or any other way to hide or minimize the > DOS window? The startupinfo option can hide the window, including a console window: http://docs.python.org/2/library/subprocess.html#subprocess.STARTUPINFO By the way, unless you're running Windows 9x, a console window isn't "DOS". A console is hosted in a separate process (csrss.exe or conhost.exe). Multiple processes can attach to a single console. If a process doesn't create or inherit a console automatically, it can attach to an existing one (kernel32.AttachConsole) or allocate one manually (kernel32.AllocConsole). From __peter__ at web.de Tue Sep 3 09:33:16 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Sep 2013 09:33:16 +0200 Subject: [Tutor] help with postgreSQL and .csv References: Message-ID: Ismar Sehic wrote: > hello. Ismar, please post in plain text. The markup appears as funny stars over here. > i wrote the following code, to insert some values from a csv file to my > postgres table : > > * ****** > *import psycopg2* > *conn = psycopg2.connect("host = ***.***.***.*** user=******* dbname = > ****** ")* > *cur = conn.cursor()* > *import csv* > *with open('HotelImages.csv', 'rb') as f: * > * mycsv = csv.reader(f, delimiter = '|')* > * for row in mycsv:* > * hotel_code = row[0]* > * hotel_url = row[-1]* > * sql = " UPDATE hotel SET path_picture = "+"';"+hotel_url+"' > WHERE code LIKE '"+"%"+hotel_code+"'"* > * print '--->'+sql* > * cur.execute(sql)* > * conn.commit()* > *c.close()* > *print '----->Complete'* > * ******* > > > the for loop iterates through the table, comparing the values from the csv > line by line with the table column 'code'. > example of csv lines: > * ****** > *94176|HAB|7|2|09/094176/094176a_hb_w_007.jpg* > *94176|HAB|8|3|09/094176/094176a_hb_w_008.jpg* > *94176|BAR|6|7|09/094176/094176a_hb_ba_006.jpg* > *94176|RES|5|6|09/094176/094176a_hb_r_005.jpg* > *94176|HAB|1|1|09/094176/094176a_hb_w_001.jpg* > *94176|CON|4|8|09/094176/094176a_hb_k_004.jpg* > *94176|COM|2|4|09/094176/094176a_hb_l_002.jpg* > *94176|RES|3|5|09/094176/094176a_hb_r_003.jpg* > * ****** > example of the code column value : *GEN94176, XLK94176,KJK94176*.... > the number before the first ' | ' gets just one hit in the database table > column, inserts some random picture once.also, if the same numbers in some > other 'code' column row are appearing, but in different order, it inserts > the same picture. > my goal is to make it write all the picture url values separated by a ';' > in just one field and to input the data correctly. > i'm new to python, as a matter of fact, just started to learn programming. > i would really like to know where is my mistake.advice and help > appreciated! In sqlite3 cur.execute("update hotel " "set path_picture = coalesce(path_picture || ';' || ?, ?) " "where code like ?;", (path_picture, path_picture, "%" + code)) would work. Alternatively you could collect pictures with the same code in Python: from collections import defaultdict code_to_pic = defaultdict(list) for row in mycsv: code_to_pic[row[0]].append(row[-1]) cur.executemany("update hotel set path_picture = ? where code like ?", [(";".join(urls), "%" + code) for code, urls in code_to_pic.items()]) Warning: This would overwrite any urls already in the database. It also assumes that you have only one match per row of the where-expression. So don't do it that way unless you are absolutely sure you understand these limitations. By the way, the right way to do this is to add another table to the db. That table should have code and url columns and one row per url/code pair. From alan.gauld at btinternet.com Tue Sep 3 11:30:25 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 03 Sep 2013 10:30:25 +0100 Subject: [Tutor] Using tkinter for cross platform application In-Reply-To: References: Message-ID: On 03/09/13 02:32, Max Bedacht wrote: > Hello; > I'm looking for a quick, if possible, solution to a problem I'm having. :-) Does anyone ever look for a slow solution?... > The problem that I am now trying to resolve, which I hope is the last > one, is the following: > > When running a packaged 'compiled' version on all windows platforms the > screen, while complete, is reduced by about 20% from the Linux version, You don't give us much detail here. What is the "screen"? How is it compiled? Does a non compiled version work OK? > where the development was mostly done. Images seem all to be the same > size, as is the main window, but all of the text, labels and buttons are > reduced in size, not by much, but enough to be annoying. You tell us it is Tkinter based but don't describe what the GUI looks like so we have no idea what bits of Tkinter you are using. Some Tkinter widgets are designed to adopt the host GUI look n' feel for example so we'd expect them to look different on each platform. > this size difference does not happen in my development environment > (Eclipse/PyDev). There, if anything, the text in windows seems to be a > bit larger than that in Linux). This confuses me because Eclipse doesn't display the GUI so what text is it that is bigger in Eclipse? Are you talking about Eclipse itself? > I seem to have 3 options at this point: > > 1. live with it; > 2. adjust the image portion, which seems fixed in size, to be x% > smaller in the Windows environment, making the overall window > smaller but maintaining proportionality; How are you displaying the image? Is it in a Canvas? Text widget, or part of a label? Images are often specified with explicit sizes so I'd expect the image to be more likely to stay constant but text is often dependent on system settings. > 3. see if there is a magic bullet to resolve this issue. > (Ubuntu 13.04 (64bit), Lubuntu 13.04(32Bit), Windows 8(64Bit), Windows > 7(64Bit), Windows XP > Python 2.7 and 3.3 64Bit on the Ubuntu box. > Python 2.7 and 3.3 32Bit on the Windows boxes You might get a better response posting on the Tkinter mailing list, there are a lot of folks there using different OS versions etc. It may be a well known problem there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Tue Sep 3 11:54:21 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 3 Sep 2013 10:54:21 +0100 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On 3 September 2013 05:49, eryksun wrote: > On Mon, Sep 2, 2013 at 10:19 AM, learner404 wrote: >> >> I can't understand why the command below works with os.system but not with >> subprocess.Popen (on windows, recording video with FFMPEG.exe) >> >> cmd=('ffmpeg -f dshow -i video="%s" -f dshow -i audio="%s" -q 5 "%s"')% >> (videoinputName, audioinputName, videoFileOutput) >> os.system(cmd) >> *works* >> >> subprocess.Popen(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName, >> "-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5", >> "%s"%videoFileOutput]) >> *don't work* >>>> [dshow @ 025984a0] Could not find video device. >>>> video="QuickCam Orbit/Sphere AF": Input/output error > > Popen joins the list into a string, as required by Windows > CreateProcess(). It assumes the tokenizing rules used by Microsoft's C > runtime. If that assumption is wrong, just switch to using a string > instead of a list, with whatever custom quoting is required. I've previously tried to find documentation that explains how MSVCRT handles this. I didn't find anything as explicit as the explanation in the subprocess docs. For example: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx > I'd first > try it like this: > > args = ['ffmpeg', > '-f', 'dshow', '-i', 'video=%s' % videoinputName, > '-f', 'dshow', '-i', 'audio=%s' % audioinputName, > '-q', '5', videoFileOutput] By the way if you find this kind of thing a little less elegant than the command line string for os.system you can always make a helper function e.g.: >>> import shlex >>> def cmdsplit(cmdline, **kwargs): ... return [a % kwargs for a in shlex.split(cmdline)] ... >>> cmdline = 'ffmpeg -f dshow -i video=%(video)s -f dshow -i audio=%(audio)s -q 5 %(device)s' >>> cmdsplit(cmdline, video="my video.mpg", audio="my audio.wav", device="my cam") ['ffmpeg', '-f', 'dshow', '-i', 'video=my video.mpg', '-f', 'dshow', '-i', 'audio=my audio.wav', '-q', '5', 'my cam'] > > Here's a simple script to print the raw command line, and also sys.argv. > > test.py > > import sys > from ctypes import * > > windll.kernel32.GetCommandLineW.restype = c_wchar_p > > print(windll.kernel32.GetCommandLineW()) I'm pretty sure Python 2.x uses CreateProcessA and GetCommandLineA. No idea about ffmpeg though (and probably makes no difference here)... > print(' '.join(sys.argv)) I'd expect 'print(sys.argv)' to be more informative here. > system() vs Popen(): > > >>> exe = sys.executable > > >>> cmdstr = '%s test.py video="QuickCam Orbit"' % exe > >>> os.system(cmdstr) > C:\Python27\python.exe test.py video="QuickCam Orbit" > test.py video=QuickCam Orbit > 0 > > >>> cmdlst = [exe, 'test.py', 'video="QuickCam Orbit"'] > >>> subprocess.call(cmdlst) > C:\Python27\python.exe test.py "video=\"QuickCam Orbit\"" > test.py video="QuickCam Orbit" > 0 Ah, so subprocess does actually pass the quotes through. Okay that's probably not what's wanted then. It occurs to me that another possibility is if ffmpeg isn't really an .exe on PATH but rather a .bat file or something. In that case os.system or subprocess shell=True would pick it up but subprocess shell=False might not. I say "might" because at least on some version of Windows CreateProcess can run .bat files directly but I've never seen this documented anywhere. Apparently some newer versions of Windows have a "where" command that could find ffmpeg for you. I don't have it on XP though... Oscar From eryksun at gmail.com Tue Sep 3 15:48:08 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 3 Sep 2013 09:48:08 -0400 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On Tue, Sep 3, 2013 at 5:54 AM, Oscar Benjamin wrote: > On 3 September 2013 05:49, eryksun wrote: > > I've previously tried to find documentation that explains how MSVCRT > handles this. I didn't find anything as explicit as the explanation in > the subprocess docs. For example: > http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx It's in the CRT startup code: http://msdn.microsoft.com/en-us/library/a1y7w461(v=vs.90) Visual Studio includes the CRT source in the subdirectory VC\crt\src. The startup code calls parse_cmdline() in stdargv.c. For the Windows API, shell32 has CommandLineToArgvW: http://msdn.microsoft.com/en-us/library/bb776391 >> import sys >> from ctypes import * >> >> windll.kernel32.GetCommandLineW.restype = c_wchar_p >> >> print(windll.kernel32.GetCommandLineW()) > > I'm pretty sure Python 2.x uses CreateProcessA and GetCommandLineA. No > idea about ffmpeg though (and probably makes no difference here)... 2.x _subprocess calls CreateProcessA, but internally Windows routes the call to CreateProcessW, after first decoding the A(NSI) strings. The process itself stores the command line as a UNICODE_STRING: PEB: http://msdn.microsoft.com/en-us/library/aa813706 RTL_USER_PROCESS_PARAMETERS http://msdn.microsoft.com/en-us/library/aa813741 > It occurs to me that another possibility is if ffmpeg isn't really an > .exe on PATH but rather a .bat file or something. In that case > os.system or subprocess shell=True would pick it up but subprocess > shell=False might not. I say "might" because at least on some version > of Windows CreateProcess can run .bat files directly but I've never > seen this documented anywhere. cmd tries each PATHEXT extension, but CreateProcess only tries .exe, and finds ffmpeg.exe. As to batch files, "Windows Internals" (Microsoft Press) documents that CreateProcess starts cmd.exe to run .bat and .cmd files. From oscar.j.benjamin at gmail.com Tue Sep 3 17:42:34 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 3 Sep 2013 16:42:34 +0100 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On 3 September 2013 14:48, eryksun wrote: >> It occurs to me that another possibility is if ffmpeg isn't really an >> .exe on PATH but rather a .bat file or something. In that case >> os.system or subprocess shell=True would pick it up but subprocess >> shell=False might not. I say "might" because at least on some version >> of Windows CreateProcess can run .bat files directly but I've never >> seen this documented anywhere. > > cmd tries each PATHEXT extension, but CreateProcess only tries .exe, > and finds ffmpeg.exe. > > As to batch files, "Windows Internals" (Microsoft Press) documents > that CreateProcess starts cmd.exe to run .bat and .cmd files. Okay, I see. So it can run a .bat if you give the extension but not implicitly via PATHEXT. In which case anything without an extension would have to be an .exe file. And of course this wouldn't explain the OP's problem anyway since they're getting output from ffmpeg. Testing the OP's actual commands out with ffmpeg I see that the problem is with the quotes. But, as you pointed out in your first post, it is the unnecessary additional quotes that are the problem rather than any missing ones. i.e. when I test it I get: # os.system output [dshow @ 02548460] Could not enumerate video devices. video=video: Input/output error # subprocess.Popen output [dshow @ 02548460] Could not enumerate video devices. video="video": Input/output error So the extra quotes used for the video and audio arguments do actually get passed through to ffmpeg causing confusion. (I don't have any video devices here so it's an error either way on this machine). Oscar From ramit.prasad at jpmorgan.com.dmarc.invalid Tue Sep 3 17:56:28 2013 From: ramit.prasad at jpmorgan.com.dmarc.invalid (Prasad, Ramit) Date: Tue, 3 Sep 2013 15:56:28 +0000 Subject: [Tutor] A mergesort In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474186AE61A@SCACMX008.exchad.jpmchase.net> D.V.N.Sarma wrote: [snip recursive merge sort algorithm] > Especially the statement > > v = (a[0] < b[0] and a or b).pop(0) > > gives a.pop(0), if a[0] < b[0] otherwise b.pop(0). I believe this idiom was used before the ternary if statements were introduced (in 2.5 I believe). In modern Python you could do an ternary if which is more explicit and clearer in my mind. v = a.pop(0) if a[0] > We have to look at the statement as > > v = ((a[0] < b[0] and a) or b).pop(0) v = (a if a[0]< b[0] else b).pop(0) > > > regards, > Sarma. ~Ramit 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. From learner404 at gmail.com Wed Sep 4 11:14:08 2013 From: learner404 at gmail.com (learner404) Date: Wed, 4 Sep 2013 11:14:08 +0200 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: Thanks a lot Oscar and Eryksun for all the explanations and answers, I really appreciate. "So the extra quotes used for the video and audio arguments do actually get passed through to ffmpeg causing confusion." Yes, this worked :) subprocess.Popen(["ffmpeg","-f","dshow","-i","video="+videoinputName,"-f","dshow","-i","audio="+audioinputName,"-q","5","%s"%videoFileOutput],shell=True) On Tue, Sep 3, 2013 at 5:42 PM, Oscar Benjamin wrote: > On 3 September 2013 14:48, eryksun wrote: > >> It occurs to me that another possibility is if ffmpeg isn't really an > >> .exe on PATH but rather a .bat file or something. In that case > >> os.system or subprocess shell=True would pick it up but subprocess > >> shell=False might not. I say "might" because at least on some version > >> of Windows CreateProcess can run .bat files directly but I've never > >> seen this documented anywhere. > > > > cmd tries each PATHEXT extension, but CreateProcess only tries .exe, > > and finds ffmpeg.exe. > > > > As to batch files, "Windows Internals" (Microsoft Press) documents > > that CreateProcess starts cmd.exe to run .bat and .cmd files. > > Okay, I see. So it can run a .bat if you give the extension but not > implicitly via PATHEXT. In which case anything without an extension > would have to be an .exe file. And of course this wouldn't explain the > OP's problem anyway since they're getting output from ffmpeg. > > Testing the OP's actual commands out with ffmpeg I see that the > problem is with the quotes. But, as you pointed out in your first > post, it is the unnecessary additional quotes that are the problem > rather than any missing ones. i.e. when I test it I get: > > # os.system output > [dshow @ 02548460] Could not enumerate video devices. > video=video: Input/output error > > # subprocess.Popen output > [dshow @ 02548460] Could not enumerate video devices. > video="video": Input/output error > > So the extra quotes used for the video and audio arguments do actually > get passed through to ffmpeg causing confusion. (I don't have any > video devices here so it's an error either way on this machine). > > > Oscar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Sep 4 12:11:30 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 4 Sep 2013 06:11:30 -0400 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On Wed, Sep 4, 2013 at 5:14 AM, learner404 wrote: > > Yes, this worked :) > > subprocess.Popen(["ffmpeg","-f","dshow","-i","video="+videoinputName,"-f", > "dshow","-i","audio="+audioinputName,"-q","5","%s"%videoFileOutput], > shell=True) Using shell=True also sets startupinfo to hide the window. If that's the only reason you're using the shell, you may as well cut out the middleman (and potential security hole). Set startupinfo=si, where si is defined like this: si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE From oscar.j.benjamin at gmail.com Wed Sep 4 12:22:22 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 4 Sep 2013 11:22:22 +0100 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On 4 September 2013 11:11, eryksun wrote: > On Wed, Sep 4, 2013 at 5:14 AM, learner404 wrote: >> >> Yes, this worked :) >> >> subprocess.Popen(["ffmpeg","-f","dshow","-i","video="+videoinputName,"-f", >> "dshow","-i","audio="+audioinputName,"-q","5","%s"%videoFileOutput], >> shell=True) You should use subprocess.check_call() rather than subprocess.Popen. subprocess.check_call() waits for the command to complete and detects when an error has occurred in the child process and turns it into a Python error which is normally what you want to happen before any subsequent code runs. >From the subprocess docs: "The recommended approach to invoking subprocesses is to use the following convenience functions for all use cases they can handle. For more advanced use cases, the underlying Popen interface can be used directly." http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module I'm pretty sure that your problem does not come under the "more advanced" use cases of subprocess. > Using shell=True also sets startupinfo to hide the window. If that's > the only reason you're using the shell, you may as well cut out the > middleman (and potential security hole). Set startupinfo=si, where si > is defined like this: I think it should just be possible to use shell=False here. > si = subprocess.STARTUPINFO() > si.dwFlags |= subprocess.STARTF_USESHOWWINDOW > si.wShowWindow = subprocess.SW_HIDE Do these statements modify module-level state? Or do you need to pass startupinfo=si when calling Popen? Oscar From eryksun at gmail.com Wed Sep 4 12:42:05 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 4 Sep 2013 06:42:05 -0400 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On Wed, Sep 4, 2013 at 6:22 AM, Oscar Benjamin wrote: > On 4 September 2013 11:11, eryksun wrote: > >> Using shell=True also sets startupinfo to hide the window. If that's >> the only reason you're using the shell, you may as well cut out the >> middleman (and potential security hole). Set startupinfo=si, where si >> is defined like this: > > I think it should just be possible to use shell=False here. > >> si = subprocess.STARTUPINFO() >> si.dwFlags |= subprocess.STARTF_USESHOWWINDOW >> si.wShowWindow = subprocess.SW_HIDE > > Do these statements modify module-level state? Or do you need to pass > startupinfo=si when calling Popen? It's a documented option for instances of Popen, to configure a few fields in the STARTUPINFO struct that gets passed to CreateProcess. http://docs.python.org/2/library/subprocess#subprocess.STARTUPINFO STARTUPINFO struct: http://msdn.microsoft.com/en-us/library/ms686331 PC/_subprocess.c: /* note: we only support a small subset of all SI attributes */ si.dwFlags = getint(startup_info, "dwFlags"); si.wShowWindow = getint(startup_info, "wShowWindow"); si.hStdInput = gethandle(startup_info, "hStdInput"); si.hStdOutput = gethandle(startup_info, "hStdOutput"); si.hStdError = gethandle(startup_info, "hStdError"); http://hg.python.org/cpython/file/ab05e7dd2788/PC/_subprocess.c#l444 From oscar.j.benjamin at gmail.com Wed Sep 4 13:11:25 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 4 Sep 2013 12:11:25 +0100 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On 4 September 2013 11:42, eryksun wrote: >>> si = subprocess.STARTUPINFO() >>> si.dwFlags |= subprocess.STARTF_USESHOWWINDOW >>> si.wShowWindow = subprocess.SW_HIDE >> >> Do these statements modify module-level state? Or do you need to pass >> startupinfo=si when calling Popen? > > It's a documented option for instances of Popen, to configure a few > fields in the STARTUPINFO struct that gets passed to CreateProcess. It's not clear from the docs (or your explanation) whether the lines above modify a global STARTUPINFO struct that gives default behaviour to subprocesses or if it is just the way to initialise one that can be passed to Popen or the convenience APIs. I guess the latter in which case it's probably better to be explicit and say: si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE subprocess.check_call(cmdargs, startupinfo=si) Oscar From eryksun at gmail.com Wed Sep 4 14:07:22 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 4 Sep 2013 08:07:22 -0400 Subject: [Tutor] os.system vs subprocess.Popen args problems In-Reply-To: References: Message-ID: On Wed, Sep 4, 2013 at 7:11 AM, Oscar Benjamin wrote: > On 4 September 2013 11:42, eryksun wrote: >>>> si = subprocess.STARTUPINFO() >>>> si.dwFlags |= subprocess.STARTF_USESHOWWINDOW >>>> si.wShowWindow = subprocess.SW_HIDE >>> >>> Do these statements modify module-level state? Or do you need to pass >>> startupinfo=si when calling Popen? >> >> It's a documented option for instances of Popen, to configure a few >> fields in the STARTUPINFO struct that gets passed to CreateProcess. > > It's not clear from the docs (or your explanation) whether the lines > above modify a global STARTUPINFO struct that gives default behaviour > to subprocesses or if it is just the way to initialise one that can be > passed to Popen or the convenience APIs. I guess the latter in which > case it's probably better to be explicit and say: > > si = subprocess.STARTUPINFO() > si.dwFlags |= subprocess.STARTF_USESHOWWINDOW > si.wShowWindow = subprocess.SW_HIDE > subprocess.check_call(cmdargs, startupinfo=si) When I said, "[s]et startupinfo=si, where si is defined", I assumed familiarity with the Popen constructor: subprocess.Popen( args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0) ... If given, startupinfo will be a STARTUPINFO object, which is passed to the underlying CreateProcess function. creationflags, if given, can be CREATE_NEW_CONSOLE or CREATE_NEW_PROCESS_GROUP. http://docs.python.org/2/library/subprocess#popen-constructor From fomcl at yahoo.com Wed Sep 4 14:39:10 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 4 Sep 2013 05:39:10 -0700 (PDT) Subject: [Tutor] myown.getfilesystemencoding() In-Reply-To: References: <1377875054.96190.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <1378298350.39416.YahooMailNeo@web163804.mail.gq1.yahoo.com> ----- Original Message ----- > From: eryksun > To: Oscar Benjamin ; Albert-Jan Roskam > Cc: Python Mailing List > Sent: Sunday, September 1, 2013 7:30 AM > Subject: Re: [Tutor] myown.getfilesystemencoding() > > On Sat, Aug 31, 2013 at 9:16 AM, Oscar Benjamin > wrote: >>? Spyder has both an internal interpreter and an external interpreter. >>? One is the same interpreter process that runs the Spyder GUI. The >>? other is run in a subprocess which keeps the GUI safe but reduces your >>? ability to inspect the workspace data via the GUI. So presumable >>? Albert means the "external" interpreter here. > > I installed Spyder on Windows to look into this. It's using Qt > QProcess to run the external interpreter in a child process. > sys.stdin.isatty() confirms it's not a tty, and Process Explorer > confirms that all 3 standard I/O handles (from msvcrt.get_osfhandle()) > are pipes. > > The file encoding is None for piped standard I/O, so printing unicode > falls back to the default encoding. Normally this is ASCII in 2.x, but > Spyder uses sitecustomize to set the default encoding based on the > default locale. It also sets the hidden console's codepage: > > ? ? if os.name == 'nt': # Windows platforms > > ? ? ? ? # Setting console encoding (otherwise Python does not > ? ? ? ? # recognize encoding) > ? ? ? ? try: > ? ? ? ? ? ? import locale, ctypes > ? ? ? ? ? ? _t, _cp = locale.getdefaultlocale('LANG') > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? _cp = int(_cp[2:]) > ? ? ? ? ? ? ? ? ctypes.windll.kernel32.SetConsoleCP(_cp) > ? ? ? ? ? ? ? ? ctypes.windll.kernel32.SetConsoleOutputCP(_cp) > ? ? ? ? ? ? except (ValueError, TypeError): > ? ? ? ? ? ? ? ? # Code page number in locale is not valid > ? ? ? ? ? ? ? ? pass > ? ? ? ? except ImportError: > ? ? ? ? ? ? pass > > http://code.google.com/p/spyderlib/source/browse/spyderlib/ > widgets/externalshell/sitecustomize.py?name=v2.2.0#74 > > Probably this was added for a good reason, but I don't grok the point. > Python isn't interested in the hidden console window at this stage, > and the standard handles are all pipes. I didn't notice any difference > with these lines commented out, running with Python 2.7.5. YMMV > > There's a design flaw here since sys.stdin.encoding is used by the > parser in single-input mode. With it set to None, Unicode literals > entered in the REPL will be incorrectly parsed if they use non-ASCII > byte values. For example, given the input is Windows 1252, then u'?' > will be parsed as u'\x80' (i.e. PAD, a C1 Control code). > > Here's an alternative to messing with the default encoding -- at least > for the new version of Spyder that doesn't have to support 2.5. Python > 2.6+ checks for the PYTHONIOENCODING environment variable. This > overrides the encoding/errors values in Py_InitializeEx(): > > http://hg.python.org/cpython/file/70274d53c1dd/Python/pythonrun.c#l265 > > You can test setting PYTHONIOENCODING without restarting Spyder. Just > bring up Spyder's "Internal Console" and set > os.environ['PYTHONIOENCODING']. The change applies to new interpreters > started from the "Interpreters" menu. Spyder could set this itself in > the environment that gets passed to the QProcess object. Wow, thanks for looking all this up. Thanks also to other people who replied. It's not really desirable that a IDE adds confusion to an area that's already confusing to begin with. But given that chcp returns cp850 on my windows system (commandline), wouldn't it be more descriptive if sys.getfilesystemencoding() returned 'cp850'? In other words: In the code below, isn't line [1] an obfuscated version of line [2]? Both versions return only question marks on my system. # Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 import ctypes ords = [3629, 3633, 3585, 3625, 3619, 3652, 3607, 3618] u = "".join([unichr(i) for i in ords]) print u.encode("mbcs") # [1] #cp850 is what chcp returns on my Windows system print u.encode("cp850", "replace") # [2] thai_latin_cp = "cp874" cp_ = int(thai_latin_cp[2:]) ctypes.windll.kernel32.SetConsoleCP(cp_) ctypes.windll.kernel32.SetConsoleOutputCP(cp_) print u.encode("cp874", "replace") ctypes.windll.kernel32.SetConsoleCP() and SetConsoleOutputCP seem useful. Can these functions be used to correctly display the Thai characters on my western European Windows version? (last block of code is an attempt) Or is that not possible altogether? Best wishes, Albert-Jan From fomcl at yahoo.com Wed Sep 4 15:30:12 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 4 Sep 2013 06:30:12 -0700 (PDT) Subject: [Tutor] Python 2 & 3 and unittest Message-ID: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> Hi, I am trying to make my app work in Python 2.7 and Python 3.3 (one codebase) and I might later also try to make it work on Python 2.6 and Python 3.2 (if I am not too fed up with it ;-). I was very happy to notice that the 'b' prefix for bytes objects is also supported for byte strings in Python 2.7. Likewise, I just found out that the "u" has been re-introduced in Python 3.3 (I believe this is the first Python 3 version where this re-appears). I am now cursing myself for having used doctest for my tests. So I am planning to rewrite everything in unittest. Is the try-except block below the best way to make this test work in Python 2.6 through 3.3? import unitttest import blah? # my package class test_blah(unittest.TestCase): ??? def test_someTest(self): ??????? try: ? ? ? ?? ?? expected = [u"lalala", 1] # Python 2.6>= & Python 3.3>= ??????? except SyntaxError: ? ? ? ?? ?? expected = ["lalala", 1] # Python 3.0, 3.1, 3.2 ??????? got = blah.yadiyadiyadi() ??????? self.assertEqual(expected, got) if __name__ == "__main__": ??? unittest.main() ? Another, though related question. We have Python 2.7 in the office and eventually we will move to some Python3 version. The code does not generally need to remain Python2 compatible. What is the best strategy: [a] write forward compatible code when using Python 2.7. (using a 'b' prefix for byte strings, parentheses for the print *statement*, sys.exc_info()[1] for error messages, etc.). [b] totally rely on 2to3 script and don't make the Python2 code less reabable and less idiomatic before the upgrade. Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From dfjennings at gmail.com Wed Sep 4 16:15:37 2013 From: dfjennings at gmail.com (Don Jennings) Date: Wed, 4 Sep 2013 10:15:37 -0400 Subject: [Tutor] Python 2 & 3 and unittest In-Reply-To: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Sep 4, 2013, at 9:30 AM, Albert-Jan Roskam wrote: > Hi, > > I am trying to make my app work in Python 2.7 and Python 3.3 (one codebase) and I might later also try to make it work on Python 2.6 and Python 3.2 (if I am not too fed up with it ;-). You might like to read Armin Ronacher's (Flask, Jinja2) take on this topic [1]. Take care, Don [1] http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ From freshmusman at gmail.com Wed Sep 4 10:50:54 2013 From: freshmusman at gmail.com (musa ezeri) Date: Wed, 4 Sep 2013 10:50:54 +0200 Subject: [Tutor] resolution Message-ID: im building an image processing software, but the python image processing modules are in 32 bit and require 32bit python 2.7 where can i find a 32 bit python 2.7? -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.sheeha at gmail.com Tue Sep 3 09:25:29 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Tue, 3 Sep 2013 09:25:29 +0200 Subject: [Tutor] Tutor Digest, Vol 115, Issue 6 In-Reply-To: References: Message-ID: help with postgres and csv: i solved my problem by playing with the sql line a little. it looked like this : sql = " UPDATE hotel SET path_picture = "+"';"+hotel_url+"' WHERE code LIKE '"+"%"+hotel_code+"'" now it's like this : " UPDATE hotel SET path_picture = '" + hot_url + "' WHERE code LIKE '%" + hot_code + "';" i guess the problem was in building the sql string, but i don't yet quite understand what i did.can someone point me to some online resorces about postgres and python integration?as i see it, python and postgresql are a quite powerful combination, when done properly.i would like to learn more about this, and would appreciate some pointing in the right direction. On Tue, Sep 3, 2013 at 4:35 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. os.system vs subprocess.Popen args problems (learner404) > 2. Re: os.system vs subprocess.Popen args problems (Oscar Benjamin) > 3. help with postgreSQL and .csv (Ismar Sehic) > 4. Using tkinter for cross platform application (Max Bedacht) > 5. Re: help with postgreSQL and .csv (R. Alan Monroe) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 2 Sep 2013 16:19:17 +0200 > From: learner404 > To: Tutor Python > Subject: [Tutor] os.system vs subprocess.Popen args problems > Message-ID: > oaOzUVRgTh1Ru-7gQ at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hello, > > I can't understand why the command below works with os.system but not with > subprocess.Popen (on windows, recording video with FFMPEG.exe) > > cmd=('ffmpeg -f dshow -i video="%s" -f dshow -i audio="%s" -q 5 > "%s"')%(videoinputName, audioinputName, videoFileOutput) > os.system(cmd) > *works* > > > subprocess.Popen(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName,"-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5","%s"%videoFileOutput]) > *don't work* > >> [dshow @ 025984a0] Could not find video device. > >> video="QuickCam Orbit/Sphere AF": Input/output error > > The reason I'm going with subprocess is to avoid to have the DOS window > coming in the forefront. > Any idea of what I'm doing wrong? Or any other way to hide or minimize the > DOS window? > > Thanks. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130902/8e44abe0/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Mon, 2 Sep 2013 15:44:25 +0100 > From: Oscar Benjamin > To: learner404 > Cc: Tutor Python > Subject: Re: [Tutor] os.system vs subprocess.Popen args problems > Message-ID: > Ky5zt7db+p5oFB4ErLPCmBmGchA at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On 2 September 2013 15:19, learner404 wrote: > > Hello, > > > > I can't understand why the command below works with os.system but not > with > > subprocess.Popen (on windows, recording video with FFMPEG.exe) > > > > cmd=('ffmpeg -f dshow -i video="%s" -f dshow -i audio="%s" -q 5 > > "%s"')%(videoinputName, audioinputName, videoFileOutput) > > os.system(cmd) > > *works* > > > > > subprocess.Popen(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName,"-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5","%s"%videoFileOutput]) > > I think you need additional quotes for the videoFileOutput part e.g. > > '"%s"' % videoFileOutput > > > *don't work* > >>> [dshow @ 025984a0] Could not find video device. > >>> video="QuickCam Orbit/Sphere AF": Input/output error > > I see that video has spaces in it. You'd think it was unnecessary to > have those quotes since you've already split the command string into a > list of strings. Unfortunately Windows has a fairly arcane way of > handling arguments to subprocesses and Python tries to emulate that: > > http://docs.python.org/2/library/subprocess.html#converting-an-argument-sequence-to-a-string-on-windows > > > The reason I'm going with subprocess is to avoid to have the DOS window > > coming in the forefront. > > Any idea of what I'm doing wrong? Or any other way to hide or minimize > the > > DOS window? > > Another thing is that you shouldn't use Popen directly unless you're > doing something fancy (which you're not if os.system does what you > want). Use subprocess.check_call instead: > > > subprocess.check_call(["ffmpeg","-f","dshow","-i",'video="%s"'%videoinputName,"-f","dshow","-i",'audio="%s"'%audioinputName,"-q","5",'"%s"'%videoFileOutput]) > > > Oscar > > > ------------------------------ > > Message: 3 > Date: Mon, 2 Sep 2013 23:22:00 +0200 > From: Ismar Sehic > To: tutor at python.org > Subject: [Tutor] help with postgreSQL and .csv > Message-ID: > syg5g at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > hello. > i wrote the following code, to insert some values from a csv file to my > postgres table : > > * ****** > *import psycopg2* > *conn = psycopg2.connect("host = ***.***.***.*** user=******* dbname = > ****** ")* > *cur = conn.cursor()* > *import csv* > *with open('HotelImages.csv', 'rb') as f: * > * mycsv = csv.reader(f, delimiter = '|')* > * for row in mycsv:* > * hotel_code = row[0]* > * hotel_url = row[-1]* > * sql = " UPDATE hotel SET path_picture = "+"';"+hotel_url+"' > WHERE code LIKE '"+"%"+hotel_code+"'"* > * print '--->'+sql* > * cur.execute(sql)* > * conn.commit()* > *c.close()* > *print '----->Complete'* > * ******* > > > the for loop iterates through the table, comparing the values from the csv > line by line with the table column 'code'. > example of csv lines: > * ****** > *94176|HAB|7|2|09/094176/094176a_hb_w_007.jpg* > *94176|HAB|8|3|09/094176/094176a_hb_w_008.jpg* > *94176|BAR|6|7|09/094176/094176a_hb_ba_006.jpg* > *94176|RES|5|6|09/094176/094176a_hb_r_005.jpg* > *94176|HAB|1|1|09/094176/094176a_hb_w_001.jpg* > *94176|CON|4|8|09/094176/094176a_hb_k_004.jpg* > *94176|COM|2|4|09/094176/094176a_hb_l_002.jpg* > *94176|RES|3|5|09/094176/094176a_hb_r_003.jpg* > * ****** > example of the code column value : *GEN94176, XLK94176,KJK94176*.... > the number before the first ' | ' gets just one hit in the database table > column, inserts some random picture once.also, if the same numbers in some > other 'code' column row are appearing, but in different order, it inserts > the same picture. > my goal is to make it write all the picture url values separated by a ';' > in just one field and to input the data correctly. > i'm new to python, as a matter of fact, just started to learn programming. > i would really like to know where is my mistake.advice and help > appreciated! > > Thanks. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130902/a571b765/attachment-0001.html > > > > ------------------------------ > > Message: 4 > Date: Mon, 2 Sep 2013 22:32:33 -0300 > From: Max Bedacht > To: tutor at python.org > Subject: [Tutor] Using tkinter for cross platform application > Message-ID: > JYQcAxaY5xC6_0Po-SA at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hello; > I'm looking for a quick, if possible, solution to a problem I'm having. I > have developed an application which I'm packaging to run on Windows, Linux > and eventually OS-X. I have gone through myriad iterations, bouncing > between Python 2.7 and 3.3 and between 32 and 64 bit Linux, Windows XP and > Windows 8. At this point I can happily say that everything is working on > all platforms except Apple, which I can not test at this time. > > The problem that I am now trying to resolve, which I hope is the last one, > is the following: > > When running a packaged 'compiled' version on all windows platforms the > screen, while complete, is reduced by about 20% from the Linux version, > where the development was mostly done. Images seem all to be the same size, > as is the main window, but all of the text, labels and buttons are reduced > in size, not by much, but enough to be annoying. (Curiously, this size > difference does not happen in my development environment (Eclipse/PyDev). > There, if anything, the text in windows seems to be a bit larger than that > in Linux). > > I seem to have 3 options at this point: > > > 1. live with it; > 2. adjust the image portion, which seems fixed in size, to be x% smaller > in the Windows environment, making the overall window smaller but > maintaining proportionality; > 3. see if there is a magic bullet to resolve this issue. > > Any thoughts would be greatly appreciated. > > (Ubuntu 13.04 (64bit), Lubuntu 13.04(32Bit), Windows 8(64Bit), Windows > 7(64Bit), Windows XP > Python 2.7 and 3.3 64Bit on the Ubuntu box. > Python 2.7 and 3.3 32Bit on the Windows boxes > > Thanks; > Max Bedacht > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130902/f104ada1/attachment-0001.html > > > > ------------------------------ > > Message: 5 > Date: Mon, 2 Sep 2013 22:35:46 -0400 > From: "R. Alan Monroe" > To: tutor at python.org > Subject: Re: [Tutor] help with postgreSQL and .csv > Message-ID: <16110070470.20130902223546 at columbus.rr.com> > Content-Type: text/plain; charset=iso-8859-1 > > > my goal is to make it write all the picture url values separated by > > a ';' in just one field and to input the data correctly. ? > > I haven't used postgresql much. Could it be you're just missing > path_picture as part of your data value? i.e. > > UPDATE hotel SET path_picture = + hotel_url > UPDATE hotel SET path_picture = path_picture + hotel_url > > Alternatively, you could read the entire csv file and generate the > semicolon-separated strings as dictionary entries, then as a second > step, insert all those dictionary entries into the database. > > Alan > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 115, Issue 6 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jennifer.abbott at gov.sk.ca Wed Sep 4 18:42:37 2013 From: jennifer.abbott at gov.sk.ca (Abbott, Jennifer ENV) Date: Wed, 4 Sep 2013 16:42:37 +0000 Subject: [Tutor] Map Element Automation Message-ID: HI, I am trying to automate a map so that every time I make a new map with the same template the sub titles and other text changes according to the specific map properties. For instance, a field from the attribute table has the PROPERTY # and with each map I need that property number to be shown on each map. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Sep 4 23:21:31 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Sep 2013 22:21:31 +0100 Subject: [Tutor] resolution In-Reply-To: References: Message-ID: On 04/09/13 09:50, musa ezeri wrote: > im building an image processing software, but the python image > processing modules are in 32 bit and require 32bit python 2.7 where can > i find a 32 bit python 2.7? On the Python.org download page I would say. Which OS? If it's Linux and you are on 64bit it might be more tricky... If so which distro? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Sep 4 23:23:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Sep 2013 22:23:01 +0100 Subject: [Tutor] Map Element Automation In-Reply-To: References: Message-ID: On 04/09/13 17:42, Abbott, Jennifer ENV wrote: > I am trying to automate a map so that every time I make a new map with > the same template the sub titles and other text changes according to the > specific map properties. For instance, a field from the attribute table > has the PROPERTY # and with each map I need that property number to be > shown on each map. And where does Python fit in? This is a list for those learning Python and its standard library. How does your question relate to that? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Sep 4 23:28:03 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Sep 2013 22:28:03 +0100 Subject: [Tutor] postgresql was: Re: Tutor Digest, Vol 115, Issue 6 In-Reply-To: References: Message-ID: On 03/09/13 08:25, Ismar Sehic wrote: > help with postgres and csv: > i solved my problem by playing with the sql line a little. > it looked like this : sql = " UPDATE hotel SET path_picture = > "+"';"+hotel_url+"' > WHERE code LIKE '"+"%"+hotel_code+"'" > now it's like this : " UPDATE hotel SET path_picture = '" + hot_url + > "' WHERE code LIKE '%" + hot_code + "';" > > i guess the problem was in building the sql string, but i don't yet > quite understand what i did.can someone point me to some online resorces > about postgres and python integration? Googling "python postgres" seems to throw up quite a few links. Did you try any of them? If so do you have a specific area of interest? Also there are several APIs to use, each has links to their own sites. You can find a list here: https://wiki.python.org/moin/PostgreSQL Finally, please don't quote the entire digest when replying and please use a sensible subject line. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at alchemy.com Wed Sep 4 23:42:28 2013 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 4 Sep 2013 14:42:28 -0700 Subject: [Tutor] postgresql was: Re: Tutor Digest, Vol 115, Issue 6 In-Reply-To: References: Message-ID: On 04-Sep-2013, at 14:28, Alan Gauld wrote: > On 03/09/13 08:25, Ismar Sehic wrote: >> help with postgres and csv: >> i solved my problem by playing with the sql line a little. >> it looked like this : sql = " UPDATE hotel SET path_picture = >> "+"';"+hotel_url+"' >> WHERE code LIKE '"+"%"+hotel_code+"'" >> now it's like this : " UPDATE hotel SET path_picture = '" + hot_url + >> "' WHERE code LIKE '%" + hot_code + "';" >> >> i guess the problem was in building the sql string, but i don't yet >> quite understand what i did.can someone point me to some online resorces >> about postgres and python integration? > > https://wiki.python.org/moin/PostgreSQL > While you're looking at all the information Alan pointed you to, consider one other general bit of advice when programming with SQL queries. It is generally a very convenient trick to use string formatting or string catenation to build the bits of your query from pieces, like you did above ("UPDATE ? SET path_picture='" + hot_url + ?). Convenient, but a very, very bad idea in practice. This makes your program vulnerable to SQL injection, which in many cases can have devastating effects when someone exploits it. Assuming that the variables come from sources beyond your control (and even if they are--at the moment--generated by you), use parameterized queries (look for those in your API libraries). They usually look something like the following (although specifics can vary), where you leave a placeholder character like ? in the SQL string, and supply the data values separately. Unlike using string-maniputation features of Python, the database API knows exactly how to properly include those data values into the SQL command for you: some_api_function_to_do_sql("UPDATE hotel SET path_picture = ? WHERE code LIKE ?", hot_url, '%' + hot_code + '%') --steve From alan.gauld at btinternet.com Thu Sep 5 00:56:43 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 4 Sep 2013 23:56:43 +0100 (BST) Subject: [Tutor] Map Element Automation In-Reply-To: References: Message-ID: <1378335403.18307.YahooMailNeo@web186004.mail.ir2.yahoo.com> Please use ReplyAll to include the list in your responses. ? I'm using python to automate this process. The map elements can be automatically? >updated using python, I just can't figure out how to access an attribute in the layer's? >attribute table. I don't think there is any other way to automate a map without python.You are going to have to give us an awful lot more information. What OS and Python version? What technology is your map using? (database, language etc?)? Is is a commercial package??Open source? Which one? What architecture does your solution have? (eg client/server, web server? desktop?) Also what is your experience level in programming in general? and Python in particular? Its probable that there is a more appropriate forum to ask your questions but we? can't even direct you there with the little information you have given so far. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 5 01:03:23 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 4 Sep 2013 19:03:23 -0400 Subject: [Tutor] myown.getfilesystemencoding() In-Reply-To: <1378298350.39416.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1377875054.96190.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1378298350.39416.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On Wed, Sep 4, 2013 at 8:39 AM, Albert-Jan Roskam wrote: > But given that chcp returns cp850 on my windows system (commandline), > wouldn't it be more descriptive if sys.getfilesystemencoding() > returned 'cp850'? The common file systems (NTFS, FAT32, UDF, exFAT) support Unicode filenames. The console also uses Unicode, but proper display depends on the current font. The cmd shell encodes to the current codepage when redirecting output from an internal command, unless it was started with /U to force Unicode (e.g. cmd /U /c dir > files.txt). For subprocess, run cmd.exe explicitly with /U (i.e. don't use shell=True), and decode the output as UTF-16. Also, some utilities, such as tree.com, display Unicode fine but always use the OEM code page when output is redirected to a file or pipe (i.e. changing the console code page won't help). > In other words: In the code below, isn't line [1] an obfuscated version of > line [2]? Both versions return only question marks on my system. > > # Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] > on win32 > import ctypes > > ords = [3629, 3633, 3585, 3625, 3619, 3652, 3607, 3618] > u = "".join([unichr(i) for i in ords]) > print u.encode("mbcs") # [1] > > #cp850 is what chcp returns on my Windows system > print u.encode("cp850", "replace") # [2] > > thai_latin_cp = "cp874" > cp_ = int(thai_latin_cp[2:]) > ctypes.windll.kernel32.SetConsoleCP(cp_) > ctypes.windll.kernel32.SetConsoleOutputCP(cp_) > print u.encode("cp874", "replace") "mbcs" is the ANSI codepage (1252), not the OEM codepage (850) nor the current codepage. Neither supports Thai characters. It would be better to compare an OEM box drawing character: >>> from unicodedata import name >>> u = u'\u2500' >>> name(u) 'BOX DRAWINGS LIGHT HORIZONTAL' >>> name(u.encode('850', 'replace').decode('850')) 'BOX DRAWINGS LIGHT HORIZONTAL' >>> name(u.encode('mbcs', 'replace').decode('mbcs')) 'HYPHEN-MINUS' > ctypes.windll.kernel32.SetConsoleCP() and SetConsoleOutputCP seem useful. > Can these functions be used to correctly display the Thai characters on > my western European Windows version? (last block of code is an attempt) > Or is that not possible altogether? If stdout is a console, a write eventually ends up at WriteConsoleA(), which decodes to the console's native Unicode based on the current output codepage. If you're using codepage 847 and the current font supports Thai characters, it should display fine. It's also possible to write a Unicode string directly by calling WriteConsoleW with ctypes. From steve at pearwood.info Thu Sep 5 01:11:50 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 5 Sep 2013 09:11:50 +1000 Subject: [Tutor] Python 2 & 3 and unittest In-Reply-To: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <20130904231150.GA23185@ando> On Wed, Sep 04, 2013 at 06:30:12AM -0700, Albert-Jan Roskam wrote: > Hi, > > I am trying to make my app work in Python 2.7 and Python 3.3 (one > codebase) and I might later also try to make it work on Python 2.6 and > Python 3.2 (if I am not too fed up with it ;-). I was very happy to > notice that the 'b' prefix for bytes objects is also supported for > byte strings in Python 2.7. Likewise, I just found out that the "u" > has been re-introduced in Python 3.3 (I believe this is the first > Python 3 version where this re-appears). > > I am now cursing myself for having used doctest for my tests. Well that's just silly :-) Doc tests and unit tests have completely different purposes, and besides, in general doc tests are easier to make version independent. Many of your doc tests will still continue to work, and those that don't can almost always be adapted to be cross-platform. > So I am planning to rewrite everything in unittest. > Is the try-except block below the best way to make this test work in > Python 2.6 through 3.3? > > import unitttest > import blah? # my package > > > class test_blah(unittest.TestCase): > ??? def test_someTest(self): > ??????? try: > ? ? ? ?? ?? expected = [u"lalala", 1] # Python 2.6>= & Python 3.3>= > ??????? except SyntaxError: > ? ? ? ?? ?? expected = ["lalala", 1] # Python 3.0, 3.1, 3.2 That cannot work. try...except catches *run time* exceptions. SyntaxError occurs at *compile time*, before the try...except gets a chance to run. Unfortunately, there is no good way to write version-independent code involving strings across Python 2.x and 3.x. If you just support 3.3 and better, it is simple, but otherwise you're stuck with various nasty work arounds, none of which are ideal. Probably the least worst for your purposes is to create a helper function in your unit test: if version < '3': def u(astr): return unicode(astr) else: def u(astr): return astr Then, everywhere you want a Unicode string, use: u("something") The two problems with this are: 1) It is slightly slower, but for testing purposes that doesn't really matter; and 2) You cannot write non-ASCII literals in your strings. Or at least not safely. > Another, though related question. We have Python 2.7 in the office and > eventually we will move to some Python3 version. The code does not > generally need to remain Python2 compatible. What is the best > strategy: [a] write forward compatible code when using Python 2.7. > (using a 'b' prefix for byte strings, parentheses for the print > *statement*, sys.exc_info()[1] for error messages, etc.). [b] totally > rely on 2to3 script and don't make the Python2 code less reabable and > less idiomatic before the upgrade. Option a, but not the way you say it. Start by putting from __future__ import division, print_function at the top of your 2.x code. I don't believe there is a way to make string literals unicode, you just have to get used to writing u"" and b"" strings by hand. You can also do: from future_builtins import * range = xrange which will replace a bunch of builtins with Python3 compatible versions. Be prepared for a torrid time getting used to Unicode strings. Not because Unicode is hard, it isn't, but because you'll have to unlearn a lot of things that you thought you knew. The first thing to unlearn is this: there is no such thing as "plain text". Unfortunately Python 2 tries to be helpful when dealing with text versus bytes, and that actually teaches bad habits. This is the sort of thing I'm talking about: [steve at ando ~]$ python2.7 -c "print 'a' + u'b'" ab That sort of implicit conversion of bytes and strings is actually a bad idea, and Python 3 prohibits it: [steve at ando ~]$ python3.3 -c "print(b'a' + u'b')" Traceback (most recent call last): File "", line 1, in TypeError: can't concat bytes to str The other bad thing about Unicode is that, unless you are lucky enough to be generating all your own textual data, you'll eventually have to deal with cross-platform text issues, and text generated by people who didn't understand Unicode and therefore produce rubbish data containing mojibake and worse. But the good thing is, the Unicode model actually isn't hard to understand, and once you learn the language of "encodings", "code points" etc. it makes great sense. Unless you're working with binary data, you are much better off learning how to use Unicode u"" strings now. Just be aware that unless you are careful, Python 2 will try to be helpful, and you don't want that. -- Steven From steve at pearwood.info Thu Sep 5 01:15:16 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 5 Sep 2013 09:15:16 +1000 Subject: [Tutor] resolution In-Reply-To: References: Message-ID: <20130904231516.GB23185@ando> On Wed, Sep 04, 2013 at 10:50:54AM +0200, musa ezeri wrote: > im building an image processing software, but the python image processing > modules are in 32 bit and require 32bit python 2.7 where can i find a 32 > bit python 2.7? http://www.python.org/download/ -- Steven From steve at pearwood.info Thu Sep 5 01:21:23 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 5 Sep 2013 09:21:23 +1000 Subject: [Tutor] Python 2 & 3 and unittest In-Reply-To: <20130904231150.GA23185@ando> References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20130904231150.GA23185@ando> Message-ID: <20130904232123.GC23185@ando> On Thu, Sep 05, 2013 at 09:11:50AM +1000, Steven D'Aprano wrote: > I don't believe there is a way to make > string literals unicode, you just have to get used to writing u"" and > b"" strings by hand. Sorry, that is unclear. I meant to say, there is no way to force unprefixed strings "" to be Unicode in 2.x. -- Steven From steve at pearwood.info Thu Sep 5 01:29:16 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 5 Sep 2013 09:29:16 +1000 Subject: [Tutor] myown.getfilesystemencoding() In-Reply-To: <1378298350.39416.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1377875054.96190.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1378298350.39416.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <20130904232915.GD23185@ando> On Wed, Sep 04, 2013 at 05:39:10AM -0700, Albert-Jan Roskam wrote: > Wow, thanks for looking all this up. Thanks also to other people who > replied. It's not really desirable that a IDE adds confusion to an > area that's already confusing to begin with. Well, naturally it isn't desirable to add confusion, but I think that when dealing with IDEs it is unavoidable. The whole point of an IDE is that it is an *integrated* environment, which implies that the environment that Python runs in is not the same as unintegrated Python would be running in. > But given that chcp > returns cp850 on my windows system (commandline), wouldn't it be more > descriptive if sys.getfilesystemencoding() returned 'cp850'? I cannot comment on the gory details of Windows file system encodings, except to say the sooner Windows moves to UTF-8 everywhere like the rest of the civilized world, the better. -- Steven From __peter__ at web.de Thu Sep 5 08:29:30 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Sep 2013 08:29:30 +0200 Subject: [Tutor] Python 2 & 3 and unittest References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20130904231150.GA23185@ando> <20130904232123.GC23185@ando> Message-ID: Steven D'Aprano wrote: > On Thu, Sep 05, 2013 at 09:11:50AM +1000, Steven D'Aprano wrote: > >> I don't believe there is a way to make >> string literals unicode, you just have to get used to writing u"" and >> b"" strings by hand. > > Sorry, that is unclear. I meant to say, there is no way to force > unprefixed strings "" to be Unicode in 2.x. For 2.6 and above there is from __future__ import unicode_literals From fomcl at yahoo.com Thu Sep 5 11:47:29 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 5 Sep 2013 02:47:29 -0700 (PDT) Subject: [Tutor] Python 2 & 3 and unittest In-Reply-To: References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20130904231150.GA23185@ando> <20130904232123.GC23185@ando> Message-ID: <1378374449.14868.YahooMailNeo@web163803.mail.gq1.yahoo.com> ----- Original Message ----- > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Cc: > Sent: Thursday, September 5, 2013 8:29 AM > Subject: Re: [Tutor] Python 2 & 3 and unittest > > Steven D'Aprano wrote: > >> On Thu, Sep 05, 2013 at 09:11:50AM +1000, Steven D'Aprano wrote: >> >>> I don't believe there is a way to make >>> string literals unicode, you just have to get used to writing > u"" and >>> b"" strings by hand. >> >> Sorry, that is unclear. I meant to say, there is no way to force >> unprefixed strings "" to be Unicode in 2.x. > > For 2.6 and above there is > > from __future__ import unicode_literals I can't find the SO page I am looking for, but this is also an intesting one. Using the 'future' import may break code. But implicitly concatening byte/unicode strings is banned in python3 anyway. I am planning to checkout unicodenazi and ascii_with_complaints http://stackoverflow.com/questions/809796/any-gotchas-using-unicode-literals-in-python-2-6 From fomcl at yahoo.com Thu Sep 5 12:20:23 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 5 Sep 2013 03:20:23 -0700 (PDT) Subject: [Tutor] Python 2 & 3 and unittest In-Reply-To: <20130904231150.GA23185@ando> References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20130904231150.GA23185@ando> Message-ID: <1378376423.2245.YahooMailNeo@web163801.mail.gq1.yahoo.com> ----- Original Message ----- > From: Steven D'Aprano > To: tutor at python.org > Cc: > Sent: Thursday, September 5, 2013 1:11 AM > Subject: Re: [Tutor] Python 2 & 3 and unittest > > On Wed, Sep 04, 2013 at 06:30:12AM -0700, Albert-Jan Roskam wrote: >> Hi, >> >> I am trying to make my app work in Python 2.7 and Python 3.3 (one >> codebase) and I might later also try to make it work on Python 2.6 and >> Python 3.2 (if I am not too fed up with it ;-). I was very happy to >> notice that the 'b' prefix for bytes objects is also supported for >> byte strings in Python 2.7. Likewise, I just found out that the > "u" >> has been re-introduced in Python 3.3 (I believe this is the first >> Python 3 version where this re-appears). >> >> I am now cursing myself for having used doctest for my tests. > > Well that's just silly :-) > > Doc tests and unit tests have completely different purposes, and > besides, in general doc tests are easier to make version independent. > Many of your doc tests will still continue to work, and those that don't > can almost always be adapted to be cross-platform. Hmm, maybe?the page below was exaggerating. I hope so. Given that quite a few?__repr__ methods have changed (bytes objects, views, ...) I still fear that a whole bunch of tests need to be modified. http://python3porting.com/problems.html: "Running doctests - One of the more persistently annoying problems you may encounter are doctests. Personally I think doctests are brilliant for testing documentation, but there has been a recommendation in some circuits to make as many tests as possible doctests. This becomes a problem with Python?3 because doctests rely on comparing the output of the code. That means they are sensitive to changes in formatting and Python?3 has several of these. This means that if you have doctests you will get many, many failures. Don?t despair! Most of them are not actual failures, but changes in the output formatting. 2to3 handles that change in the code of the doctests, but not in the output. If you are only porting to Python?3, the solution is simple and boring. Run the doctests and look at each failure to see if it is a real failure or a change in formatting. This can sometimes be frustrating, as you can sit and stare at a failure trying to figure out what actually is different between the expected and the actual output. On the other hand, that?s normal with doctests, even when you aren?t porting to Python?3, which of course is one of the reasons that they aren?t suitable as the main form of testing for a project. It gets more tricky if you need to continue to support Python?2, since you need to write output that works in both versions and that can be difficult and in some cases impossible for example when testing for exceptions, see below." ? >> So I am planning to rewrite everything in unittest. >> Is the try-except block below the best way to make this test work in >> Python 2.6 through 3.3? >> >> import unitttest >> import blah? # my package >> >> >> class test_blah(unittest.TestCase): >> ??? def test_someTest(self): >> ??????? try: >> ? ? ? ?? ?? expected = [u"lalala", 1] # Python 2.6>= & > Python 3.3>= >> ??????? except SyntaxError: >> ? ? ? ?? ?? expected = ["lalala", 1] # Python 3.0, 3.1, 3.2 > > That cannot work. try...except catches *run time* exceptions. > SyntaxError occurs at *compile time*, before the try...except gets a > chance to run. > > Unfortunately, there is no good way to write version-independent code > involving strings across Python 2.x and 3.x. If you just support 3.3 and > better, it is simple, but otherwise you're stuck with various nasty work > arounds, none of which are ideal. > > Probably the least worst for your purposes is to create a helper > function in your unit test: > > if version < '3': > ? ? def u(astr): > ? ? ? ? return unicode(astr) > else: > ? ? def u(astr): > ? ? ? ? return astr > > Then, everywhere you want a Unicode string, use: > > u("something") > > The two problems with this are: > > 1) It is slightly slower, but for testing purposes that doesn't really > matter; and > > 2) You cannot write non-ASCII literals in your strings. Or at least not > safely. > > >> Another, though related question. We have Python 2.7 in the office and >> eventually we will move to some Python3 version. The code does not >> generally need to remain Python2 compatible. What is the best >> strategy: [a] write forward compatible code when using Python 2.7. >> (using a 'b' prefix for byte strings, parentheses for the print >> *statement*, sys.exc_info()[1] for error messages, etc.). [b] totally >> rely on 2to3 script and don't make the Python2 code less reabable and >> less idiomatic before the upgrade. > > Option a, but not the way you say it. Start by putting > > from __future__ import division, print_function ? Assuming I never use the arguments of the print function, why also import print_function??print("something") works no matter if 'print' is a statement or?a function. ? ? > at the top of your 2.x code. I don't believe there is a way to make > string literals unicode, you just have to get used to writing u"" and > b"" strings by hand. > > You can also do: > > from future_builtins import * > range = xrange > > which will replace a bunch of builtins with Python3 compatible versions. > > Be prepared for a torrid time getting used to Unicode strings. Not > because Unicode is hard, it isn't, but because you'll have to unlearn a > lot of things that you thought you knew. The first thing to unlearn is > this: there is no such thing as "plain text". ? Switching back and forth between python 2 and 3 creates quite some mental overhead indeed. The?association of str() with the concept "byte strings" is hard-coded somewhere in my medulla oblongata. And now it suddenly means unicode string! Nice implementation of the stroop effect ;-)) http://en.wikipedia.org/wiki/Stroop_effect ? > Unfortunately Python 2 tries to be helpful when dealing with text versus > bytes, and that actually teaches bad habits. This is the sort of thing > I'm talking about: > > [steve at ando ~]$ python2.7 -c "print 'a' + u'b'" > ab ? The ascii_with_complaints?codec seems to offer some help here. I have not yet tried it though. ? > That sort of implicit conversion of bytes and strings is actually a bad > idea, and Python 3 prohibits it: > > [steve at ando ~]$ python3.3 -c "print(b'a' + u'b')" > Traceback (most recent call last): > ? File "", line 1, in > TypeError: can't concat bytes to str > > > The other bad thing about Unicode is that, unless you are lucky enough > to be generating all your own textual data, you'll eventually have to > deal with cross-platform text issues, and text generated by people who > didn't understand Unicode and therefore produce rubbish data containing > mojibake and worse. > > But the good thing is, the Unicode model actually isn't hard to > understand, and once you learn the language of "encodings", "code > > points" etc. it makes great sense. > > Unless you're working with binary data, you are much better off learning > how to use Unicode u"" strings now. Just be aware that unless you are > careful, Python 2 will try to be helpful, and you don't want that. ? I am using lots of char pointers (ctypes.c_char_p) which don't take unicode strings. I wrote a small wrapper function c_char_py3k that turns the?strings in to bytes objects if applicable and needed, then calls c_char_p. From oscar.j.benjamin at gmail.com Thu Sep 5 12:29:07 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 5 Sep 2013 11:29:07 +0100 Subject: [Tutor] Python 2 & 3 and unittest In-Reply-To: <1378376423.2245.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20130904231150.GA23185@ando> <1378376423.2245.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 5 September 2013 11:20, Albert-Jan Roskam wrote: >> from __future__ import division, print_function > > Assuming I never use the arguments of the print function, why also import print_function? print("something") works no matter if 'print' is a statement or a function. The problem is when you want to print more than one thing i.e. print(a, b) vs print a, b While the former isn't an error in Python 2.x it prints the tuple (a, b) with brackets which will break any doctest. The latter form is a syntax error in 3.x that would be dealt with by the 2to3 fixer except you're trying to use a single codebase so that won't work for you. Oscar From iafleischer at gmail.com Thu Sep 5 21:13:16 2013 From: iafleischer at gmail.com (I. Alejandro Fleischer) Date: Thu, 5 Sep 2013 15:13:16 -0400 Subject: [Tutor] Tutor Digest, Vol 114, Issue 73 In-Reply-To: References: Message-ID: Dear Friends, I have a set of data to fit to a custom equation, y=a+b*exp(k*x), would you advice me on the how to, or tutorial? Thank you On Thu, Aug 22, 2013 at 10:11 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: hi (Oscar Benjamin) > 2. global variables (Matthew Ngaha) > 3. Re: global variables (Chris Down) > 4. Re: global variables (Matthew Ngaha) > 5. Re: global variables (Chris Down) > 6. Re: global variables (Alan Gauld) > 7. Re: global variables (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 22 Aug 2013 13:03:10 +0100 > From: Oscar Benjamin > To: Vick > Cc: "Tutor at python.org" > Subject: Re: [Tutor] hi > Message-ID: > On53Hr1g at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On 20 August 2013 13:49, Vick wrote: > > > > From: Oscar Benjamin [mailto:oscar.j.benjamin at gmail.com] > > > >> Well just send me some tutorial on how to build and obtain the > >> coefficients for the butcher tableau for the RK4 as an example, and > >> after I've mastered it, I'd give the dopri8 a shot. > > > > I am up for it so I'll see if I can find time to write a script that > shows > > how to do it. > > > > [Vick] Hope you've had the time to code it. I'm waiting for it. > > Sorry, I haven't found the time yet. It is still on my todo list though! > > > By the way your code for the Adams-Moulton coefficients are actually the > > Adams-Bashforth ones and so I copied it and modified the copy to have the > > Adams-Moulton coefficients as well. This means that I have now an > nth-order > > predictor-corrector method to solve for ODEs. > > Oh sorry. That'll be a cut and paste error. My code lives in a private > software library that I keep meaning to release on PyPI but it's not > ready for public consumption in quite a number of ways. > > I'm glad that you worked it out though. You''ll probably understand > what I mean now when I say that the AM or AB integrators need a > secondary algorithm to bootstrap. The accuracy of the subsequent AM/AB > method depends on the accuracy of that step. In the worst case you can > just use rk4 with a very small time-step for this bit though. > > > Oscar > > > ------------------------------ > > Message: 2 > Date: Thu, 22 Aug 2013 13:36:24 +0100 > From: Matthew Ngaha > To: "tutor at python.org" > Subject: [Tutor] global variables > Message-ID: > zO+y3BY20vkAumhaPTQ0w at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > I'm always told to avoid using them. I read discussions on the python > irc channel about them but honestly i feel there are some times where > i can't avoid using them. Like where i want to keep track of a state > variable in many different functions that may or may not alter its > value and also not wanting any of the functions to return it to the > caller. > > My question is how many global variables did your last decent sized > program have? Also please share any insight you have about them. I do > try to avoid them, but is this always possible? > > > ------------------------------ > > Message: 3 > Date: Thu, 22 Aug 2013 14:40:34 +0200 > From: Chris Down > To: Matthew Ngaha > Cc: "tutor at python.org" > Subject: Re: [Tutor] global variables > Message-ID: <20130822124033.GC4577 at chrisdown.name> > Content-Type: text/plain; charset="us-ascii" > > On 2013-08-22 13:36, Matthew Ngaha wrote: > > I'm always told to avoid using them. I read discussions on the python > > irc channel about them but honestly i feel there are some times where > > i can't avoid using them. Like where i want to keep track of a state > > variable in many different functions that may or may not alter its > > value and also not wanting any of the functions to return it to the > > caller. > > It sounds like you want to use a class. > > > My question is how many global variables did your last decent sized > > program have? Also please share any insight you have about them. I do > > try to avoid them, but is this always possible? > > I don't have any global variables in any of my projects, and I've been > programming Python in some capacity for almost 8 years now. Why would you > not > just use a class if you want to store state? > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: not available > Type: application/pgp-signature > Size: 490 bytes > Desc: not available > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130822/02883212/attachment-0001.sig > > > > ------------------------------ > > Message: 4 > Date: Thu, 22 Aug 2013 14:43:03 +0100 > From: Matthew Ngaha > To: Chris Down > Cc: "tutor at python.org" > Subject: Re: [Tutor] global variables > Message-ID: > < > CACzNyA3K-hj8PTRTa9W2NaShUtqbPFgYAU0_a7Sa_jTRoXY8NA at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On Thu, Aug 22, 2013 at 1:40 PM, Chris Down wrote: > > > It sounds like you want to use a class. > > Why would you not just use a class if you want to store state? > > I don't feel my program needs a class. Also i have been told to stop > using classes by some very experienced Python programmers on irc even > though i don't see why. It's confusing being told different things. > > > ------------------------------ > > Message: 5 > Date: Thu, 22 Aug 2013 15:52:13 +0200 > From: Chris Down > To: Matthew Ngaha > Cc: "tutor at python.org" > Subject: Re: [Tutor] global variables > Message-ID: <20130822135212.GA6965 at chrisdown.name> > Content-Type: text/plain; charset="us-ascii" > > On 2013-08-22 14:43, Matthew Ngaha wrote: > > I don't feel my program needs a class. Also i have been told to stop > > using classes by some very experienced Python programmers on irc even > > though i don't see why. It's confusing being told different things. > > Well, if you want to store state, you should really be using a class. What > has > made you think that your program doesn't "need a class"? There's no "need", > there's just what's best suited to your problem case (which you have not > made > clear, so nobody can comment on it). > > No experienced Python programmers are going to universally tell you not to > use > classes, likewise, no experienced Python programmers are going to > universally > tell you to use them all the time. It's a matter of context and > suitability, > which is entirely dependent on what it is that you are coding in the first > place. I would doubt that anyone has told you "don't ever use classes", > because > that's nonsense; you've probably misread a dissuasion from that path in a > single instance as applying more broadly than was intended. > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: not available > Type: application/pgp-signature > Size: 490 bytes > Desc: not available > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130822/8b858999/attachment-0001.sig > > > > ------------------------------ > > Message: 6 > Date: Thu, 22 Aug 2013 15:04:42 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] global variables > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 22/08/13 13:36, Matthew Ngaha wrote: > > I'm always told to avoid using them. > > Global variables in themselves are not the problem. > It's how they tend to get used that causes problems. > Read-only global values - aka constants (so not > really variables!) - are not an issue. > > Globals that are only changed via a set of > dedicated functions are not topo much of a > problem - although they should probably be > bundled as a class (or module) if you have > such features available. > > > i can't avoid using them. Like where i want to > > keep track of a state variable in many > > different functions > > Usually that should be in a class. A class represents > a set of operations using common data. Therefore shared > state would naturally fit in a class along with the > operations which depend on/modify that state. > > You may then have a single global variable which > is the instance of that class. > > > also not wanting any of the functions to return it to the > > caller. > > Thats more problematic and usually a sign of a bad design. > Even if using global variables you should modify them > explicitly via return values of functions rather than > as hidden side-effects inside other functions. > > mystate = changestate(mystate, some, other, args) > > > My question is how many global variables did your last decent sized > > program have? > > I usually have not more than a half dozen plus one per > thousand lines of code. So in a 10,000 line program I'd > expect to have less than 16 in total (actually I'd hope > less than 10!). And many of those would be instances > of classes. I would not expect to have more than one > or two fundamental typed globals (ints, strings, bools etc), > if any. > > > Also please share any insight you have about them. I do > > try to avoid them, but is this always possible? > > It is possible but only by playing silly games with > semantics such as: > > class MyProgram > global1 = 0 > global2 = True > > def __init__(self, lots, of, args, > self.inst1 = .... # initialise program runtime vars > def run(self) > # my program code all goes here > # and accesses the class level globals and instance > # level runtime and state values > > if __name__ = __main__": > MyProgram(args....).run() > > [Or alternatively you can hide them inside a database.] > > Now technically there are no globals but in fact we are > just moving them inside the meaningless class and have > all the same potential issues with global side effects > etc. > > In my experience there are usually a few globals required > for any meaningful program. It's not avoiding globals > completely that's important, it's being careful to use > them sensibly and with good adherence to the principles > of coupling and cohesion in the design. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Message: 7 > Date: Thu, 22 Aug 2013 15:10:55 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] global variables > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 22/08/13 14:43, Matthew Ngaha wrote: > > On Thu, Aug 22, 2013 at 1:40 PM, Chris Down > wrote: > >> It sounds like you want to use a class. > >> Why would you not just use a class if you want to store state? > > Local coding conventions or programmer skill levels may preclude it. > > > I don't feel my program needs a class. > > But in this case it sounds like a class is the best solution. > Why would you "feel" that you don't need a class when you have a > situation where several functions share common state? That's > almost the definition of a class. > > > Also i have been told to stop using classes by some very > > experienced Python programmers on irc > > Really? What reasons did they give. > Unless they are talking about very specific circumstances > that doesn't sound like good advice! > > > It's confusing being told different things. > > Software engineering, like any branch of engineering, is about learning > to use many different tools and selecting the best set for a problem. > There are cases where classes are not in the best set, there are cases > where many global variables are a good fit. But both of these are the > exceptions to the rule and the engineer's job is to identify when a > genuine exception exists and make the right choice. There is never a > single right answer. Sorry, but that's life. > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 114, Issue 73 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Sep 5 22:51:57 2013 From: bgailer at gmail.com (bob gailer) Date: Thu, 05 Sep 2013 16:51:57 -0400 Subject: [Tutor] fit data to equation In-Reply-To: References: Message-ID: <5228EEED.3060605@gmail.com> On 9/5/2013 3:13 PM, I. Alejandro Fleischer wrote: > Dear Friends, Hi and welcome to the tutor list. Since you are new bear with me while I offer some important guidelines to effective communication with us. 1 - don't "hijack" some other email as a quick way to get our email address. 2 - when communicating delete all irrelevant text. We don't need to see all the digest. 3 - always use a meaningful subject 4 - when starting a new subject start a new email. Otherwise our thread trackers bury the (to you new) message. > > I have a set of data to fit to a custom equation, y=a+b*exp(k*x), > would you advice me on the how to, or tutorial? Curve fitting is not my strength. Perhaps someone else on the list will come to your aid. -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Thu Sep 5 22:59:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 05 Sep 2013 21:59:59 +0100 Subject: [Tutor] equation solving (was: Re: Tutor Digest, Vol 114, Issue 73) In-Reply-To: References: Message-ID: On 05/09/13 20:13, I. Alejandro Fleischer wrote: > Dear Friends, Hi, please, in future, do not resend the entire digest message - it just clutters up inboxes and costs members money on their bandwidth allowance. Alsao change the subject line to something relevant (as I've done here). Also, send new posts direct to tutor at python.org its easier to work with in threaded readers and archive lists. Now to your question... > I have a set of data to fit to a custom equation, y=a+b*exp(k*x), would > you advice me on the how to, or tutorial? Can be be more precise? The more specific you are the easier it is to give specific answers. Do you have all of the constants and only want a mapping of x and y values? Or do you have a subset of x and y and want to find an arbitrary set of constants that will make the equation fit? There are well known mathematical techniques for doing this kind of thing. Are you aware of them and need help implementing them in Python? Or are you starting with no knowledge of how to solve the problem? It's difficult to know what kind of help you need until we know more about you and the problem -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Thu Sep 5 23:37:26 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 5 Sep 2013 14:37:26 -0700 (PDT) Subject: [Tutor] Python 2 & 3 and unittest In-Reply-To: References: <1378301412.11876.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <1378417046.99308.YahooMailNeo@web163803.mail.gq1.yahoo.com> ---- Original Message ----- > From: Don Jennings > To: Albert-Jan Roskam > Cc: Python Mailing List > Sent: Wednesday, September 4, 2013 4:15 PM > Subject: Re: [Tutor] Python 2 & 3 and unittest > > > On Sep 4, 2013, at 9:30 AM, Albert-Jan Roskam wrote: > >> Hi, >> >> I am trying to make my app work in Python 2.7 and Python 3.3 (one codebase) > and I might later also try to make it work on Python 2.6 and Python 3.2 (if I am > not too fed up with it ;-). > > You might like to read Armin Ronacher's (Flask, Jinja2) take on this topic > [1]. > > Take care, > Don > > [1] http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux *Very* useful page, thanks! Also a cool example of a class decorator on that page. Python Modernize also sounds promising. I've downloaded it but did not yet try it. From oscar.j.benjamin at gmail.com Fri Sep 6 11:27:59 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 6 Sep 2013 10:27:59 +0100 Subject: [Tutor] equation solving (was: Re: Tutor Digest, Vol 114, Issue 73) In-Reply-To: References: Message-ID: On 5 September 2013 21:59, Alan Gauld wrote: > On 05/09/13 20:13, I. Alejandro Fleischer wrote: >> >> I have a set of data to fit to a custom equation, y=a+b*exp(k*x), would >> you advice me on the how to, or tutorial? > > Can be be more precise? The more specific you are the easier it is > to give specific answers. I agree with Alan. You need to be more specific. I think that I understand what you mean but perhaps you aren't aware that your problem is ill-posed. I'm going to assume that you have some data that gives paired measurements of two quantities e.g. (x1, y1), (x2, y2), ... (xn, yn). You want to find parameters a, b, and k so that y = a+b*exp(k*x) is a good fit to your data. The problem is that there is no unique definition of a "good" fit. A well-posed optimisation problem identifies a single scalar quantity that must be minimised (or maximised). The obvious choice in this kind of thing is to treat one of your measured variables as the independent variable (by convention this is called x) and the other as the dependent variable (by convention y) and then define your error as the sum of the squares of the residuals in estimating yi from xi: Error = (1/2) sum[i=1..N] { ((yi - (a+b*exp(k*xi)))**2) } However this is an arbitrary choice. You could have tried to regress x onto y instead and then used the residuals for x which would lead to different answers. Similarly choosing the sum of squares of the residuals is an arbitrary choice. In your particular case the highly non-linear relationship between x and y means that minimising this kind of error could lead to a poor result. If some of the yi are very large - as they could easily be for this exponential relationship - then your fit will end up being dominated by the largest data-points. In the worst case you'd basically be computing an exact fit to the three largest data-points. So a better residual might be something like: (yi - (a+b*exp(k*xi))) / yi It's hard to say without knowing more about the data or the problem though. In any case your problem is just complicated enough that you need a non-linear optimisation routine e.g. from scipy. If you knew the value of a you could do a linear regression of log(y-a) onto x. Similarly if you knew the value of k you could do a linear regression of y onto exp(k*x). If you don't know any of a, b, or k then you have a non-linear regression problem and you'll probably want to use a function for non-linear least squares or perhaps an arbitrary non-linear optimisation routine. So your first step is probably to install scipy if you haven't already and have a look at its optimize module. I can be more specific if you explain a little more about what you're trying to do and what your data looks like. Also as Alan says you need to explain how experienced you are in the relevant maths, and in programming and Python to get reasonable help. Oscar From alan.gauld at btinternet.com Fri Sep 6 12:47:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 06 Sep 2013 11:47:58 +0100 Subject: [Tutor] OT: Coffeescript and Python Message-ID: This is somewhat off topic so replies offlist may be appropriate. I've just come across coffeescript(*) and started playing with it. It seems to share a lot with Python and as such seems like a good replacement for Javascript in client side web code. I'm wondering if anyone here has used coffeescript with any of the Python web frameworks? Specifically any of Turbogears, Django or Pylons? (*)For any similarly afflicted souls, coffeescript is a language that compiles into pure (portable) javascript so it has no dependency issues with webservers or browsers but is easier to read/write. At least, that's the theory, I'm too early into it to be sure it works as advertised, but it looks promising. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From iafleischer at gmail.com Fri Sep 6 14:19:49 2013 From: iafleischer at gmail.com (I. Alejandro Fleischer) Date: Fri, 6 Sep 2013 08:19:49 -0400 Subject: [Tutor] fit data to equation Message-ID: Dear Alan and Oscar Thank you. I'll try to be more accurate: What Oscar wrote is exactly the situation: > "I'm going to assume that you have some data that gives paired > measurements of two quantities e.g. (x1, y1), (x2, y2), ... (xn, yn). > You want to find parameters a, b, and k so that y = a+b*exp(k*x) is a > good fit to your data. The problem is that there is no unique > definition of a "good" fit." > > > I will install scipy. > > So your first step is probably to install scipy if you haven't already > and have a look at its optimize module. I can be more specific if you > explain a little more about what you're trying to do and what your > data looks like. It's a variation , of a physical value ("y") in time ("x") (while cooling) , you have the data measured (xi, yi), but not from x=0. I need to extrapolate "y" to "x=0", by that equation. I know the very basics about statistics, and a beginner in python, I ve chosen python to work with. Regards, Igor -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Fri Sep 6 16:16:18 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 6 Sep 2013 15:16:18 +0100 Subject: [Tutor] fit data to equation In-Reply-To: References: Message-ID: On 6 September 2013 13:19, I. Alejandro Fleischer wrote: > > It's a variation , of a physical value ("y") in time ("x") (while > cooling) , you have the data measured (xi, yi), but not from x=0. I need to > extrapolate "y" to "x=0", by that equation. > > I know the very basics about statistics, and a beginner in python, I ve > chosen python to work with. Okay well you'll want numpy, scipy and matplotlib if you don't have those. Most documentation for those assumes familiarity with Python so you may want to work through a bit of a python tutorial first (if you haven't already). Then I'd suggest first writing a script that can just plot your data-points using matplotlib. Then for your actual fitting problem you'll want to use leastsq from scipy's optimize module. See section 5.4 in this link: http://www.tau.ac.il/~kineret/amit/scipy_tutorial/ Here's a basic example of how to use the function: from scipy.optimize import leastsq # The "true values" amin = 2 bmin = 3 # The residual as a function of the parameters a and b def residual(ab): a, b = ab return [amin - a, bmin - b] # Initial estimate of parameters a and b aguess = 0 bguess = 0 # Fitted values from fitting algorithm (afit, bfit), _ = leastsq(residual, (aguess, bguess)) print('afit: %s' % afit) print('bfit: %s' % bfit) Oscar From nelsonpaixaopinto at gmail.com Fri Sep 6 00:59:41 2013 From: nelsonpaixaopinto at gmail.com (nelsonpaixao) Date: Thu, 5 Sep 2013 22:59:41 +0000 (UTC) Subject: [Tutor] How to unpack python-dateutil-2.0.tar.gz References: Message-ID: Richard D. Moores gmail.com> writes: > > Python 3.2.3 64 bit > MS Windows 7 Home Premium 64-bit SP1 > > I see python-dateutil recommended here from time to time, so I thought > I'd try it out. I downloaded python-dateutil-2.1.tar.gz from > http://pypi.python.org/pypi/python-dateutil but have forgotten how to > unpack a .tar.gz file. Please remind me. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > hello there, today i was searching for that too, you can download here all the adds you need for python, all came with windons installer http://www.lfd.uci.edu/~gohlke/pythonlibs/ From emile at fenx.com Fri Sep 6 18:38:57 2013 From: emile at fenx.com (Emile van Sebille) Date: Fri, 06 Sep 2013 09:38:57 -0700 Subject: [Tutor] OT: Coffeescript and Python In-Reply-To: References: Message-ID: On 9/6/2013 3:47 AM, Alan Gauld wrote: > This is somewhat off topic so replies offlist may be appropriate. I can fix that. :) Are you familiar with pyjs, which provides python to javascript capabilities? (see http://pyjs.org/) Is there any reason to prefer one over the other? Emile > I've just come across coffeescript(*) and started playing with it. > It seems to share a lot with Python and as such seems like a good > replacement for Javascript in client side web code. I'm wondering if > anyone here has used coffeescript with any of the Python web frameworks? > Specifically any of Turbogears, Django or Pylons? > > (*)For any similarly afflicted souls, coffeescript is a language that > compiles into pure (portable) javascript so it has no dependency issues > with webservers or browsers but is easier to read/write. At least, > that's the theory, I'm too early into it to be sure it works as > advertised, but it looks promising. > From japhy at pearachute.com Fri Sep 6 18:01:59 2013 From: japhy at pearachute.com (Japhy Bartlett) Date: Fri, 6 Sep 2013 11:01:59 -0500 Subject: [Tutor] OT: Coffeescript and Python In-Reply-To: References: Message-ID: I worked on a project that used cofeescript with Django. You basically have to know javascript to debug it properly, so it didn't really save our team any time and we got rid of it as soon as we could. Obviously that's just anecdotal, YMMV! On Fri, Sep 6, 2013 at 5:47 AM, Alan Gauld wrote: > This is somewhat off topic so replies offlist may be appropriate. > > I've just come across coffeescript(*) and started playing with it. > It seems to share a lot with Python and as such seems like a good > replacement for Javascript in client side web code. I'm wondering if anyone > here has used coffeescript with any of the Python web frameworks? > Specifically any of Turbogears, Django or Pylons? > > (*)For any similarly afflicted souls, coffeescript is a language that > compiles into pure (portable) javascript so it has no dependency issues > with webservers or browsers but is easier to read/write. At least, that's > the theory, I'm too early into it to be sure it works as advertised, but it > looks promising. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pretorian at hotmail.com Fri Sep 6 06:27:23 2013 From: pretorian at hotmail.com (mike johnson) Date: Fri, 6 Sep 2013 04:27:23 +0000 Subject: [Tutor] why do i keep getting syntax errors in python when this runs Message-ID: can you please help me figure out why this isnt working thanks # convert.py # this program is used to convert Celsius temps to Fahrenheit # By: James Michael Johnson Def main (): Celsius = float (input ("What is the Celsius temperature? ")) Fahrenheit = 9.0 / 5.0 * Celsius + 32 Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") Main () -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: convertcelsiustofarenheit.py Type: text/x-script.phyton Size: 312 bytes Desc: not available URL: From meher.tanmay3 at gmail.com Fri Sep 6 11:35:54 2013 From: meher.tanmay3 at gmail.com (Tanmaya Meher) Date: Fri, 6 Sep 2013 15:05:54 +0530 Subject: [Tutor] fit data to equation In-Reply-To: <5228EEED.3060605@gmail.com> References: <5228EEED.3060605@gmail.com> Message-ID: You can try the below tutorial. 1. http://wiki.scipy.org/Cookbook/FittingData 2. http://people.duke.edu/~ccc14/pcfb/analysis.html Also, take a look at the below curve fitting tool from optimization tool set of scipy. I think it will help you better and with ease. http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html If you are writing program on your own try lambda to define your function, use some library module like scipy for fitting / optimization and library module like pylab to plot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Sep 6 19:25:05 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 6 Sep 2013 13:25:05 -0400 Subject: [Tutor] why do i keep getting syntax errors in python when this runs In-Reply-To: References: Message-ID: On Fri, Sep 6, 2013 at 12:27 AM, mike johnson wrote: > can you please help me figure out why this isnt working thanks You have tthree problems: > # convert.py > # this program is used to convert Celsius temps to Fahrenheit > # By: James Michael Johnson > > Def main (): The keyword is def, not Def, so rewrite like: def main(): > Celsius = float (input ("What is the Celsius temperature? ")) > Fahrenheit = 9.0 / 5.0 * Celsius + 32 > Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") > > You have not indented the suite of code that runs in main, so set your editor to print 4 spaces when tab is pressed, and tab each line under main. > Main () You defined main() but you called Main. Python is case sensitive, so change this to main() > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From ramit.prasad at jpmorgan.com.dmarc.invalid Fri Sep 6 20:53:15 2013 From: ramit.prasad at jpmorgan.com.dmarc.invalid (Prasad, Ramit) Date: Fri, 6 Sep 2013 18:53:15 +0000 Subject: [Tutor] why do i keep getting syntax errors in python when this runs In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474186BA4C0@SCACMX008.exchad.jpmchase.net> Joel Goldstick wrote: > On Fri, Sep 6, 2013 at 12:27 AM, mike johnson wrote: > > can you please help me figure out why this isnt working thanks > > You have tthree problems: > > > # convert.py > > # this program is used to convert Celsius temps to Fahrenheit > > # By: James Michael Johnson > > > > Def main (): > > The keyword is def, not Def, so rewrite like: > def main(): > > > Celsius = float (input ("What is the Celsius temperature? ")) > > Fahrenheit = 9.0 / 5.0 * Celsius + 32 > > Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") > > > > > You have not indented the suite of code that runs in main, so set your > editor to print 4 spaces when tab is pressed, and tab each line under > main. > > > > Main () > > > You defined main() but you called Main. Python is case sensitive, so > change this to main() It should also be "print" and not "Print". ~Ramit 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. From corsam28 at hotmail.com Fri Sep 6 21:52:51 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Fri, 6 Sep 2013 14:52:51 -0500 Subject: [Tutor] (no subject) Message-ID: on my Interpreter windows, as my first attempt, I wrote "hello world" but it keep telling me this: SyntaxError: invalid syntax Can you help me please? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 7 01:31:30 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 07 Sep 2013 00:31:30 +0100 Subject: [Tutor] why do i keep getting syntax errors in python when this runs In-Reply-To: References: Message-ID: On 06/09/13 05:27, mike johnson wrote: > can you please help me figure out why this isnt working thanks The fundamental problem is that Python is case sensitive so Def and def are two different words. As are Main and main and Print and print. Also Python cares about spacing. You need to indent your code within the function. > Def main (): > Celsius = float (input ("What is the Celsius temperature? ")) > Fahrenheit = 9.0 / 5.0 * Celsius + 32 > Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") > > Main() Finally, as a matter of style, capitalized names tend to be reserved for class definitions (you probably haven't read about them yet!) This should therefore become: def main (): celsius = float (input ("What is the Celsius temperature? ")) fahrenheit = 9.0 / 5.0 * celsius + 32 print ("The temperature is ", fahrenheit, " degrees Fahrenheit.") main() HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Sep 7 01:35:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 07 Sep 2013 00:35:13 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 06/09/13 20:52, Sammy Cornet wrote: > on my Interpreter windows, as my first attempt, I wrote "hello world" > but it keep telling me this: SyntaxError: invalid syntax > Can you help me please? Python doesn't understand what "hello world" means. It's just a value, like 42 or True to python. So python reports a syntax error (ie 'grammar' it doesn't understand). You need to tell Python what to do with your text. I suspect you wanted to print it so you should type: print("hello world") Find a tutorial you like and follow it until you get the hang of things. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Sep 7 01:44:29 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 7 Sep 2013 09:44:29 +1000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <20130906234429.GB26319@ando> On Fri, Sep 06, 2013 at 02:52:51PM -0500, Sammy Cornet wrote: > on my Interpreter windows, as my first attempt, I wrote "hello world" > but it keep telling me this: SyntaxError: invalid syntax > Can you help me please? Yes. The first, and most important, tool in your toolbox as a programmer is to take careful note of the error messages you are given. The second most important tool is to ask good questions. Asking good questions means showing exactly what you did, *precisely*, and not leaving it up to the reader to guess. The best way is to copy and paste the relevant lines from your interpreter window. If you typed *literally* "hello world", complete with quotation marks, you shouldn't have got a SyntaxError, so I'm guessing you didn't do this: py> "hello world" 'hello world' But if you left out the quotation marks, you would have: py> hello world File "", line 1 hello world ^ SyntaxError: invalid syntax Notice the almost-blank line above the SyntaxError? See the ^ caret? That shows you where Python thinks the error is. Unfortunately the Python parser is a bit dumb, and often doesn't detect the error until the end of the offending text, rather than the beginning. But in this case, it doesn't matter: the offending term is "world" (no quotation marks) since you cannot separate what looks like two variables with just a space. `"hello"` inside quotation marks is a string, `hello` on its own without quotation marks is a variable. If you leave the quotation marks out, then Python parses your text as: (variable hello) (variable world) which is illegal syntax. Have I guessed you problem correctly? If not, you'll have to show us exactly what you did. In the meantime, here's my second guess: you tried to *print* "hello world", and you did this: print "hello world" In this case, are you using Python 3? In Python 2, print is a statement, and can be given as shown above, but that was deemed to be a mistake for various reasons, and in Python 3 it was changed to a regular function that requires round brackets (or parentheses for American readers): print("hello world") Does this help? -- Steven From jmz at kontrol.kode5.net Sat Sep 7 09:09:25 2013 From: jmz at kontrol.kode5.net (James Griffin) Date: Sat, 7 Sep 2013 08:09:25 +0100 Subject: [Tutor] why do i keep getting syntax errors in python when this runs In-Reply-To: References: Message-ID: <20130907070925.GB28234@kontrol.kode5.net> !-- On Fri 6.Sep'13 at 5:27:23 BST, mike johnson (pretorian at hotmail.com), wrote: > can you please help me figure out why this isnt working thanks > # convert.py > # this program is used to convert Celsius temps to Fahrenheit > # By: James Michael Johnson > > Def main (): > Celsius = float (input ("What is the Celsius temperature? ")) > Fahrenheit = 9.0 / 5.0 * Celsius + 32 > Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") > > > Main () [ ...] > # convert.py > # this program is used to convert Celsius temps to Fahrenheit > # By: James Michael Johnson > > Def main (): > Celsius = float (input ("What is the Celsius temperature? ")) > Fahrenheit = 9.0 / 5.0 * Celsius + 32 > Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") > > > Main () I'm sure this is homework. I had a peice of homework in my first year Undergrad exactly like this. -- James Griffin: jmz at kontrol.kode5.net A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 From JATINSHR001 at e.ntu.edu.sg Sat Sep 7 09:18:41 2013 From: JATINSHR001 at e.ntu.edu.sg (#PATHANGI JANARDHANAN JATINSHRAVAN#) Date: Sat, 7 Sep 2013 07:18:41 +0000 Subject: [Tutor] Is Python a scripting language Message-ID: <52B2907AE37EB94B8690A0B45EE20918CB0500@HKNPRD0111MB386.apcprd01.prod.exchangelabs.com> Hi all, I just wanted to know what exactly are scripting language used for and if python is one such language. Can it be used in place of say, PHP? I'm asking because I have a project in my 1st sem to design a website using PHP and since I already know a good deal of python and nothing of PHP, I was wondering if I could use python instead. Thanks Jatin P.S I'm the guy who started the project euler conversation with the question :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 7 10:13:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 07 Sep 2013 09:13:18 +0100 Subject: [Tutor] Is Python a scripting language In-Reply-To: <52B2907AE37EB94B8690A0B45EE20918CB0500@HKNPRD0111MB386.apcprd01.prod.exchangelabs.com> References: <52B2907AE37EB94B8690A0B45EE20918CB0500@HKNPRD0111MB386.apcprd01.prod.exchangelabs.com> Message-ID: On 07/09/13 08:18, #PATHANGI JANARDHANAN JATINSHRAVAN# wrote: > I just wanted to know what exactly are scripting language used for Your best bet is to read what wikipedia has to say on the subject. The whole question of "scripting languages" has become clouded in recent times and the definition is open to some interpretation. > and if python is one such language. Python can be used as a scripting language but in my personal definition of the term Python is more than a scripting language it is a purpose programming language which happens to be interpreted rather than compiled. (and even that is only partly true). > Can it be used in place of say, PHP? Yes. > I'm asking because I have a project in my 1st sem to design a website > using PHP and since I already know a good deal of python and nothing of > PHP, I was wondering if I could use python instead. If the class is in PHP then no, you will likely fail if you use a different language from that assigned. If the class is in web design then yes, you probably can, but you will need to pick a suitable web framework (and Python has many). Something like Pylons or CherryPy are candidates. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From petluke at gmail.com Sat Sep 7 10:34:09 2013 From: petluke at gmail.com (Luke Pettit) Date: Sat, 7 Sep 2013 18:34:09 +1000 Subject: [Tutor] why do i keep getting syntax errors in python when this runs In-Reply-To: <20130907070925.GB28234@kontrol.kode5.net> References: <20130907070925.GB28234@kontrol.kode5.net> Message-ID: def main (): Celsius = float (input ("What is the Celsius temperature? ")) Fahrenheit = 9.0 / 5.0 * Celsius + 32 print("The temperature is ", Fahrenheit, " degrees Fahrenheit.") main() You need to check your capitalisation on all the basic things for a start # def main() Def? # then you call it with Main()? On 7 September 2013 17:09, James Griffin wrote: > !-- On Fri 6.Sep'13 at 5:27:23 BST, mike johnson (pretorian at hotmail.com), > wrote: > > can you please help me figure out why this isnt working thanks > > # convert.py > > # this program is used to convert Celsius temps to Fahrenheit > > # By: James Michael Johnson > > > > Def main (): > > Celsius = float (input ("What is the Celsius temperature? ")) > > Fahrenheit = 9.0 / 5.0 * Celsius + 32 > > Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") > > > > > > Main () > > [ ...] > > > # convert.py > > # this program is used to convert Celsius temps to Fahrenheit > > # By: James Michael Johnson > > > > Def main (): > > Celsius = float (input ("What is the Celsius temperature? ")) > > Fahrenheit = 9.0 / 5.0 * Celsius + 32 > > Print ("The temperature is ", Fahrenheit, " degrees Fahrenheit.") > > > > > > Main () > > I'm sure this is homework. I had a peice of homework in my first year > Undergrad exactly like this. > > -- > > > James Griffin: jmz at kontrol.kode5.net > > A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Luke Pettit ,,, ^..^,,, http://lukepettit-3d.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 7 13:59:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 07 Sep 2013 12:59:04 +0100 Subject: [Tutor] Is Python a scripting language In-Reply-To: References: <52B2907AE37EB94B8690A0B45EE20918CB0500@HKNPRD0111MB386.apcprd01.prod.exchangelabs.com> Message-ID: On 07/09/13 09:13, Alan Gauld wrote: > of the term Python is more than a scripting language > it is a purpose programming language ... Oops, that should be *general purpose*.... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Sat Sep 7 21:45:02 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 7 Sep 2013 12:45:02 -0700 (PDT) Subject: [Tutor] Polymorphic function in Python 2 & 3? Message-ID: <1378583102.35441.YahooMailNeo@web163805.mail.gq1.yahoo.com> Hi, I have a class and I want it's initializer to be able to take both byte strings (python 3: byte objects) and unicode strings (python 3: strings). So it's foward compatible Python 2 code (or backward compatible Python 3 code, if you like). If needed, the arguments of __init__ are converted into bytes using a function called encode(). I pasted the code that I wrote here: http://pastebin.com/2WBQ0H87. Sorry if it's a little long. It works for Python 2.7 and 3.3. But is this the best way to do this? In particular, is inspect.getargs the best way to get the argument names? (I don't want to use **kwargs). Also, I am using setattr to set the parameters, so the encode() method has side effects, which may not be desirable. I need bytes because I am working with binary data. Thank you in advance! ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From davea at davea.name Sat Sep 7 23:11:25 2013 From: davea at davea.name (Dave Angel) Date: Sat, 7 Sep 2013 21:11:25 +0000 (UTC) Subject: [Tutor] Polymorphic function in Python 2 & 3? References: <1378583102.35441.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: On 7/9/2013 15:45, Albert-Jan Roskam wrote: > Hi, > > I have a class and I want it's initializer to be able to take both byte strings (python 3: byte objects) and unicode strings (python 3: strings). So it's foward compatible Python 2 code (or backward compatible Python 3 code, if you like). If needed, the arguments of __init__ are converted into bytes using a function called encode(). I pasted the code that I wrote here: http://pastebin.com/2WBQ0H87. Sorry if it's a little long. It works for Python 2.7 and 3.3. But is this the best way to do this? In particular, is inspect.getargs the best way to get the argument names? (I don't want to use **kwargs). Also, I am using setattr to set the parameters, so the encode() method has side effects, which may not be desirable. I need bytes because I am working with binary data. > Seems to me you went way around the barn, just to avoid the **kwargs (and *args) construct. Is this an assignment where the teacher specified extra constraints, or is it a self-challenge, or are you just trying to learn more about introspection? Perhaps you were trying to make sure the caller never uses any keyword arguments other than those 5? Your sample top-level call never uses keyword arguments at all, so if that was your goal, you could have used *args, instead of kwargs. At the same time, you allow several specific types of data in each argument. You don't permit list of dicts, or dict of dict of dict, or many other variants that could have been done. So it's not as general as it might have been, with a little more work. You give no indication how the user of this library would use the data stored in the object. But presently he has to use the names a, b, ... instead of the more natural numeric subscripting if you had just accepted a *args. And finally, you say that your data is binary. But valid utf-8 byte strings are a tiny subset of possible binary byte strings. So if some data is being converted from unicode strings using utf-8, and other data is binary byte strings, it seems the result might be confusing and error prone. If I were mixing binary byte strings and encoded unicode strings, I'd want to store flags with each. And what better way to do that than just not to convert from unicode at all. The strict typing of Python handles it nicely. Presumably you have some real goal which makes all these points moot. -- DaveA From byron.ruffin at g.austincc.edu Sun Sep 8 00:02:15 2013 From: byron.ruffin at g.austincc.edu (Byron Ruffin) Date: Sat, 7 Sep 2013 17:02:15 -0500 Subject: [Tutor] cs student needs help import math Message-ID: I am writing a simple program based off an ipo chart that I did correctly. I need to use ceil but I keep getting an error saying ceil is not defined. I did import math, I think. I am using 3.2.3 and I imported this way... >>> import math >>> math.pi 3.141592653589793 >>> math.ceil(math.pi) 4 >>> math.floor(math.pi) 3 ... but I get the error when using ceil... pepsticks = ceil(peplength / StickLength) Traceback (most recent call last): File "", line 1, in pepsticks = ceil(peplength / StickLength) NameError: name 'ceil' is not defined Thanks for the help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at chrisdown.name Sun Sep 8 02:16:15 2013 From: chris at chrisdown.name (Chris Down) Date: Sun, 8 Sep 2013 02:16:15 +0200 Subject: [Tutor] cs student needs help import math In-Reply-To: References: Message-ID: <20130908001613.GB23259@chrisdown.name> On 2013-09-07 17:02, Byron Ruffin wrote: > I am writing a simple program based off an ipo chart that I did correctly. > I need to use ceil but I keep getting an error saying ceil is not defined. > I did import math, I think. I am using 3.2.3 and I imported this way... > > >>> import math > >>> math.pi > 3.141592653589793 > >>> math.ceil(math.pi) > 4 > >>> math.floor(math.pi) > 3 > > ... but I get the error when using ceil... > > pepsticks = ceil(peplength / StickLength) > Traceback (most recent call last): > File "", line 1, in > pepsticks = ceil(peplength / StickLength) > NameError: name 'ceil' is not defined The error message is pretty clear, "ceil" is not defined. If you started by using "import math", this is expected, because you need to explicitly call "math.ceil", not just "ceil". If you want to import ceil into your current namespace, you need to use "from": >>> from math import ceil >>> ceil(3.14) 4 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From amitsaha.in at gmail.com Sun Sep 8 02:16:10 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 8 Sep 2013 10:16:10 +1000 Subject: [Tutor] cs student needs help import math In-Reply-To: References: Message-ID: On Sun, Sep 8, 2013 at 8:02 AM, Byron Ruffin wrote: > I am writing a simple program based off an ipo chart that I did correctly. > I need to use ceil but I keep getting an error saying ceil is not defined. > I did import math, I think. I am using 3.2.3 and I imported this way... > >>>> import math >>>> math.pi > 3.141592653589793 >>>> math.ceil(math.pi) > 4 >>>> math.floor(math.pi) > 3 > > ... but I get the error when using ceil... > > pepsticks = ceil(peplength / StickLength) > Traceback (most recent call last): > File "", line 1, in > pepsticks = ceil(peplength / StickLength) > NameError: name 'ceil' is not defined So, like you see earlier, you used math.ceil() to refer to the ceil() function. That is how you refer to a function defined in a module. If you want to refer to it as ceil(), you have to import it like so: from math import ceil Best, Amit. -- http://echorand.me From dfjennings at gmail.com Sun Sep 8 02:12:01 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 7 Sep 2013 20:12:01 -0400 Subject: [Tutor] cs student needs help import math In-Reply-To: References: Message-ID: On Sep 7, 2013, at 6:02 PM, Byron Ruffin wrote: > > >>> math.ceil(math.pi) > 4 > ... but I get the error when using ceil... > > pepsticks = ceil(peplength / StickLength) > Traceback (most recent call last): > File "", line 1, in > pepsticks = ceil(peplength / StickLength) > NameError: name 'ceil' is not defined Look carefully again at that error. Basically, it's telling you that 'ceil' is not the same as 'math.ceil' which is how you used it correctly the first time. That's an easy mistake to make. Take care, Don From steve at pearwood.info Sun Sep 8 05:28:58 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 8 Sep 2013 13:28:58 +1000 Subject: [Tutor] Polymorphic function in Python 2 & 3? In-Reply-To: <1378583102.35441.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1378583102.35441.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <20130908032858.GE26319@ando> On Sat, Sep 07, 2013 at 12:45:02PM -0700, Albert-Jan Roskam wrote: > Hi, > > I have a class and I want it's initializer to be able to take both > byte strings (python 3: byte objects) and unicode strings (python 3: > strings). [...] I need bytes because I am > working with binary data. Consider only accepting binary data. It is not very difficult for the caller to explicitly convert their text strings into binary data ahead of time, and besides, "convert text to binary" is ambiguous. As the Zen of Python says, resist the temptation to guess. Consider the *text* string "abcdef". Which of the following binary data (shown in hex) does it represent? Six values, limited between 0 and FF? 1) 61 62 63 64 65 66 2) 81 82 83 84 85 86 # Hint: IBM mainframe users might expect this. Six values, limited between 0 and FFFF? 3) 6100 6200 6300 6400 6500 6600 4) 0061 0062 0063 0064 0065 0066 Twelve values between 0 and FF? 5) 61 00 62 00 63 00 64 00 65 00 66 00 6) 00 61 00 62 00 63 00 64 00 65 00 66 Three values between 0 and FF? 7) AB CD EF Something else? 8) ValueError: expected decimal digits but got "abcdef" Even assuming that you are expecting single byte data, not double bytes, there are still six legitimate ways to convert this string. It seems risky to assume that if the caller passes you "???" they actually meant E2 96 BC E2 96 A1 E2 96 A0. If I were designing this, I'd probably take the rule: - byte strings are accepted by numeric value, e.g. b'a' -> hex 61 - text strings are expected to be pairs of hex digits, e.g. u'a' is an error, u'abcdef' -> hex AB, CD EF, u'hello' is an error. That seems more useful to me than UTF-8. > So it's foward compatible Python 2 code (or backward > compatible Python 3 code, if you like). If needed, the arguments of > __init__ are converted into bytes using a function called encode(). I > pasted the code that I wrote here: http://pastebin.com/2WBQ0H87. Sorry > if it's a little long. It works for Python 2.7 and 3.3. But is this > the best way to do this? In particular, is inspect.getargs the best > way to get the argument names? (I don't want to use **kwargs). Also, I > am using setattr to set the parameters, so the encode() method has > side effects, which may not be desirable. Some questions/observations: * Why do you bother setting attributes a, b, ... e only to then set them again in the encode method? * It isn't clear to me what the encode method is supposed to do, which suggests it is trying to do too much. The doc string says: Params can be bytes, str, unicode, dict, dict of dics, list of str/bytes/unicode but it isn't clear what will happen if you pass these different values to encode. For instance, if params = {1: None, 2: None}, what do you expect to happen? How about {None: 42} or ['a']? My *guess* is that it is actually expecting a list of (attribute name, string value) pairs, that at least is how you seem to be using it, but that documentation gives me no help here. I think a much better approach would be to use a helper function: def to_bytes(string): if isinstance(string, unicode): return string.encode('uft-8') # But see above, why UTF-8? elif isinstance(string, bytes): return string raise TypeError class Test: def __init__(self, a, b, *args): self.a = to_bytes(a) try: self.b = to_bytes(b) except TypeError: self.b = None self.extras = [to_bytes(s) for s in args] Short, sweet, easy to understand, efficient, requires no self-inspection magic, doesn't try to guess the caller's intention, easily useable without worrying about side-effects, which means it is easy to test. Some other observations... I dislike the fact that on UnicodeDecodeError you assume that the dodgy bytes given must be encoded in the default encoding: except UnicodeDecodeError: # str, python 2 cp = locale.getdefaultlocale()[-1].lower() if cp != "utf-8": return arg.decode(cp).encode("utf-8") return arg I think the whole approach is complicated, convoluted and quite frankly nasty (you have no comments explaining the logic of why you catch some exceptions and why you do what you) but if you're going to use the default locale this is how you ought to do it IMO: lang, encoding = locale.getdefaultlocale() if encoding is None: # no default locale, or can't determine it # what the hell do we guess now??? else: try: unistr = arg.decode(encoding) except UnicodeDecodeError: # And again, what guess do we make now??? else: return unistr.encode('utf-8') # Why UTF-8? but as already mentioned, I think that being less "Do What I Mean" and more "be explicit about what you want" is a better idea. As far as your 2/3 compatibility code at the top of the module: try: unichr except NameError: unichr = chr # python 3 try: unicode except NameError: unicode = basestring = str # python 3 I don't believe you use either unichr or basestring, so why bother with them? I normally do something like this: try: unicode except NameError: # Python 3 unicode = str which I think is all you need. Also, rather than building all the 2-and-3 logic into _bytify, I think it is better to split it into two functions: def _bytify2(s): ... def _bytify2(s): ... if sys.version() < '3': _bytify = _bytify2 else: _bytify = _bytify3 which makes it much easier to understand the code, and much easier to drop support for version 2 eventually. -- Steven From kimberly.mansfield at g.austincc.edu Sun Sep 8 21:43:54 2013 From: kimberly.mansfield at g.austincc.edu (Kimberly Mansfield) Date: Sun, 8 Sep 2013 14:43:54 -0500 Subject: [Tutor] Won't run. Syntax Error. Message-ID: This is the first homework assignment. Driving me crazy - struggling with it for two entire days. I want to drop this class now. I think it is all entered correctly, but it won't run and teacher will not accept it if it won't run. Says "syntax error" and highlights one of the numbers in the top line that was there when I first opened it, before I typed anything. Specifically, this: Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 The middle 3 (in red) is highlighted. There is no arrow pointing to it or anything else. We are supposed to write something to help a pizza parlor owner figure out how many pepperoni sticks he will need for the month. The teacher gave us an IPO chart with these definitions and we are supposed to write the code for it in Python. I used floats throughout because this is the umpteenth time I have rewritten this thing, and was thinking maybe it was because I used integers as well as floats before, and thought maybe the problem was because I used both. I will post it below in case you need to see the whole thing. Obviously, I have no programming background and this is supposed to be a beginner's class. Please help. I am running out of hair to yank out of my head and my dogs are afraid of me now. Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> Pizzas = float (input ("Number of Pizzas ")) Number of Pizzas 100 >>> Length = float (input ("Length of Pizzas ")) Length of Pizzas 11 >>> Width = float (input ("Width of Pizzas ")) Width of Pizzas 11 >>> Thickness = float (input ("Thickness of Pepperoni Slices ")) Thickness of Pepperoni Slices .1 >>> Diameter = float (input ("Diameter of Pepperoni Slices ")) Diameter of Pepperoni Slices 1 >>> Edge = float (input ("Crust Edge of Pizzas ")) Crust Edge of Pizzas .5 >>> StickLength = float (input ("Length of Pepperoni Sticks ")) Length of Pepperoni Sticks 10 >>> UsefulLength = Length - 2 * Edge >>> SlicesLength = UsefulLength / Diameter >>> UsefulWidth = Width - 2 * Edge >>> SlicesWidth = UsefulWidth / Diameter >>> Slices = SlicesWidth * SlicesLength >>> TotalSlices = Slices * Pizzas >>> HypoLength = TotalSlices * Thickness >>> PepperoniSticks = HypoLength / StickLength >>> print (StickLength) 10.0 >>> print ("You will need", PepperoniSticks, "pepperoni sticks this month.") You will need 100.0 pepperoni sticks this month. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jslozier at gmail.com Sun Sep 8 22:35:30 2013 From: jslozier at gmail.com (Jay Lozier) Date: Sun, 08 Sep 2013 16:35:30 -0400 Subject: [Tutor] Won't run. Syntax Error. In-Reply-To: References: Message-ID: <1378672530.5920.5.camel@linux-3jah.site> -----Original Message----- From: Kimberly Mansfield To: tutor at python.org Subject: [Tutor] Won't run. Syntax Error. Date: Sun, 8 Sep 2013 14:43:54 -0500 This is the first homework assignment. Driving me crazy - struggling with it for two entire days. I want to drop this class now. I think it is all entered correctly, but it won't run and teacher will not accept it if it won't run. Says "syntax error" and highlights one of the numbers in the top line that was there when I first opened it, before I typed anything. Specifically, this: Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 The middle 3 (in red) is highlighted. There is no arrow pointing to it or anything else. We are supposed to write something to help a pizza parlor owner figure out how many pepperoni sticks he will need for the month. The teacher gave us an IPO chart with these definitions and we are supposed to write the code for it in Python. I used floats throughout because this is the umpteenth time I have rewritten this thing, and was thinking maybe it was because I used integers as well as floats before, and thought maybe the problem was because I used both. I will post it below in case you need to see the whole thing. Obviously, I have no programming background and this is supposed to be a beginner's class. Please help. I am running out of hair to yank out of my head and my dogs are afraid of me now. Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> Pizzas = float (input ("Number of Pizzas ")) Number of Pizzas 100 >>> Length = float (input ("Length of Pizzas ")) Length of Pizzas 11 >>> Width = float (input ("Width of Pizzas ")) Width of Pizzas 11 >>> Thickness = float (input ("Thickness of Pepperoni Slices ")) Thickness of Pepperoni Slices .1 >>> Diameter = float (input ("Diameter of Pepperoni Slices ")) Diameter of Pepperoni Slices 1 >>> Edge = float (input ("Crust Edge of Pizzas ")) Crust Edge of Pizzas .5 >>> StickLength = float (input ("Length of Pepperoni Sticks ")) Length of Pepperoni Sticks 10 >>> UsefulLength = Length - 2 * Edge >>> SlicesLength = UsefulLength / Diameter >>> UsefulWidth = Width - 2 * Edge >>> SlicesWidth = UsefulWidth / Diameter >>> Slices = SlicesWidth * SlicesLength >>> TotalSlices = Slices * Pizzas >>> HypoLength = TotalSlices * Thickness >>> PepperoniSticks = HypoLength / StickLength >>> print (StickLength) 10.0 >>> print ("You will need", PepperoniSticks, "pepperoni sticks this month.") You will need 100.0 pepperoni sticks this month. Kimberly, Your output indicates the code runs correctly as written. There are no error messages. I was able to run the code without any errors. I copied and pasted the code into a text editor (Notepad on Windows or idle3) and removed the extraneous prompts, echoed output, and spaces. When saving the file the extension should be *.py.as in pizza.py -- Jay Lozier jslozier at gmail.com From davea at davea.name Sun Sep 8 23:17:09 2013 From: davea at davea.name (Dave Angel) Date: Sun, 8 Sep 2013 21:17:09 +0000 (UTC) Subject: [Tutor] Won't run. Syntax Error. References: Message-ID: On 8/9/2013 15:43, Kimberly Mansfield wrote: > This is the first homework assignment. Driving me crazy - struggling with > it for two entire days. I want to drop this class now. > > I think it is all entered correctly, but it won't run and teacher will not > accept it if it won't run. Says "syntax error" and highlights one of the > numbers in the top line that was there when I first opened it, before I > typed anything. Specifically, this: > Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 > bit (Intel)] on win32 But that line should NOT be in your source file. That's the prompt the interpreter displays. > The middle 3 (in red) is highlighted. There is no arrow pointing to it or > anything else. We are supposed to write something to help a pizza parlor > owner figure out how many pepperoni sticks he will need for the month. The > teacher gave us an IPO chart with these definitions and we are supposed to > write the code for it in Python. I used floats throughout because this is > the umpteenth time I have rewritten this thing, and was thinking maybe it > was because I used integers as well as floats before, and thought maybe the > problem was because I used both. > I will post it below in case you need to see the whole thing. > Obviously, I have no programming background and this is supposed to be a > beginner's class. > Please help. I am running out of hair to yank out of my head and my dogs > are afraid of me now. > > Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 > bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. Why are you typing all this into the interpreter? >>>> Pizzas = float (input ("Number of Pizzas ")) > Number of Pizzas 100 >>>> Length = float (input ("Length of Pizzas ")) > Length of Pizzas 11 >>>> Width = float (input ("Width of Pizzas ")) > Width of Pizzas 11 >>>> Thickness = float (input ("Thickness of Pepperoni Slices ")) > Thickness of Pepperoni Slices .1 >>>> Diameter = float (input ("Diameter of Pepperoni Slices ")) > Diameter of Pepperoni Slices 1 >>>> Edge = float (input ("Crust Edge of Pizzas ")) > Crust Edge of Pizzas .5 >>>> StickLength = float (input ("Length of Pepperoni Sticks ")) > Length of Pepperoni Sticks 10 >>>> UsefulLength = Length - 2 * Edge >>>> SlicesLength = UsefulLength / Diameter >>>> UsefulWidth = Width - 2 * Edge >>>> SlicesWidth = UsefulWidth / Diameter >>>> Slices = SlicesWidth * SlicesLength >>>> TotalSlices = Slices * Pizzas >>>> HypoLength = TotalSlices * Thickness >>>> PepperoniSticks = HypoLength / StickLength >>>> print (StickLength) > 10.0 >>>> print ("You will need", PepperoniSticks, "pepperoni sticks this month.") > You will need 100.0 pepperoni sticks this month. > Have you got a text editor? (Even Notepad is good enough for a case like this) Nobody should write a program of this size directly in the interpreter. You certainly don't want to be retyping the whole thing when there's one typo. Start simple. Create a text file called simple.py, and consisting of one line: print("Hello world") Now run that file, by typing python simple.py If that works for you, you've got a clue how to write a longer program. -- DaveA From cybervigilante at gmail.com Sun Sep 8 23:18:14 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 8 Sep 2013 14:18:14 -0700 Subject: [Tutor] Won't run. Syntax Error. In-Reply-To: <1378672530.5920.5.camel@linux-3jah.site> References: <1378672530.5920.5.camel@linux-3jah.site> Message-ID: > From: Kimberly Mansfield > This is the first homework assignment. Driving me crazy - struggling > with it for two entire days. I want to drop this class now. Does the Python interpreter run with even a simple program such as print('hello') ? If it doesn't run that, it may be a windows or installation problem, so try running the program from a different computer that has python installed. Also, copy and post the exact Error Message here, rather than describing it. You should get a little bit more than "Syntax Error" - like this: >>> prent('hello') Traceback (most recent call last): File "", line 1, in NameError: name 'prent' is not defined Jim From alan.gauld at btinternet.com Mon Sep 9 01:16:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 09 Sep 2013 00:16:28 +0100 Subject: [Tutor] Won't run. Syntax Error. In-Reply-To: References: Message-ID: On 08/09/13 20:43, Kimberly Mansfield wrote: > This is the first homework assignment. Driving me crazy - struggling > with it for two entire days. I want to drop this class now. > Hi, welcome to tutor. Can you explain exactly how you are running the program because it looks below like there are twi distinct things going on. > I think it is all entered correctly, but it won't run and teacher will > not accept it if it won't run. Says "syntax error" and highlights one of > the numbers in the top line that was there when I first opened it, > before I typed anything. Specifically, this: > Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 > bit (Intel)] on win32 > The middle 3 (in red) is highlighted. There is no arrow pointing to it > or anything else. This looks like you have copied a Python interpreter interactive session into a text file and tried to run it as a script. Is that what you did? If so, that's the problem. You need to separate out what the interpreter displayed (its output) from what the interpreter read(its input). The interpreters input is all you should have in your program. > month. The teacher gave us an IPO chart with these definitions and we > are supposed to write the code for it in Python. Wow, that's quite an advanced first class! I didn't see IPO diagrams till my third year at Uni! And then never used them again until I started using 6 Sigma as a business analyst at work many years later... (And even then usually in the context of SIPOC charts...) > Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 > bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > >>> Pizzas = float (input ("Number of Pizzas ")) > Number of Pizzas 100 > >>> Length = float (input ("Length of Pizzas ")) > Length of Pizzas 11 > >>> Width = float (input ("Width of Pizzas ")) > Width of Pizzas 11 > >>> Thickness = float (input ("Thickness of Pepperoni Slices ")) > Thickness of Pepperoni Slices .1 > >>> Diameter = float (input ("Diameter of Pepperoni Slices ")) > Diameter of Pepperoni Slices 1 > >>> Edge = float (input ("Crust Edge of Pizzas ")) > Crust Edge of Pizzas .5 > >>> StickLength = float (input ("Length of Pepperoni Sticks ")) > Length of Pepperoni Sticks 10 > >>> UsefulLength = Length - 2 * Edge > >>> SlicesLength = UsefulLength / Diameter > >>> UsefulWidth = Width - 2 * Edge > >>> SlicesWidth = UsefulWidth / Diameter > >>> Slices = SlicesWidth * SlicesLength > >>> TotalSlices = Slices * Pizzas > >>> HypoLength = TotalSlices * Thickness > >>> PepperoniSticks = HypoLength / StickLength > >>> print (StickLength) > 10.0 > >>> print ("You will need", PepperoniSticks, "pepperoni sticks this > month.") > You will need 100.0 pepperoni sticks this month. Down to here it looks like a perfectly successful interactive session. Converting that to a script that you can run directly it looks like: Pizzas = float (input ("Number of Pizzas ")) Length = float (input ("Length of Pizzas ")) Width = float (input ("Width of Pizzas ")) Thickness = float (input ("Thickness of Pepperoni Slices ")) Diameter = float (input ("Diameter of Pepperoni Slices ")) Edge = float (input ("Crust Edge of Pizzas ")) StickLength = float (input ("Length of Pepperoni Sticks ")) UsefulLength = Length - 2 * Edge SlicesLength = UsefulLength / Diameter UsefulWidth = Width - 2 * Edge SlicesWidth = UsefulWidth / Diameter Slices = SlicesWidth * SlicesLength TotalSlices = Slices * Pizzas HypoLength = TotalSlices * Thickness PepperoniSticks = HypoLength / StickLength print (StickLength) print ("You will need", PepperoniSticks, "pepperoni sticks this month.") And the output when you run it is: Number of Pizzas 100 Length of Pizzas 11 Width of Pizzas 11 Thickness of Pepperoni Slices .1 Diameter of Pepperoni Slices 1 Crust Edge of Pizzas .5 Length of Pepperoni Sticks 10 10.0 You will need 100.0 pepperoni sticks this month. So it looks like it all works. We could critique the style and design but the basic code works. I suspect your probl;em is that you are trying to save or cut 'n paste an interpreter session directly into a python script and that just won't work. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From noponus at yahoo.com Sun Sep 8 22:00:33 2013 From: noponus at yahoo.com (olatunde Adebayo) Date: Sun, 8 Sep 2013 13:00:33 -0700 (PDT) Subject: [Tutor] Where do I start learning Python Message-ID: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> hey everyone, I am taking a graduate level class this fall that required python programming. can anyone direct me to where can i get a free python training crash course / program anyone with idea. I have one week to learn..is it possible.... thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Sep 9 11:41:19 2013 From: wprins at gmail.com (Walter Prins) Date: Mon, 9 Sep 2013 10:41:19 +0100 Subject: [Tutor] Where do I start learning Python In-Reply-To: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> References: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> Message-ID: Hi, On 8 September 2013 21:00, olatunde Adebayo wrote: > hey everyone, > I am taking a graduate level class this fall that required python > programming. > can anyone direct me to where can i get a free python training crash > course / program > anyone with idea. > I have one week to learn..is it possible.... > Have you got any prior programming experience? The basics of Python is fairly easy to learn, but if you've got zero previous programming experience then it might be a challenge to get up to speed with only 1 week available. Either way, here's some useful references/links for you: http://marakana.com/techtv/python-fundamentals-screencast-tutorials.html http://www.youtube.com/playlist?list=PLF39DBF75ED758CF8 https://www.khanacademy.org/science/computer-science http://pyvideo.org/video/287/pycon-2010--python-101 http://nedbatchelder.com/text/iter.html http://pyvideo.org/video/1758/loop-like-a-native-while-for-iterators-genera http://openbookproject.net/thinkcs/python/english3e/ http://www.greenteapress.com/thinkpython/ http://learnpythonthehardway.org/book/intro.html http://www.diveintopython.net/ Good luck! Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 9 11:43:16 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 09 Sep 2013 10:43:16 +0100 Subject: [Tutor] Where do I start learning Python In-Reply-To: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> References: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> Message-ID: On 08/09/13 21:00, olatunde Adebayo wrote: > can anyone direct me to where can i get a free python training crash > course / program anyone with idea. > I have one week to learn..is it possible.... It depends on your previous experience but the official tutorial on the python.org website is a good place to start if you have programmed before in another language. You can easily learn the basics of python in a day. If you are a beginner to programming as well as python then you need to start with one of the non-programmers tutorials listed on the site. Which one is best will be very subjective. You need to try a few and see if they work for your style. Whichever route you choose feel free to ask questions here if you get stuck. Please tell us Which tutorial, Which python version you use Which OS Show us your code and include the full error message not just a summary. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From andrew.vanvalkenburg at gmail.com Mon Sep 9 13:06:16 2013 From: andrew.vanvalkenburg at gmail.com (Andrew Van Valkenburg) Date: Mon, 9 Sep 2013 07:06:16 -0400 Subject: [Tutor] Where do I start learning Python In-Reply-To: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> References: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> Message-ID: codecademy.com has a pretty good tutorial imo On Sun, Sep 8, 2013 at 4:00 PM, olatunde Adebayo wrote: > hey everyone, > I am taking a graduate level class this fall that required python > programming. > can anyone direct me to where can i get a free python training crash > course / program > anyone with idea. > I have one week to learn..is it possible.... > > > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jugurtha.hadjar at gmail.com Mon Sep 9 21:02:13 2013 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Mon, 09 Sep 2013 20:02:13 +0100 Subject: [Tutor] Where do I start learning Python In-Reply-To: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> References: <1378670433.44491.YahooMailNeo@web125603.mail.ne1.yahoo.com> Message-ID: <522E1B35.3070009@gmail.com> On 09/08/2013 09:00 PM, olatunde Adebayo wrote: > hey everyone, > I am taking a graduate level class this fall that required python > programming. > can anyone direct me to where can i get a free python training crash > course / program > anyone with idea. > I have one week to learn..is it possible.... You can definitely have something going on in a week for your stuff (It takes less if you have some background in programming and these things just make sense to you. You won't develop an awesome piece that solves world problems, but for what you'll probably do (lists, etc..) you'll be able to do that). There is a great one from Zed Shaw called "Learn Python The Hard Way". Basically, it gets you to actually write a lot (provided you don't cheat). It's available here: http://learnpythonthehardway.org/book/ Welcome, good luck and keep us posted on your progress, Olatunde. -- ~Jugurtha Hadjar, From thabilerampa at gmail.com Tue Sep 10 09:58:31 2013 From: thabilerampa at gmail.com (Thabile Rampa) Date: Tue, 10 Sep 2013 09:58:31 +0200 Subject: [Tutor] [Re:] I need help with the following question Message-ID: On Aug 27, 2013, at 3:40 AM, isaac Eric wrote > print "For a circle of radius %s the area is %s" % (radius,area) > Question: What is the purpose of %s ? I will admit that this is homework for me. However, this is more for my log book and not for marks. According to my understanding, the purpose of the %s is to turn the numbers, which the program has recognized as numbers, into strings, so that they fit in the print command without any syntax errors. Could you guide me in the right direction if it is completely off? *Tab Tab* -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Sep 10 11:57:27 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 10 Sep 2013 10:57:27 +0100 Subject: [Tutor] [Re:] I need help with the following question In-Reply-To: References: Message-ID: On 10 September 2013 08:58, Thabile Rampa wrote: > On Aug 27, 2013, at 3:40 AM, isaac Eric wrote > > > >> print "For a circle of radius %s the area is %s" % (radius,area) > >> Question: What is the purpose of %s ? > > I will admit that this is homework for me. However, this is more for my log > book and not for marks. > > According to my understanding, the purpose of the %s is to turn the numbers, > which the program has recognized as numbers, into strings, so that they fit > in the print command without any syntax errors. > > Could you guide me in the right direction if it is completely off? You are correct. '%s' is used to convert numbers (or other non-string things) into strings so that they can be used in places where text is required. In the particular case of the print command, this is done automatically so printing a number directly works just fine: >>> a = 123.0 >>> print a 123.0 >>> print 'The size is:', a The size is: 123.0 The '%s' form though allows you to insert the string representation of the number at the appropriate place in the string making it a bid cleaner to read e.g.: >>> radius = 4 >>> pi = 3.1412654 >>> area = pi * radius ** 2 This one: >>> print 'For a circle of radius', radius, 'the area is', area For a circle of radius 4 the area is 50.2602464 is equivalent to this one: >>> print 'For a circle of radius %s the area is %s' % (radius, area) For a circle of radius 4 the area is 50.2602464 If you just want to get the string representation of a number you can just use the str() function: >>> area 50.2602464 >>> str(area) '50.2602464' Oscar From alan.gauld at btinternet.com Tue Sep 10 12:40:35 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Sep 2013 11:40:35 +0100 Subject: [Tutor] [Re:] I need help with the following question In-Reply-To: References: Message-ID: On 10/09/13 08:58, Thabile Rampa wrote: >> print "For a circle of radius %s the area is %s" % (radius,area) > >> Question: What is the purpose of %s ? Oscar has answered your basic question but to add to his comments thee are other reasons for using the %s rather than str() or simply printing the variables directly. The %s allows us to add extra information to control the format of the string produced, for example the total field length and whether it is left or right justified. eg Try >>> "%12s" % "Hello" >>> "%-12s" % "Hello" >>> "%-12.4s" % "Hello" You can read about all the string formatting characters and their 'extras' here: http://www.python.org/doc//current/library/stdtypes.html in Section 6.6.2 Note that in Python 3 this style of string formatting is being deprecated in favour of the new format method of strings (linked on the same page above under the str.format() method) which offers even more options. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Tue Sep 10 12:48:18 2013 From: davea at davea.name (Dave Angel) Date: Tue, 10 Sep 2013 10:48:18 +0000 (UTC) Subject: [Tutor] [Re:] I need help with the following question References: Message-ID: On 10/9/2013 03:58, Thabile Rampa wrote: > >
On Aug 27, 2013, at 3:40 AM, isaac Eric wrote

<snip> > > > print "For a circle of radius %s the area is %s" % (radius,area) > <snip> > > Question: What is the purpose of %s ?
I will admit that this is homework for me. However, this is more for my log book and not for marks.

According to my understanding, the purpose of the %s is to turn the numbers,
> which the program has recognized as numbers, into strings, so that they fit in the print command without any syntax errors.

Could you guide me in the right direction if it is completely off?
>

Tab Tab
> Please post using text email, not html email. In this particular message, your text was pretty easy to extract, but in many cases the html email will become quite garbled by the time the newsreaders pick it up. Besides, it wastes space. The statement, print "For a circle of radius %s the area is %s" % (radius,area) has several areas of interest. Let's decompose it. print - the print statement, which will take whatever expressions it is handed, and convert each to a string before sending them to stdout. In this particular case, there is exactly one expression, and it already is a string. % - the formatting operator, which takes a string on the left side, and a tuple (or other interable) on the right, and combines them together to form a single string. http://docs.python.org/2/library/stdtypes.html#string-formatting-operations "For a circle of radius %s the area is %s" This string contains two %s place-holders. These are not python language syntax, but are clues to the formatting operator that you want a substitution to happen there. So there are two of them, to line up with the two items in the tuple. In this case they are both looking for strings. But %d could have been used to indicate that we want int numbers. And many other combinations could be used, depending on the type of object being used. %08d would mean take the int and left pad it with zeroes till it's 8 characters wide. If you are writing new code, the docs prefer you to use the format method of strings. in this case, the print statement might look something like: print "For a circle of radius {0} the area is {1}".format(radius, area) http://docs.python.org/2/library/stdtypes.html#str.format http://docs.python.org/2/library/string.html#formatstrings -- DaveA From ljetibo at gmail.com Tue Sep 10 17:37:28 2013 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Tue, 10 Sep 2013 17:37:28 +0200 Subject: [Tutor] I need help with the following question Message-ID: > Message: 3 > Date: Tue, 10 Sep 2013 09:58:31 +0200 > From: Thabile Rampa > To: tutor at python.org > Subject: [Tutor] [Re:] I need help with the following question > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > On Aug 27, 2013, at 3:40 AM, isaac Eric wrote > > > > print "For a circle of radius %s the area is %s" % (radius,area) > > Question: What is the purpose of %s ? > > I will admit that this is homework for me. However, this is more for my log > book and not for marks. > > According to my understanding, the purpose of the %s is to turn the numbers, > which the program has recognized as numbers, into strings, so that they fit > in the print command without any syntax errors. > > Could you guide me in the right direction if it is completely off? > > *Tab Tab* I'm not a python "brainiac" so I apologize in advance if my answer is lacking I'll try to be as thorough as possible. In the light of another recent question on here "Where do I start python" I want to point out there's been tons of linkage to places where it's rather easy to find the answer what %s %d and %r are.... One of my favs is the http://learnpythonthehardway.org/book/ and if you start from exercise 5 onwards you should get a better idea of all the print options there are in Python and how to use them efficiently. If you were inquiring SPECIFICALLY about 'formaters' (the %s,d,i,r.... look no further then basic Python manual here: http://docs.python.org/2/library/stdtypes.html#string-formatting Lucky for you the %s automatically converts any argument to string with str() which works for everything in Python, except you might not like the look of the output. Be careful to use %i or %d for integers otherwise floats will be rounded up. Printing strings when using %i will report an error. I don't think there's any difference between %d (d does NOT stand for double) and %i. If you want pretty decimals (1.1) and not floats (1.100000001) use the decimal module. Else if you were interested in all the ways you can print in python just look at the learn python link but here's the crash course anyhow. I don't think you should have any problems if you ever worked in any of the big c's before. Printing in Python 3 onwards needs parentheses around the arguments you're printing, I think for Python <3 following should work: Basically if in python you want to print string, python can automatically connect them in a sentence: >>>> print "This"+"is"+"ok" This is ok but that won't work if the print arguments are not strings i.e.: >>>> print "This"+"is"+"not" + 6 + "ok" TypeError: cannot concatenate string and integer objects and it's also silly to do that, could you imagine explicitly converting everything to string? >>>> print str(hours)+":"+str(minutes)+":"+str(seconds)) fugly! What you want to do, resembles the c and c++ printf syntax >>>>print "You can add string %s and number %d like this" %(string, number) You can add string Banana and number 5 like this Or also fine, valid only for python>=2.6, and also the way that I prefer for longer strings is the C# syntax (I think): >>>>print "Something is here: {0}".format(anything) Something is here: (any number or string) Because it avoids the necessity for declaring exactly what is it you're printing and program won't crash, or at least it avoids the need to add special try catch blocks just for printing. If you see your output is not what you want you can return and try to work out exactly what happened. Hope no serious rules were broken by answering to this question... Regards, Dino From novoshot at gmail.com Tue Sep 10 19:49:11 2013 From: novoshot at gmail.com (novo shot) Date: Tue, 10 Sep 2013 13:49:11 -0400 Subject: [Tutor] Question about Functions Message-ID: Dear tutors: The following is an example I found in the Raspberry Pi for Dummies book: #function test def theFunction(message): print "I don't get ", message return "ARRRGH!" theFunction("this") result=theFunction("this either") print "reply is: ", result --------------------------------------------- The result of this code looks like this: I don't get this I don't get this either reply is: ARRRGH! ---------------------------------------------- Here's what I don't understand: When I declare a variable to be equal as the fucntion (result=theFunction("this either")) is Python also executing the function? The way I see it, I only called for the function once before printing ARRRGH!! Then after that I declared a variable and then I print. This is how I expected the result to look like: I don't get this reply is: I don't get this either ARRRGH! ----------------------------------------- Can you help me understand? I can't move forward until I understand how Python solves this code. Thanks in advance Optional From novoshot at gmail.com Tue Sep 10 19:34:50 2013 From: novoshot at gmail.com (novo shot) Date: Tue, 10 Sep 2013 13:34:50 -0400 Subject: [Tutor] Question about Functions Message-ID: Dear tutors: The following is an example I found in the Raspberry Pi for Dummies book: #function test def theFunction(message): print "I don't get ", message return "ARRRGH!" theFunction("this") result=theFunction("this either") print "reply is: ", result --------------------------------------------- The result of this code looks like this: I don't get this I don't get this either reply is: ARRRGH! ---------------------------------------------- Here's what I don't understand: When I declare a variable to be equal as the fucntion (result=theFunction("this either")) is Python also executing the function? The way I see it, I only called for the function once before printing ARRRGH!! Then after that I declared a variable and then I print. This is how I expected the result to look like: I don't get this reply is: I don't get this either ARRRGH! ----------------------------------------- Can you help me understand? I can't move forward until I understand how Python solves this code. Thanks in advance Optional -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Sep 10 22:24:16 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 10 Sep 2013 16:24:16 -0400 Subject: [Tutor] Question about Functions In-Reply-To: References: Message-ID: On Tue, Sep 10, 2013 at 1:49 PM, novo shot wrote: > Dear tutors: > > The following is an example I found in the Raspberry Pi for Dummies book: > > #function test > > def theFunction(message): > print "I don't get ", message > return "ARRRGH!" > > theFunction("this") > the above line invokes theFunction, and prints "I don't get this". It returns "ARRRGH" but you con't assign that to a name, so it is lost. > > result=theFunction("this either") > Now you call theFunction again and it prints "I don't get this either". You save the ARRRGH bit in result > print "reply is: ", result > You print the value of result with is ARRRGH > > --------------------------------------------- > The result of this code looks like this: > > I don't get this > I don't get this either > reply is: ARRRGH! > > ---------------------------------------------- > Here's what I don't understand: > > When I declare a variable to be equal as the fucntion > (result=theFunction("this either")) is Python also executing the > function? > Yes it is > > The way I see it, I only called for the function once before printing > ARRRGH!! Then after that I declared a variable and then I print. > > You see it wrong. Each time you have theFunction(...) in your code that function is run > This is how I expected the result to look like: > > I don't get this > reply is: I don't get this either > ARRRGH! > > ----------------------------------------- > > Can you help me understand? I can't move forward until I understand > how Python solves this code. > > Thanks in advance > Optional > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at chrisdown.name Tue Sep 10 22:25:41 2013 From: chris at chrisdown.name (Chris Down) Date: Tue, 10 Sep 2013 22:25:41 +0200 Subject: [Tutor] Question about Functions In-Reply-To: References: Message-ID: <20130910202540.GB6116@chrisdown.name> On 2013-09-10 13:34, novo shot wrote: > When I declare a variable to be equal as the fucntion > (result=theFunction("this either")) is Python also executing the function? You're not declaring it as equal, that would be `==' (or `is' for identity). `=' assigns, it doesn't check for equality. > The way I see it, I only called for the function once before printing > ARRRGH!! Then after that I declared a variable and then I print. > > This is how I expected the result to look like: > > I don't get this > reply is: I don't get this either > ARRRGH! Why do you expect "reply is" to happen on the second line? It clearly only happens when printing the returned value, not when printing from inside the function itself: > def theFunction(message): > print "I don't get ", message > return "ARRRGH!" > > theFunction("this") > > result=theFunction("this either") > print "reply is: ", result The extra spaces are because "," implies one. If you don't want a double space before the message, remove the trailing space in the string. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From ramit.prasad at jpmorgan.com.dmarc.invalid Tue Sep 10 22:33:06 2013 From: ramit.prasad at jpmorgan.com.dmarc.invalid (Prasad, Ramit) Date: Tue, 10 Sep 2013 20:33:06 +0000 Subject: [Tutor] Question about Functions In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474186D18FC@SCACMX008.exchad.jpmchase.net> novo shot wrote: > Dear tutors: > > The following is an example I found in the Raspberry Pi for Dummies book: > > #function test > > def theFunction(message): > print "I don't get ", message > return "ARRRGH!" > > theFunction("this") > > result=theFunction("this either") > print "reply is: ", result > > --------------------------------------------- > The result of this code looks like this: > > I don't get this > I don't get this either > reply is: ARRRGH! > > ---------------------------------------------- > Here's what I don't understand: > > When I declare a variable to be equal as the fucntion > (result=theFunction("this either")) is Python also executing the > function? Yes, when you do function() it calls the function. In this case it is calling theFunction with the string arguments 'this' and 'this either', respectively. > The way I see it, I only called for the function once before printing > ARRRGH!! Then after that I declared a variable and then I print. > > This is how I expected the result to look like: > > I don't get this > reply is: I don't get this either > ARRRGH! You do not get this output because you do not return the string with the `message`, you print it immediately and return "ARRRGH!". "ARRRGH!" then gets bound to the name `result` which you then print. If you want the result you specify you should return "reply is: " + result # where result must be a string Not sure how to expect to get "ARRRGH!" unless you return that too. You can return multiple objects but you typically need to attach it to an object. Lists and tuples are frequently used to return multiple objects. Some examples are below. # tuple return a,b,c # list (in-line) return [ a, b, c] # list (created and all objects added earlier) list_object = [] for x in xrange(4): list_object.append( x ) #just an example return list_object # as attribute (use when you need to pass state / data handling) obj = Class() obj.attribute = [a,b,c] return obj > > ----------------------------------------- > > Can you help me understand? I can't move forward until I understand > how Python solves this code. I recommend going through some beginner Python tutorials first to get a grasp of how Python works before you start on a book for Raspberry Pi. > > Thanks in advance > Optional ~Ramit 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. From alan.gauld at btinternet.com Wed Sep 11 01:52:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Sep 2013 00:52:59 +0100 Subject: [Tutor] Question about Functions In-Reply-To: References: Message-ID: On 10/09/13 18:49, novo shot wrote: > Dear tutors: > > The following is an example I found in the Raspberry Pi for Dummies book: > > #function test > > def theFunction(message): > print "I don't get ", message > return "ARRRGH!" All the code above does is define the function and assign it the name theFunction (which is a terrible name but we'll ignore that for now!) It does not execute the function. > theFunction("this") Any time the function name is followed by parentheses (but not preceded by def) the function gets executed. So this calls the function passing in the argument 'this' which results in the string "I don't get this" being printed. The value 'AARGH!' is returned but not stored anywhere so is lost. > result=theFunction("this either") This time the function is executed with the argument 'this either' passed in and the string "I don't get this either" is printed. Again the value 'AARGH!' is returned but this time it is assigned to the variable result. > print "reply is: ", result This prints the string "reply is: AARGH!" > The result of this code looks like this: > > I don't get this > I don't get this either > reply is: ARRRGH! Which is what I described above. > When I declare a variable to be equal as the fucntion > (result=theFunction("this either")) is Python also executing the > function? Yes, every time the function name is followed by parentheses it gets executed (and the return value assigned to any variable ready to receive it). > The way I see it, I only called for the function once before printing > ARRRGH!! Then after that I declared a variable and then I print. Wrong. You defined the function once. You called it twice. Then you printed the return value of the second invocation. > This is how I expected the result to look like: > > I don't get this > reply is: I don't get this either > ARRRGH! The 'I don't get...' line is printed inside the function. The program outside the function knows nothing about that. It has no way to access that string. That separation of what's inside the function from the code outside is a very important feature of programming and is known as abstraction, data hiding and encapsulation. (All subtly different variations on the same theme but very important in programming). It is this feature that enables us to write reusable functions that can be inserted into any program without relying on, or breaking, the surrounding code. One final thing to note is that when you are at the Python interpreter prompt the return value of a function is always printed. But when executing a script file the return value is not printed unless the program does it explicitly using print. >>> def f(): ... print 'this is always printed' ... return "this isn't" ... >>> f() this is always printed "this isn't" Now if you put the definition of f() in a file called test.py like this: ################ def f(): print 'this is always printed' return "this isn't" f() ############## and run it, you will only see the first line printed. The return value has been lost because it was never explicitly printed out. This difference in behaviour between the >>>> prompt and executing a script often confuses beginners but is a useful feature when testing/experimenting at the >>> prompt. You just need to remember that it will not always give identical behaviour to a script. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ljetibo at gmail.com Wed Sep 11 01:49:15 2013 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Wed, 11 Sep 2013 01:49:15 +0200 Subject: [Tutor] Question about Functions Message-ID: > Date: Tue, 10 Sep 2013 13:34:50 -0400 > From: novo shot > To: tutor at python.org > Subject: [Tutor] Question about Functions > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Dear tutors: > > The following is an example I found in the Raspberry Pi for Dummies book: > > #function test > > def theFunction(message): > print "I don't get ", message > return "ARRRGH!" > > theFunction("this") > > result=theFunction("this either") > print "reply is: ", result > > --------------------------------------------- > The result of this code looks like this: > > I don't get this > I don't get this either > reply is: ARRRGH! > > ---------------------------------------------- > Here's what I don't understand: > > When I declare a variable to be equal as the fucntion > (result=theFunction("this either")) is Python also executing the function? > > The way I see it, I only called for the function once before printing > ARRRGH!! Then after that I declared a variable and then I print. > > This is how I expected the result to look like: > > I don't get this > reply is: I don't get this either > ARRRGH! > > ----------------------------------------- > > Can you help me understand? I can't move forward until I understand how > Python solves this code. > > Thanks in advance Function in Python work very much the same way like they do in most programming languages. When working with them you can't really "feel" the difference. There is a big difference, however, "underneath" (just always keep in mind everything in Python is an object, the book should mention that repeatedly). Since you didn't mention I have to assume you didn't do any programming before python. In the case of big C's (C, C++, C#) I was always thought that I should look at a function as a variable. In particular the exact same variable you return. I.e. if I have a function: >>> def add1(int_number): return number+1 you can look at function add1 as if it's an integer because it returns an integer. The same applies to your example, which you can see if you do some introspection: >>> type(result) So you see your result is nothing more then a string! Basically whatever you return in your function will be assigned to the variable you return it to. Because you return "AARGH" in your function and assign the return value to result: >>> result=theFunction("thisEither") the variable result will become "AARGH". So this line basically amounts to: >>> result= "AARGH" This is a special case because this function always returns the same thing. That's not usually the case with functions. I.e. let's return to my add1 function. Output (that part behind the return statement) of add1 function will change depending on the input number: >>> add1(3) 4 >>> added = add1(5) >>> print added 6 What you can also see from the above example is that when I explicitly assigned a variable to a function [added = add1(5)] the result of the function did not print out, but the function must have executed because variable added has a value of '6'. So function executes every time you call on it, but prints out value of "return" only when you don't specify a "container" that will hold it's output. I'm pretty sure you're confused here because you have a print statement in your function. Print statement calls on your standard output that works "over" anything and pretty much "whenever", it's kind of special that way. If I changed my example function add1 to: >>> def add1(int_number): print "Working, hold your horses...." return number+1 then my output from before would be: >>> add1(3) Working, hold your horses.... 4 >>> added = add1(5) Working, hold your horses.... >>> print added 6 This is the main difference between return and print, think of return like it defaults to print if there is no value to which it can assign what it returned. That is also why you always see line "I don't get (this/this either)" printed every time you call on your function. >>> theFunction("this") I don't get this ARRGHHH >>> result=theFunction("this either") I don't get this either >>> print "reply is: ", result reply is AARGGGHHHH I think it should be pretty clear by now how it works..... On another note apparently ugly with an f in front is a bad word around here, my apologies I'm fairly new around these places and was inquiring for your help not even a week ago and don't really know how things work. But I am willing to help out like you did me, does that count? Also I'm not a programmer so I imagine analogies when I program and may be off point sometimes, hope I didn't make too many people cringe because of that... Regards, Dino From steve at pearwood.info Wed Sep 11 04:45:04 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 11 Sep 2013 12:45:04 +1000 Subject: [Tutor] Question about Functions In-Reply-To: References: Message-ID: <20130911024504.GR26319@ando> On Tue, Sep 10, 2013 at 01:49:11PM -0400, novo shot wrote: > When I declare a variable to be equal as the fucntion > (result=theFunction("this either")) is Python also executing the > function? No, you have misunderstood. Equals in programming languages is not the same as equals in mathematics. Some languages, like Pascal, use := instead of = in order to avoid that misunderstanding. In mathematics, "y = 3*x - 1" declares that y is equal to the equation on the right, no matter what value x happens to have. But in programming, instead it *evaluates* the equation on the right, using the current value of x, and *assigns* the result to y. So in your example above, result=theFunction("this either"), Python evaluates the function call theFunction("this either"), collects whatever result is returned (but not what is printed!), and assigns that to the variable "result". Since theFunction prints some things, they will be printed but not assigned to anything. Only whatever is returned, using the "return" statement, will be assigned to variable "result". [...] > Can you help me understand? I can't move forward until I understand > how Python solves this code. It might help you to start with a simpler example: def print_test(): print "Hello World!" # use print("...") in Python 3 This function takes no arguments, and always prints the same thing. It returns nothing. (To be precise, it returns the special object None, but don't worry about that.) py> print_test() # Round brackets calls the function Hello World! py> result = print_test() Hello World! py> result py> So this demonstrates that printing values just prints them. You cannot access the printed result programatically. It just gets printed to the screen and that's it. def return_test(): return "And now for something completely different!" This function uses return instead of print. Here it is in use: py> return_test() 'And now for something completely different!' py> result = return_test() py> result 'And now for something completely different!' py> result.upper() 'AND NOW FOR SOMETHING COMPLETELY DIFFERENT!' So as you can see, using return is *much* more flexible. You can capture the result of the function, hold of printing it until you want, or process it further, pass it on to other functions, or so forth. Finally, let's combine the two: def test_both(): print "This is immediately printed." return "And this is returned." By now you hopefully should be able to predict what calling this function will do, but just in case you can't: py> result = test_both() This is immediately printed. py> result 'And this is returned.' py> result.upper() 'AND THIS IS RETURNED.' -- Steven From xrandomheartzx at aim.com Wed Sep 11 03:01:55 2013 From: xrandomheartzx at aim.com (Katie) Date: Tue, 10 Sep 2013 21:01:55 -0400 (EDT) Subject: [Tutor] Python Programming Help Message-ID: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> Hello, I am a beginner in computer programming. I am studying math, and the math class that I will be taking requires knowledge in Python. So, I am in a computer science class. Therefore, I do not have an in-depth knowledge of computer programming. I am currently trying to write a program in Python version 2.7.5 that uses the math module to compute sinh(x) = 1/2(e^x - e^(-x)) in three ways for a given value of x: 1a) by using the sinh function 1b) by using the exp function 1c) by using the value of e and the exponentiation operator ** 2. Print the results and note any differences that appear. So, I know that I have to create a NotePad file so that I can import that into my command prompt. In my NotePad file, I have the following...I'm not sure if I am even going about doing this problem correctly... def sinh(x): return (1/2)*(e^x - e^(-x)) def exp(x): return e**x I am stuck, and don't know where to go from here. I would appreciate help please. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at chrisdown.name Wed Sep 11 11:14:21 2013 From: chris at chrisdown.name (Chris Down) Date: Wed, 11 Sep 2013 11:14:21 +0200 Subject: [Tutor] Python Programming Help In-Reply-To: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> References: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> Message-ID: <20130911091421.GK839@chrisdown.name> On 2013-09-10 21:01, Katie wrote: > In my NotePad file, I have the following...I'm not sure if I am even going > about doing this problem correctly... I don't envy you having to use notepad. Consider using a more sane editor... you'll thank yourself for it. > def sinh(x): > return (1/2)*(e^x - e^(-x)) > def exp(x): > return e**x > > I am stuck, and don't know where to go from here. I would appreciate help please. You'd have done well to present the problem you're having, but you should know that ^ is XOR (as it is in most programming languages), you probably want ** (and space out your function definitions -- PEP8 says to use two blank lines between functions). -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From amitsaha.in at gmail.com Wed Sep 11 11:48:34 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 11 Sep 2013 19:48:34 +1000 Subject: [Tutor] Python Programming Help In-Reply-To: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> References: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> Message-ID: Hi Katie, On Wed, Sep 11, 2013 at 11:01 AM, Katie wrote: > Hello, > > I am a beginner in computer programming. I am studying math, and the math > class that I will be taking requires knowledge in Python. So, I am in a > computer science class. Therefore, I do not have an in-depth knowledge of > computer programming. Welcome to the forum and welcome to the world of programming! > > I am currently trying to write a program in Python version 2.7.5 that uses > the math module to compute sinh(x) = 1/2(e^x - e^(-x)) in three ways for a > given value of x: > 1a) by using the sinh function > 1b) by using the exp function > 1c) by using the value of e and the exponentiation operator ** > > 2. Print the results and note any differences that appear. > > So, I know that I have to create a NotePad file so that I can import that > into my command prompt. > > In my NotePad file, I have the following...I'm not sure if I am even going > about doing this problem correctly... Okay, so when you are programming, there are two things you do to see the result of your programs: 1. First, you write the program. You write this in an text editor. Notepad is a text editor (There are better options, but let's keep it as it is for now) 2. Then, you run the program. Sometimes you can run the program from the editor itself, such as in IDLE. Other times, you have to run it separately. So, before you write the solution to the programming problem above, can you first try to write a program and then run it? What operating system are you working? If you are on Windows, can I suggest you to take a look at these videos I created a while back and they may help you: http://www.youtube.com/playlist?list=PLD0rs_vnIQS5r8IhNpu0rWIAyKpTX34yo Only when you have written your first program, which is really simple, you should try to attempt your exercise. Hope that helps. -Amit. -- http://echorand.me From alan.gauld at btinternet.com Wed Sep 11 11:52:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Sep 2013 10:52:52 +0100 Subject: [Tutor] Python Programming Help In-Reply-To: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> References: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> Message-ID: On 11/09/13 02:01, Katie wrote: > I am a beginner in computer programming. Hi welcome to the tutor list. > I am currently trying to write a program in Python version 2.7.5 *that > uses the math module to compute sinh(x) = 1/2(e^x - e^(-x)) in three > ways for a given value of x:* > *1a) by using the sinh function* > *1b) by using the exp function* > *1c) by using the value of e and the exponentiation operator > So, I know that I have to create a NotePad file so that I can import > that into my command prompt. You don;t need to import it into the command prompt although you may for that for testing purposes. But you can run Python programs directly by double clicking them in your file explorer. It will help if you tell us which version of Python you are using and which Operating System you use. (I'll assume Windows in this post since you mention Notepad) Finally, Notepad is fine for short text notes but it's not good for programming. You should get a proper programer's editor. IDLE comes with Python in most cases and if you are using Windows and download the ActiveState version of Python you will also get Pythonwin. Either of those will be better than Notepad for writing code. > In my NotePad file, I have the following...I'm not sure if I am even > going about doing this problem correctly... > > def sinh(x): > return (1/2)*(e^x - e^(-x)) The ^ sign does not do what you think in Python. The operator you need is ** (or use the pow() function). Also e is not defined directly, it's in the math module so you need to import math and then reference it as math.e Alternatively, import e from math: >>> from math import e,exp # import e and exp() from math And then use them directly: >>> import math >>> math.exp(3) 20.085536923187668 or >>> from math import e,exp >>> exp(3) 20.085536923187668 > I am stuck, and don't know where to go from here. I would appreciate > help please. You have defined your first version of sinh() you now need to fix and test it. You can either import it into your python session >>> import sinh # assuming the file is called sinh.py >>> sinh.sinh(5) # remember to include the module name as a prefix or You could call the function in your file and run it by clicking in explorer. To do that you should add to the end of your file: print( sinh(2) ) # use any test value you wish... input('Hit enter to quit') # pauses output so you can see it If you are comfortable using the OS command prompt you can also run it from there with C:\PATH\TO\YOUR\FILE> python sinh.py This has the advantage that you will see any error messages too. Finally, if you use IDLE or Pythonwin you can run the program from inside those tools using the menus. At this stage that's probably the best option. You can get a video tutorial on using IDLE here: http://www.youtube.com/watch?v=bOvqYw1SZJg HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From oscar.j.benjamin at gmail.com Wed Sep 11 11:59:11 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 11 Sep 2013 10:59:11 +0100 Subject: [Tutor] Python Programming Help In-Reply-To: References: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> Message-ID: On 11 September 2013 10:48, Amit Saha wrote: > Hi Katie, > > So, before you write the solution to the programming problem above, > can you first try to write a program and then run it? What operating > system are you working? If you are on Windows, can I suggest you to > take a look at these videos I created a while back and they may help > you: http://www.youtube.com/playlist?list=PLD0rs_vnIQS5r8IhNpu0rWIAyKpTX34yo Good work Amit. I don't have any sound on this machine but I skimmed those videos and they seem really useful. I'll remember to point someone there in future. Do you know of anything similar for OSX? Oscar From oscar.j.benjamin at gmail.com Wed Sep 11 12:15:26 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 11 Sep 2013 11:15:26 +0100 Subject: [Tutor] [Re:] I need help with the following question In-Reply-To: References: Message-ID: I'm resending this to the list. Please reply to the tutor list rather than directly to me. Also please don't top-post. My answer is below. On 11 September 2013 10:47, Thabile Rampa wrote: > > On Tue, Sep 10, 2013 at 11:57 AM, Oscar Benjamin wrote: >> >> On 10 September 2013 08:58, Thabile Rampa wrote: >> > On Aug 27, 2013, at 3:40 AM, isaac Eric wrote >> > >> > According to my understanding, the purpose of the %s is to turn the numbers, >> > which the program has recognized as numbers, into strings, so that they fit >> > in the print command without any syntax errors. >> > >> >> You are correct. '%s' is used to convert numbers (or other non-string >> things) into strings so that they can be used in places where text is >> required. In the particular case of the print command, this is done >> automatically so printing a number directly works just fine: >> > Wow! Thanks so much guy! > > The last two paragraphs especially made it a lot easier to understand! but why are there so many ways to achieve one goal in Python? The str() function is the default way to convert an object to a string. The print statement uses this implicitly if you try to print something that is not a string which is convenient for simple output. The % formatting codes allow for more advanced usage (see below) but %s is just for the specific case where you want to convert each object using str(). Here's how you can use % formatting to represent the same number in different ways: >>> radius = 12.3456789 >>> radius 12.3456789 >>> print 'radius =', radius radius = 12.3456789 >>> print 'radius = %s' % radius radius = 12.3456789 >>> print 'radius = %.3f' % radius radius = 12.346 >>> print 'radius = %.5f' % radius radius = 12.34568 >>> print 'radius = %.5e' % radius radius = 1.23457e+01 There is also the .format method. This was initially intended to replace % formatting but it was ultimately decided that removing % formatting was not necessary. Consequently there are now two ways of doing advanced string formatting in Python. Oscar From steve at pearwood.info Wed Sep 11 13:54:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 11 Sep 2013 21:54:03 +1000 Subject: [Tutor] [Re:] I need help with the following question In-Reply-To: References: Message-ID: <20130911115403.GS26319@ando> On Wed, Sep 11, 2013 at 11:15:26AM +0100, Oscar Benjamin wrote: > There is also the .format method. This was initially intended to > replace % formatting but it was ultimately decided that removing % > formatting was not necessary. Consequently there are now two ways of > doing advanced string formatting in Python. Three ways. People forget the string.Template class. py> import string py> template = string.Template("Hello $name") py> template.substitute(name="Oscar") 'Hello Oscar' py> template.safe_substitute(nmae="Oscar") 'Hello $name' -- Steven From amitsaha.in at gmail.com Wed Sep 11 22:44:12 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Thu, 12 Sep 2013 06:44:12 +1000 Subject: [Tutor] Python Programming Help In-Reply-To: References: <8D07CA1A4B60A29-6D4-86CC@Webmail-d112.sysops.aol.com> Message-ID: On Wed, Sep 11, 2013 at 7:59 PM, Oscar Benjamin wrote: > On 11 September 2013 10:48, Amit Saha wrote: >> Hi Katie, >> >> So, before you write the solution to the programming problem above, >> can you first try to write a program and then run it? What operating >> system are you working? If you are on Windows, can I suggest you to >> take a look at these videos I created a while back and they may help >> you: http://www.youtube.com/playlist?list=PLD0rs_vnIQS5r8IhNpu0rWIAyKpTX34yo > > Good work Amit. I don't have any sound on this machine but I skimmed > those videos and they seem really useful. I'll remember to point > someone there in future. Do you know of anything similar for OSX? Thanks, Oscar. I haven't really seen something similar for OSX, mainly because I have never used one. I searched now though on YouTube and there seems to be a few. -- http://echorand.me From zubair.alam.jmi at gmail.com Wed Sep 11 14:40:18 2013 From: zubair.alam.jmi at gmail.com (zubair alam) Date: Wed, 11 Sep 2013 18:10:18 +0530 Subject: [Tutor] class data member and objects of class in python Message-ID: i am learning how a __class__ data member behaves in python as compared to static data member in java, but following code is throwing error class PizzaShop(): pizza_stock = 10 def get_pizza(self): while not PizzaShop.pizza_stock: PizzaShop.pizza_stock -= 1 yield "take yours pizza order, total pizzas left {}".format(PizzaShop.pizza_stock) mypizza_shop = PizzaShop() pizza_order = mypizza_shop.get_pizza() # iterator is obtained print "a pizza pls!! {}:".format(pizza_order.next()) print "a pizza pls!! {}:".format(pizza_order.next()) output: Traceback (most recent call last): File "/home/scott/pythonfiles/core_python/pizza.py", line 10, in print "a pizza pls!! {}:".format(pizza_order.next()) StopIteration don't know where i am doing mistake....any help will be appreciated... i have other questions on based on this class -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Sep 12 03:23:52 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 11 Sep 2013 18:23:52 -0700 Subject: [Tutor] class data member and objects of class in python In-Reply-To: References: Message-ID: On Wed, Sep 11, 2013 at 5:40 AM, zubair alam wrote: > i am learning how a __class__ data member behaves in python as compared to > static data member in java, but following code is throwing error > > > class PizzaShop(): > pizza_stock = 10 > def get_pizza(self): > while not PizzaShop.pizza_stock: > PizzaShop.pizza_stock -= 1 > yield "take yours pizza order, total pizzas left > {}".format(PizzaShop.pizza_stock) > > mypizza_shop = PizzaShop() > pizza_order = mypizza_shop.get_pizza() # iterator is obtained > print "a pizza pls!! {}:".format(pizza_order.next()) > print "a pizza pls!! {}:".format(pizza_order.next()) > > output: > Traceback (most recent call last): > File "/home/scott/pythonfiles/core_python/pizza.py", line 10, in > print "a pizza pls!! {}:".format(pizza_order.next()) > StopIteration > > > don't know where i am doing mistake....any help will be appreciated... i > have other questions on based on this class > > Change "while not PizzaShop.pizza_stock:" to "while PizzaShop.pizza_stock:"; I get the following output: > a pizza pls!! take yours pizza order, total pizzas left 9: > a pizza pls!! take yours pizza order, total pizzas left 8: > -------------- next part -------------- An HTML attachment was scrubbed... URL: From felix.dietrich at sperrhaken.name Thu Sep 12 02:59:51 2013 From: felix.dietrich at sperrhaken.name (Felix Dietrich) Date: Thu, 12 Sep 2013 02:59:51 +0200 Subject: [Tutor] class data member and objects of class in python In-Reply-To: (zubair alam's message of "Wed, 11 Sep 2013 18:10:18 +0530") References: Message-ID: <87hadqx3aw.fsf@sperrhaken.name> > i am learning how a __class__ data member behaves in python as > compared to static data member in java [...] The error is not related to class variables. Also could you elaborate on what you intended to find out with this snippet? > class PizzaShop(): > pizza_stock = 10 > > def get_pizza(self): > while not PizzaShop.pizza_stock: > PizzaShop.pizza_stock -= 1 > yield "take yours pizza order, total pizzas left {}".format(PizzaShop.pizza_stock) The condition in the while loop is wrong. bool(PizzaShop.pizza_stock) is True for all values but 0. (All numbers but 0 are considered True.) The while loop does its commands while the condition holds True. When you do not PizzaShop.pizza_stock it will return False for values other than 0, therefor the loop is never run and on exit of get_pizza it raises StopIteration to indicate that there are no more values to be yielded. > mypizza_shop = PizzaShop() > pizza_order = mypizza_shop.get_pizza() # iterator is obtained > print "a pizza pls!! {}:".format(pizza_order.next()) > print "a pizza pls!! {}:".format(pizza_order.next()) You might want to catch StopIteration here so that you can handle the case that the shop runs out of the initial stack of pizzas. ;) -- Felix Dietrich From zubair.alam.jmi at gmail.com Thu Sep 12 11:10:08 2013 From: zubair.alam.jmi at gmail.com (zubair alam) Date: Thu, 12 Sep 2013 14:40:08 +0530 Subject: [Tutor] class data member and objects of class in python In-Reply-To: References: Message-ID: class PizzaShop(): pizza_stock = 10 def get_pizza(self): while PizzaShop.pizza_stock: PizzaShop.pizza_stock -= 1 yield "take yours pizza order, total pizzas left {}".format(PizzaShop.pizza_stock) mypizza_shop = PizzaShop() pizza_order = mypizza_shop.get_pizza() # print "{}".format(repr(pizza_order.next())) for order in pizza_order: print "{}".format(repr(order)) domino_pizza_store = mypizza_shop.get_pizza() print "{}".format(repr(domino_pizza_store.next())) mypizza_shop.pizza_stock = 10 domino_pizza_store = mypizza_shop.get_pizza() print "{}".format(repr(domino_pizza_store.next())) can't we again use the same object mypizza_shop once its generator is exhausted On Thu, Sep 12, 2013 at 6:53 AM, Marc Tompkins wrote: > On Wed, Sep 11, 2013 at 5:40 AM, zubair alam wrote: > >> i am learning how a __class__ data member behaves in python as compared >> to static data member in java, but following code is throwing error >> >> >> class PizzaShop(): >> pizza_stock = 10 >> def get_pizza(self): >> while not PizzaShop.pizza_stock: >> PizzaShop.pizza_stock -= 1 >> yield "take yours pizza order, total pizzas left >> {}".format(PizzaShop.pizza_stock) >> >> mypizza_shop = PizzaShop() >> pizza_order = mypizza_shop.get_pizza() # iterator is obtained >> print "a pizza pls!! {}:".format(pizza_order.next()) >> print "a pizza pls!! {}:".format(pizza_order.next()) >> >> output: >> Traceback (most recent call last): >> File "/home/scott/pythonfiles/core_python/pizza.py", line 10, in >> >> print "a pizza pls!! {}:".format(pizza_order.next()) >> StopIteration >> >> >> don't know where i am doing mistake....any help will be appreciated... i >> have other questions on based on this class >> >> > > Change "while not PizzaShop.pizza_stock:" to "while > PizzaShop.pizza_stock:"; I get the following output: > >> a pizza pls!! take yours pizza order, total pizzas left 9: >> a pizza pls!! take yours pizza order, total pizzas left 8: >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 12 15:39:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Sep 2013 14:39:53 +0100 Subject: [Tutor] class data member and objects of class in python In-Reply-To: References: Message-ID: On 12/09/13 10:10, zubair alam wrote: > class PizzaShop(): > pizza_stock = 10 > def get_pizza(self): > while PizzaShop.pizza_stock: > PizzaShop.pizza_stock -= 1 > yield "take yours pizza order, total pizzas left > {}".format(PizzaShop.pizza_stock) > > mypizza_shop = PizzaShop() > pizza_order = mypizza_shop.get_pizza() > > for order in pizza_order: > print "{}".format(repr(order)) You might as well just use print order > domino_pizza_store = mypizza_shop.get_pizza() > print "{}".format(repr(domino_pizza_store.next())) > > mypizza_shop.pizza_stock = 10 This preobably isn't doing what you think it is. This is creating a new instance attribute in the mypizza_shop instance it is not resetting the class attribute. For that you would need to use PizzaShop.pizza_stock = 10 > can't we again use the same object mypizza_shop > once its generator is exhausted You can't use the same iterator again but you can get a new one. But your problem here is that you have not reset the class stock level. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ljetibo at gmail.com Thu Sep 12 14:25:05 2013 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Thu, 12 Sep 2013 14:25:05 +0200 Subject: [Tutor] Tutor Digest, Vol 115, Issue 27 Message-ID: > Date: Wed, 11 Sep 2013 18:10:18 +0530 > From: zubair alam > To: tutor > Subject: [Tutor] class data member and objects of class in python > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > i am learning how a __class__ data member behaves in python as compared to > static data member in java, but following code is throwing error > > > class PizzaShop(): > pizza_stock = 10 > def get_pizza(self): > while not PizzaShop.pizza_stock: > PizzaShop.pizza_stock -= 1 > yield "take yours pizza order, total pizzas left > {}".format(PizzaShop.pizza_stock) > > mypizza_shop = PizzaShop() > pizza_order = mypizza_shop.get_pizza() # iterator is obtained > print "a pizza pls!! {}:".format(pizza_order.next()) > print "a pizza pls!! {}:".format(pizza_order.next()) > > output: > Traceback (most recent call last): > File "/home/scott/pythonfiles/core_python/pizza.py", line 10, in > print "a pizza pls!! {}:".format(pizza_order.next()) > StopIteration > > > don't know where i am doing mistake....any help will be appreciated... i > have other questions on based on this class Integers different from zero are considered to be True. So what you're basically doing is: >>> pizza_stock=10 >>> while not pizza_stock:0 ## not True == False so the loop never runs, not even once. Python reports an error because of that. Similar reports occur if you have variables that are not used but those are Warnings and not actual Error events. Regards, Dino From davea at davea.name Thu Sep 12 22:15:11 2013 From: davea at davea.name (Dave Angel) Date: Thu, 12 Sep 2013 20:15:11 +0000 (UTC) Subject: [Tutor] class data member and objects of class in python References: Message-ID: On 12/9/2013 05:10, zubair alam wrote: >
class PizzaShop():
? ? pizza_stock = 10
? ? def get_pizza(self):
? ? ? ? while PizzaShop.pizza_stock:
? ? ? ? ? ? PizzaShop.pizza_stock -= 1
? ? ? ? ? ? yield "take yours pizza order, total pizzas left {}".format(PizzaShop.pizza_stock)
>

mypizza_shop = PizzaShop()
pizza_order = mypizza_shop.get_pizza()?
# print "{}".format(repr(pizza_order.next()))

for order in pizza_order:
> print "{}".format(repr(order))

domino_pizza_store = mypizza_shop.get_pizza()
print "{}".format(repr(domino_pizza_store.next()))
>

mypizza_shop.pizza_stock = 10

domino_pizza_store = mypizza_shop.get_pizza()
print "{}".format(repr(domino_pizza_store.next()))


>
can't we again use the same object mypizza_shop once its generator is exhausted


On Thu, Sep 12, 2013 at 6:53 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
Please use text email, not hmtl. The indentation of your program was messed up in places, and I can't tell whether it was you or the email program that messed it up. This is a text newgroup, and html doesn't work reliably. As Alan has said, you're confusing class attributes with instance attributes. But I wonder if the mistake is actually the reverse of what he says. Do you intend that an instance of PizzaShop refers to a particul pizza shop, and that it has its own inventory, independent of all other pizza shop instances? in that case all use of the class attribute pizza_stock = 10 is bogus. To re-iterate the other point Alan made, an iterator is *required* to continue to throw Stopiteration once its exhausted and has thrown it once, even if new items show up that it could have used. But you can readily make a new iterator from the same mypizza_shop, once you set its pizza_stock to a nonzero value. -- DaveA From dotancohen at gmail.com Fri Sep 13 12:24:40 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 13 Sep 2013 12:24:40 +0200 Subject: [Tutor] Wrapping with list Message-ID: A function that I wrote works on a list or on a string. If the function is passed a string, then it wraps the string in a list at the top of the function. Is it bad form to wrap the sting in place? if not isinstance(someVar, list): someVar = [someVar] To avoid that, I am creating a list then appending the original value: if not isinstance(someVar, list): temp = someVar someVar = [] someVar.append(temp) Is my prudence unwarrented? Thanks! -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From oscar.j.benjamin at gmail.com Fri Sep 13 13:18:30 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 13 Sep 2013 12:18:30 +0100 Subject: [Tutor] Wrapping with list In-Reply-To: References: Message-ID: On 13 September 2013 11:24, Dotan Cohen wrote: > A function that I wrote works on a list or on a string. If the > function is passed a string, then it wraps the string in a list at the > top of the function. Is it bad form to wrap the sting in place? > > if not isinstance(someVar, list): > someVar = [someVar] > > To avoid that, I am creating a list then appending the original value: > > if not isinstance(someVar, list): > temp = someVar > someVar = [] > someVar.append(temp) > > Is my prudence unwarrented? Yes it is. A simple assignment 'someVar = ...' does not modify the object that the name 'someVar' previously referred to. The right hand side of the assignment is evaluated producing an object and the name 'someVar' is bound to the created object. >>> a = 'asd' >>> b = a >>> a 'asd' >>> b 'asd' >>> b = 'qwe' >>> a 'asd' >>> b 'qwe' Unless 'someVar' is declared global or nonlocal the name binding is local to the function. >>> def f(x): ... x = 1 ... >>> a = 2 >>> a 2 >>> f(a) >>> a 2 >>> x Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined So the first form neither modifies the object in-place nor changes the binding of any names outside the function. The tow forms you showed above are equivalent except for the creation of the redundant name 'temp' that refers to the original argument passed to the function. Compound assignments e.g. 'a += b' can sometimes modify the object referred to by the name 'a' in-place if the object is mutable e.g. a list: >>> a = [1, 2, 3] >>> b = a >>> a [1, 2, 3] >>> b [1, 2, 3] >>> b += [4] >>> a [1, 2, 3, 4] >>> b [1, 2, 3, 4] >>> b = b + [5] >>> a [1, 2, 3, 4] >>> b [1, 2, 3, 4, 5] However, if 'a' is bound to an immutable object (such as a string) then in-place modification is impossible and 'a += b' is equivalent to 'a = a + b'. >>> s = 'qwe' >>> s2 = s >>> s 'qwe' >>> s2 'qwe' >>> s2 += 'zxc' >>> s 'qwe' >>> s2 'qwezxc' Oscar From davea at davea.name Fri Sep 13 13:23:13 2013 From: davea at davea.name (Dave Angel) Date: Fri, 13 Sep 2013 11:23:13 +0000 (UTC) Subject: [Tutor] Wrapping with list References: Message-ID: On 13/9/2013 06:24, Dotan Cohen wrote: > A function that I wrote works on a list or on a string. If the > function is passed a string, then it wraps the string in a list at the > top of the function. Is it bad form to wrap the sting in place? > > if not isinstance(someVar, list): > someVar = [someVar] > > To avoid that, I am creating a list then appending the original value: > > if not isinstance(someVar, list): > temp = someVar > someVar = [] > someVar.append(temp) > > Is my prudence unwarrented? > yes. There are two possible issues with your first approach. The first is that somehow this is too complicated for one statement, and that something might go wrong. No worries there, as long as the object is fully formed on the right side, the "assignment" won't take place until the expression is fully evaluated. But the second one is that you now have a name that has two different meanings, depending on the path through the code. Fans of static typing might criticize this, but it's part of the essence of Python flexibility. As long as you're careful about how you implement the if-test, there's nothing wrong with doing the assignment in one statement. A separate question is whether defining the function to take these two specific types of argument is reasonable. As soon as you have an isinstnace() call, you might shortcircuit some duck-typing usage that yo hadn't imagined for your function. If you're writing a library function, to be used many places, best think about it really hard. But if it's an ordinary function, go with it. -- DaveA From steve at pearwood.info Fri Sep 13 13:25:42 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 13 Sep 2013 21:25:42 +1000 Subject: [Tutor] Wrapping with list In-Reply-To: References: Message-ID: <20130913112542.GH16820@ando> On Fri, Sep 13, 2013 at 12:24:40PM +0200, Dotan Cohen wrote: > A function that I wrote works on a list or on a string. If the > function is passed a string, then it wraps the string in a list at the > top of the function. Is it bad form to wrap the sting in place? > > if not isinstance(someVar, list): > someVar = [someVar] > > To avoid that, I am creating a list then appending the original value: > > if not isinstance(someVar, list): > temp = someVar > someVar = [] > someVar.append(temp) > > Is my prudence unwarrented? Yes :-) The two pieces of code end up having *exactly* the same effect, except the second takes three lines instead of one, is harder to understand, and is a tiny bit slower. Oh, and it introduces an extra variable, which otherwise has no real reason to exist. In fact, it's quite likely that under the hood, the first version someVar = [someVar] ends up doing precisely what the second version does, except in fast C code rather than slower Python code. -- Steven From paulrsmith7777 at gmail.com Fri Sep 13 16:59:43 2013 From: paulrsmith7777 at gmail.com (Paul Smith) Date: Fri, 13 Sep 2013 10:59:43 -0400 Subject: [Tutor] Newbie question. Is it possible to run/call a python2.7 program and reference results from/in python3.3? Message-ID: Attempting a simple web crawler in python3, browse a url - collect/clean/produce valid url list from a url; random choice from valid url list; visit new url repeat process - collect/clean/produce valid url list from new url... So there are many tools out there but mechanize and scrapy 3rd party modules seem to produce the best results; however nothing like these exist for Python3. I get close but cannot produce the clean simple url results in python3 my borrowed bastardized python2.7 code producing clean url list from "nytimes" example: ### #MechSnake2 import urllib import mechanize import cookielib from bs4 import BeautifulSoup import urlparse # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # debugging messages br.set_debug_http(True) br.set_debug_redirects(True) br.set_debug_responses(True) # User-Agent Not a Robot here spoof Mozilla coolness.... br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] url = ("http://www.nytimes.com") br.open(url) for link in br.links(): newurl = urlparse.urljoin(link.base_url, link.url) b1 = urlparse.urlparse(newurl).hostname b2 = urlparse.urlparse(newurl).path print "http://"+b1+b2 ### Works like a charm! But now go do the same in python3? I am stumped... Most of the other project code I am working on is in Python3 and works great! I can produce everything above except the last parse join cleaning process (urllib.request.Request(url, headers = Mozilla/5.0 etc...for spoofing) but then it fails to produce the same clean list because of the Mechanize mojo producing link info that easily allows the parse join cleaning process at the end. So can one call the python27 program and use results in python33? Thank you in advance! Another nightmare is stripping-cleaning google search results into clean url lists... but I will defer to another post for that mess. Thanks again in advance Paul Smith +++ Two Kinds of Intelligence There are two kinds of intelligence: one acquired, as a child in school memorizes facts and concepts from books and from what the teacher says, collecting information from the traditional sciences as well as from the new sciences. With such intelligence you rise in the world. You get ranked ahead or behind others in regard to your competence in retaining information. You stroll with this intelligence in and out of fields of knowledge, getting always more marks on your preserving tablets. There is another kind of tablet, one already completed and preserved inside you. A spring overflowing its springbox. A freshness in the center of the chest. This other intelligence does not turn yellow or stagnate. It's fluid, and it doesn't move from outside to inside through conduits of plumbing-learning. This second knowing is a fountainhead from within you, moving out. Mewlana Jalaluddin Rumi +++ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 13 18:46:33 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Sep 2013 17:46:33 +0100 Subject: [Tutor] Newbie question. Is it possible to run/call a python2.7 program and reference results from/in python3.3? In-Reply-To: References: Message-ID: On 13/09/13 15:59, Paul Smith wrote: > So there are many tools out there but mechanize and scrapy 3rd party > modules seem to produce the best results; however nothing like these > exist for Python3. I get close but cannot produce the clean simple url > results in python3 Yes that's the biggest barrier to python 3 adoption. There are just too many tools that have not been ported yet. > But now go do the same in python3? I am stumped... You can do it but it's a rewrite with other modules. > So can one call the python27 program and use results in python33? Yes via the subprocess module. You can execute any program that reads/writes to stdin/out and access the output. Its not exactly pretty but it works. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Sep 13 18:57:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Sep 2013 17:57:20 +0100 Subject: [Tutor] Wrapping with list In-Reply-To: References: Message-ID: On 13/09/13 11:24, Dotan Cohen wrote: > A function that I wrote works on a list or on a string. If the > function is passed a string, then it wraps the string in a list at the > top of the function. Is it bad form to wrap the string in place? It depends what your function does. In most cases the string and list sequence methods work (strings are immutable lists are mutable so they can't be used identically). So maybe you want to treat the string as a sequence of chars. OTOH if you want to treat the string as a single element list then wrapping it makes sense. It all depends what your function does. > if not isinstance(someVar, list): > someVar = [someVar] Is that really what you want? What if a set, tuple or dict is passed in? Do you want to create a list containing the tuple or do you want to convert the tuple to a list? It depends what the function does. But if you only want to special case strings you would be better using if isinstance(someVar, str): someVar = [someVar] > To avoid that, I am creating a list then appending the original value: > > if not isinstance(someVar, list): > temp = someVar > someVar = [] > someVar.append(temp) Your first attempt is much simpler and produces an identical result. > Is my prudence unwarrented? Yes, it's just creating lots more work. But I'd consider if you can write the function such that it doesn't rely on types at all, can you use a subset of functions/methods that work on all/most sequence types? Then catch exceptions using a try/except construct? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alexpalazzo18 at aol.com Sun Sep 15 05:17:31 2013 From: alexpalazzo18 at aol.com (Alex Palazzo) Date: Sat, 14 Sep 2013 23:17:31 -0400 Subject: [Tutor] need help with something Message-ID: Hi i need help with something with python. Alexander Palazzo Rhode Island College '17 (401)474-1669 apalazzo_5558 at email.ric.edu -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Sep 15 10:45:39 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 15 Sep 2013 18:45:39 +1000 Subject: [Tutor] need help with something In-Reply-To: References: Message-ID: <20130915084538.GS16820@ando> On Sat, Sep 14, 2013 at 11:17:31PM -0400, Alex Palazzo wrote: > Hi i need help with something with python. And we're here to help. Would you like to tell us what you need help with, or shall we guess? -- Steven From dotancohen at gmail.com Tue Sep 17 07:47:28 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 17 Sep 2013 07:47:28 +0200 Subject: [Tutor] Wrapping with list In-Reply-To: References: Message-ID: Thank you to everyone who commented! I've refactored the code and I'm looking into "duck typing" to see if it fits this usage scenario. Thank you very much! -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From memilanuk at gmail.com Wed Sep 18 10:10:15 2013 From: memilanuk at gmail.com (memilanuk) Date: Wed, 18 Sep 2013 01:10:15 -0700 Subject: [Tutor] flask/sqlite3 problem - 'OperationalError: no such table'? Message-ID: Hello there, I'm working thru a Flask tutorial, and when I get to the portion for querying the database (sqlite3) for the existing posts, i.e. 'SELECT * FROM posts', I get an error that says there is no such table 'posts' in my database. Yet I can query said db file from either the sqlite3 command-line client, or from the python interactive interpreter, and run the same query and get the expected results. I've looked at this 'til I'm about ready to go cross-eyed... I'm sure it must be something simple that I'm missing, but I can't seem to spot it. Below is the tail end of the traceback error message, followed by the code from the file in question. Any help would be much appreciated. Thanks, Monte Traceback (most recent call last): ... return test(*args, **kwargs) File "/home/monte/Dropbox/Documents/Programming/python/flask/blog/blog.py", line 57, in main cur = g.db.execute('SELECT * FROM posts') OperationalError: no such table: posts # blog.py - application module from flask import Flask, render_template, request, session, flash, redirect, url_for, g from functools import wraps import sqlite3 # Configuration DATABASE = 'fblog.db' USERNAME = 'admin' PASSWORD = 'admin' SECRET_KEY = 'hard to guess' app = Flask(__name__) app.config.from_object(__name__) def connect_db(): #return sqlite3.connect(app.config['DATABASE']) return sqlite3.connect('fblog.db') #### Other functions not shown for brevity #### @app.route('/main') @login_required def main(): g.db = connect_db() cur = g.db.execute('SELECT * FROM posts') posts = [dict(title=row[0], post=row[1]) for row in cur.fetchall()] g.db.close() return render_template('main.html', posts=posts) if __name__ == '__main__': app.run(debug=True) From __peter__ at web.de Wed Sep 18 10:33:16 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Sep 2013 10:33:16 +0200 Subject: [Tutor] flask/sqlite3 problem - 'OperationalError: no such table'? References: Message-ID: memilanuk wrote: > I'm working thru a Flask tutorial, and when I get to the portion for > querying the database (sqlite3) for the existing posts, i.e. 'SELECT * > FROM posts', I get an error that says there is no such table 'posts' in > my database. Yet I can query said db file from either the sqlite3 > command-line client, or from the python interactive interpreter, and run > the same query and get the expected results. I've looked at this 'til > I'm about ready to go cross-eyed... I'm sure it must be something simple > that I'm missing, but I can't seem to spot it. Below is the tail end of > the traceback error message, followed by the code from the file in > question. Any help would be much appreciated. Sqlite3 (un)helpfully creates a new database if it doesn't find one. That may happen here if the current working directory differs from the one you are expecting. I'd try specifying the complete path of the db, something like def connect_db(): return sqlite3.connect('/path/to/fblog.db') From memilanuk at gmail.com Wed Sep 18 12:46:49 2013 From: memilanuk at gmail.com (memilanuk) Date: Wed, 18 Sep 2013 03:46:49 -0700 Subject: [Tutor] flask/sqlite3 problem - 'OperationalError: no such table'? In-Reply-To: References: Message-ID: Sheeesh... After reading your message, I realized I was running the script from inside a new-to-me IDE (pycharm), and started wondering if somehow a path or working directory was not what I thought it might be. I closed out the IDE window, and ran the script directly from the terminal - success! After that I went thru and did some digging through the settings for this particular 'project' in pycharm, and found an option for the working directory, which was set to a different folder. I fixed that and everything is off and running again. Looks like I need to do some more reading up on projects in pycharm before I shoot myself in the foot again... Thanks, Monte From alan.gauld at btinternet.com Wed Sep 18 15:37:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Sep 2013 14:37:53 +0100 Subject: [Tutor] flask/sqlite3 problem - 'OperationalError: no such table'? In-Reply-To: References: Message-ID: On 18/09/13 09:10, memilanuk wrote: > that I'm missing, but I can't seem to spot it. Below is the tail end of > the traceback error message, followed by the code from the file in > question. Any help would be much appreciated. > > line 57, in main > cur = g.db.execute('SELECT * FROM posts') > OperationalError: no such table: posts > > def connect_db(): > #return sqlite3.connect(app.config['DATABASE']) > return sqlite3.connect('fblog.db') You may need to specify a relatie path rather than just the filename. > def main(): > g.db = connect_db() > cur = g.db.execute('SELECT * FROM posts') You are trying to execute on the database rather than on a cursor. You need to create a cursor first to hold your results. Something like; cur = g.db.cursor() cur.execute(.....) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From corsam28 at hotmail.com Wed Sep 18 06:59:43 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Tue, 17 Sep 2013 23:59:43 -0500 Subject: [Tutor] Copy and paste python on Microsoft word Message-ID: I'm using python 3.3.0, I have made a program on my script and output it. I have tried several times to copy and paste the output and the script on Microsoft word, every time I select the part that I need and right click on it, this message appears: go to the file/line. It provides me no access to copy and paste them. Please, can someone help me? Sent from my iPhone From i.sheeha at gmail.com Wed Sep 18 11:05:18 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Wed, 18 Sep 2013 11:05:18 +0200 Subject: [Tutor] Web Services with python Message-ID: Hello, can someone point me to some good guality resources to learn Web Services with Python?with some exaples, tutorials, exercises and such. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Wed Sep 18 15:42:34 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 18 Sep 2013 23:42:34 +1000 Subject: [Tutor] Web Services with python In-Reply-To: References: Message-ID: On Wed, Sep 18, 2013 at 7:05 PM, Ismar Sehic wrote: > Hello, can someone point me to some good guality resources to learn Web > Services with Python?with some exaples, tutorials, exercises and such. What do you want to do? Do you want to connect to a remote server or do you want to implement a server, or both? -- http://echorand.me From amitsaha.in at gmail.com Wed Sep 18 15:44:14 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 18 Sep 2013 23:44:14 +1000 Subject: [Tutor] Copy and paste python on Microsoft word In-Reply-To: References: Message-ID: On Wed, Sep 18, 2013 at 2:59 PM, Sammy Cornet wrote: > I'm using python 3.3.0, I have made a program on my script and output it. I have tried several times to copy and paste the output and the script on Microsoft word, every time I select the part that I need and right click on it, this message appears: go to the file/line. It provides me no access to copy and paste them. Please, can someone help me? Are you using IDLE ? If so, select the text and use the "Edit" menu to copy/cut/paste. -- http://echorand.me From dfjennings at gmail.com Wed Sep 18 15:49:12 2013 From: dfjennings at gmail.com (Don Jennings) Date: Wed, 18 Sep 2013 09:49:12 -0400 Subject: [Tutor] Copy and paste python on Microsoft word In-Reply-To: References: Message-ID: <49512FE1-CEBF-49DC-A081-CA3D115A950F@gmail.com> On Sep 18, 2013, at 12:59 AM, Sammy Cornet wrote: > I'm using python 3.3.0, I have made a program on my script and output it. I have tried several times to copy and paste the output and the script on Microsoft word, every time I select the part that I need and right click on it, this message appears: go to the file/line. It provides me no access to copy and paste them. Please, can someone help me? Evidently you are using an IDE which is interfering with the behavior you expect. Tell us which IDE and I bet someone will be able to point you in the right direction. By the way, you *really* should use something other than MS Word to edit your python text files. People have offered plenty of suggestions in the past on this list. If you don't know how to search the archives (available at activestate [1] or gmane [2] among other places), ask. Take care, Don [1] http://code.activestate.com/lists/python-tutor/ [2] http://news.gmane.org/gmane.comp.python.tutor From hobbestigrou at erakis.eu Wed Sep 18 16:10:42 2013 From: hobbestigrou at erakis.eu (Natal =?iso-8859-1?Q?Ng=E9tal?=) Date: Wed, 18 Sep 2013 16:10:42 +0200 Subject: [Tutor] Web Services with python In-Reply-To: References: Message-ID: <20130918141042.GA32360@hobbestigrou-desktop> On 09/18/13 11:05, Ismar Sehic wrote: > Hello, can someone point me to some good guality resources to learn Web > Services with Python?with some exaples, tutorials, exercises and such. If you want to implement a server, you can look on the side of bottle or flask. From alan.gauld at btinternet.com Wed Sep 18 18:55:34 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Sep 2013 17:55:34 +0100 Subject: [Tutor] Web Services with python In-Reply-To: References: Message-ID: On 18/09/13 10:05, Ismar Sehic wrote: > Hello, can someone point me to some good guality resources to learn Web > Services with Python?with some exaples, tutorials, exercises and such. Python can do web services just fine both as server or client. But what kind of web service? REST? SOAP? XMLRPC? AJAX? What do you want to do then we can point you in a useful direction. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Sep 18 18:57:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Sep 2013 17:57:58 +0100 Subject: [Tutor] Copy and paste python on Microsoft word In-Reply-To: References: Message-ID: On 18/09/13 05:59, Sammy Cornet wrote: > I'm using python 3.3.0, I have made a program on my > script and output it. I have tried several times to > copy and paste the output and the script on Microsoft word, How are you creating and running your script? I'm guessing this is an IDE issue rather than a python one, but we need to know what toolset you are using. How do you create the program? What tool do you use to write the code? How do you run the program? Where does the output appear? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From timomlists at gmail.com Wed Sep 18 19:13:10 2013 From: timomlists at gmail.com (Timo) Date: Wed, 18 Sep 2013 19:13:10 +0200 Subject: [Tutor] flask/sqlite3 problem - 'OperationalError: no such table'? In-Reply-To: References: Message-ID: <5239DF26.6070505@gmail.com> Op 18-09-13 15:37, Alan Gauld schreef: > On 18/09/13 09:10, memilanuk wrote: > > >> def main(): >> g.db = connect_db() >> cur = g.db.execute('SELECT * FROM posts') > > You are trying to execute on the database rather > than on a cursor. You need to create a cursor > first to hold your results. > > Something like; > > cur = g.db.cursor() > cur.execute(.....) Not really. sqlite3.connect() returns a sqlite3.Connection object which has a execute method. It will create a cursor object for you. Cheers, Timo > > HTH From alan.gauld at btinternet.com Wed Sep 18 23:34:12 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Sep 2013 22:34:12 +0100 Subject: [Tutor] flask/sqlite3 problem - 'OperationalError: no such table'? In-Reply-To: <5239DF26.6070505@gmail.com> References: <5239DF26.6070505@gmail.com> Message-ID: On 18/09/13 18:13, Timo wrote: >> You are trying to execute on the database rather >> than on a cursor. You need to create a cursor >> first to hold your results. >> >> Something like; >> >> cur = g.db.cursor() >> cur.execute(.....) > Not really. > > sqlite3.connect() returns a sqlite3.Connection object which has a > execute method. It will create a cursor object for you. Interesting. I didn't know that, I've always created a separate cursor explicitly. But that's probably because I'm used to Oracle which requires me to do that from C++ -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jennyallar at gmail.com Wed Sep 18 18:50:51 2013 From: jennyallar at gmail.com (Jenny Allar) Date: Wed, 18 Sep 2013 12:50:51 -0400 Subject: [Tutor] Field Width Message-ID: I'm only a few days in to learning Python, so please bear with me. I need to line up the decimals on the printed information but I cannot get the text to look uniform at all. Here is my code: def main(): # Set up constants for cost per yard, flat fee, and tax rate cost_carpet = 5.50 fee = 25 tax = .06 # Ask for yards needed yards_needed = float(input('Please enter the total number of yards needed ')) # Calculate subtotal subtotal = yards_needed * cost_carpet + fee # Calculate tax_rate tax_rate = subtotal * tax # Calculate total_due total_due = subtotal + tax_rate # Print blank line print() # Print infomation print("The cost of the carpet is $", format(subtotal,'9,.2f')) print("The flat fee is $", format(fee,'9,.2f')) print("The tax is $", format(tax_rate,'9,.2f')) print("The total due is $", format(total_due,'9,.2f')) main () Thank you in advance, Jenny -------------- next part -------------- An HTML attachment was scrubbed... URL: From kotharinaman at yahoo.in Thu Sep 19 09:59:40 2013 From: kotharinaman at yahoo.in (Naman Kothari) Date: Thu, 19 Sep 2013 15:59:40 +0800 (SGT) Subject: [Tutor] How to add modules? Message-ID: <1379577580.55612.YahooMailNeo@web193805.mail.sg3.yahoo.com> Can you please suggest a link from where i can download SendKeys module for python. Also provide an explanation to add the module to my library. PS: I am a Windows user. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 19 11:24:20 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Sep 2013 11:24:20 +0200 Subject: [Tutor] Field Width References: Message-ID: Jenny Allar wrote: > I'm only a few days in to learning Python, so please bear with me. Welcome! > I need to line up the decimals on the printed information but I cannot get > the text to look uniform at all. > print("The cost of the carpet is $", format(subtotal,'9,.2f')) > print("The flat fee is $", format(fee,'9,.2f')) Just add some spaces manually: print("The cost of the carpet is $", format(subtotal,'9,.2f')) print("The flat fee is $", format(fee,'9,.2f')) This is usually written as print("The cost of the carpet is $ {:9,.2f}".format(subtotal)) print("The flat fee is $ {:9,.2f}".format(fee)) If this is not what you want you need to give more details; for instance: the above won't look "uniform" when it is displayed in a proportional font. From davea at davea.name Thu Sep 19 11:24:37 2013 From: davea at davea.name (Dave Angel) Date: Thu, 19 Sep 2013 09:24:37 +0000 (UTC) Subject: [Tutor] Field Width References: Message-ID: On 18/9/2013 12:50, Jenny Allar wrote: > I'm only a few days in to learning Python, so please bear with me. > > I need to line up the decimals on the printed information but I cannot get > the text to look uniform at all. > > > Here is my code: > > > # Print infomation > print("The cost of the carpet is $", format(subtotal,'9,.2f')) > print("The flat fee is $", format(fee,'9,.2f')) > print("The tax is $", format(tax_rate,'9,.2f')) > print("The total due is $", format(total_due,'9,.2f')) > Have you tried lining it up in the source? # Print infomation print("The cost of the carpet is $", format(subtotal,'9,.2f')) print("The flat fee is $", format(fee,'9,.2f')) print("The tax is $", format(tax_rate,'9,.2f')) print("The total due is $", format(total_due,'9,.2f')) The format() method can handle variability in the floating point number, but it does nothing to guess what else you put on the line. Does that help? -- DaveA From __peter__ at web.de Thu Sep 19 12:05:17 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Sep 2013 12:05:17 +0200 Subject: [Tutor] How to add modules? References: <1379577580.55612.YahooMailNeo@web193805.mail.sg3.yahoo.com> Message-ID: Naman Kothari wrote: > Can you please suggest a link from where i can download SendKeys module > for python. Also provide an explanation to add the module to my library. > PS: I am a Windows user. I'd start installing a tool called "pip". I suggest that you follow the instructions given here: http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows The easiest way seems to be (quoting the above page) """ Aug 2013 Update: These answers are outdated or otherwise wordy and difficult. In short: Download: Setuptools: https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py Pip: https://raw.github.com/pypa/pip/master/contrib/get-pip.py Inspect files to confirm they aren't malicious. Open a console in the download folder as Admin and run... python ez_setup.py python get-pip.py The new binaries easy_install.exe and pip.exe will be found in the "%ProgramFiles%\PythonXX\Scripts" folder (or similar), which is likely not in your PATH. I recommend adding it. """ As I'm not a windows user have no first-hand experience with the above. Once you have pip installed you can search the Python package index (aka "Cheese Shop", ) with $ pip search sendkeys SendKeys - An implementation of Visual Basic's SendKeys function and then install the module with $ pip install SendKeys (Don't type "$", it is the prompt on Unix terminals, on Windows you will see something like "C:\" instead) As always, as you are installing other people's code they are free to do arbitrary things with your computer. This includes destroying or stealing sensitive data. From bgailer at gmail.com Thu Sep 19 15:48:47 2013 From: bgailer at gmail.com (bob gailer) Date: Thu, 19 Sep 2013 09:48:47 -0400 Subject: [Tutor] Field Width In-Reply-To: References: Message-ID: <523B00BF.2030301@gmail.com> On 9/18/2013 12:50 PM, Jenny Allar wrote: > I'm only a few days in to learning Python, so please bear with me. That's what we are here for. > > I need to line up the decimals on the printed information but I cannot > get the text to look uniform at all. Suggestions to help us help you. - post only the relevant code. In this case that is: print("The cost of the carpet is $", format(subtotal,'9,.2f')) print("The flat fee is $", format(fee,'9,.2f')) print("The tax is $", format(tax_rate,'9,.2f')) print("The total due is $", format(total_due,'9,.2f')) - When you get unexpected results post them as well. - what OS are you using, version on Python, what are you using to write and run your code? Now for the answer: You have used tabs to align the text. This will often fail, as each output "window" has its own way of interpreting tabs. Convert the tabs to spaces. Even better provide formatting directives for the text as well as the number. I prefer Python's original format (%): print("%-30s$%9.2f" % ("The cost of the carpet is ", subtotal)) % start of first format specification - = left justify 30 = field length %s = treat value as string $ = itself % start of seconb format specification 9.2f = same meaning as in format() % - format operator ("The cost of the carpet is ", subtotal) = tuple of values to be formatted. HTH -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 19 14:37:44 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 19 Sep 2013 08:37:44 -0400 Subject: [Tutor] How to add modules? In-Reply-To: References: <1379577580.55612.YahooMailNeo@web193805.mail.sg3.yahoo.com> Message-ID: On Thu, Sep 19, 2013 at 6:05 AM, Peter Otten <__peter__ at web.de> wrote: > As I'm not a windows user have no first-hand experience with the above. Once > you have pip installed you can search the Python package index (aka "Cheese > Shop", ) with pip requires a C compiler, such as VC++ or MinGW, in order to install source packages that include C extensions. pip doesn't support exe installers, but these can be converted to the Wheel format that pip 1.4 supports. https://pypi.python.org/pypi/wheel pip is great for virtual environments. But for system installations, it's simpler to use exe/msi installers that can be uninstalled from the Windows control panel. > $ pip search sendkeys > SendKeys - An implementation of Visual Basic's SendKeys > function Christoph Gohlke distributes a Python 2.7 installer for SendKeys: http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys The SendKeys site on rutherfurd.net is down, but archived (2012-10-25): http://web.archive.org/web/20121025123135/http://www.rutherfurd.net/python/sendkeys SendKeys on Bitbucket (last updated: 2011-09-16): https://bitbucket.org/orutherfurd/sendkeys Reimplementing the _sendkeys.c extension module with ctypes would be a simple project. It uses the following functions from user32.dll: keybd_event VkKeyScanA MapVirtualKeyA GetKeyboardState Keyboard Input Functions: http://msdn.microsoft.com/en-us/library/ff468859 From fluca1978 at infinito.it Thu Sep 19 14:20:50 2013 From: fluca1978 at infinito.it (Luca Ferrari) Date: Thu, 19 Sep 2013 14:20:50 +0200 Subject: [Tutor] Copy and paste python on Microsoft word In-Reply-To: References: Message-ID: On Wed, Sep 18, 2013 at 6:59 AM, Sammy Cornet wrote: > I'm using python 3.3.0, I have made a program on my script and output it. I have tried several times to copy and paste the output and the script on Microsoft word, every time I select the part that I need and right click on it, this message appears: go to the file/line. It provides me no access to copy and paste them. Please, can someone help me? As other said this is a behaviour tied to the IDE you are using. I would be using Emacs to run the program, outputting the result into an org file and then converting it into a RTF or alike document. Luca From i.sheeha at gmail.com Thu Sep 19 13:43:20 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Thu, 19 Sep 2013 13:43:20 +0200 Subject: [Tutor] Tutor Digest, Vol 115, Issue 35 In-Reply-To: References: Message-ID: I'm especially interested in SOAP and XMLRPC, for now. On Thu, Sep 19, 2013 at 11:24 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Web Services with python (Alan Gauld) > 2. Re: Copy and paste python on Microsoft word (Alan Gauld) > 3. Re: flask/sqlite3 problem - 'OperationalError: no such > table'? (Timo) > 4. Re: flask/sqlite3 problem - 'OperationalError: no such > table'? (Alan Gauld) > 5. Field Width (Jenny Allar) > 6. How to add modules? (Naman Kothari) > 7. Re: Field Width (Peter Otten) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 18 Sep 2013 17:55:34 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Web Services with python > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 18/09/13 10:05, Ismar Sehic wrote: > > Hello, can someone point me to some good guality resources to learn Web > > Services with Python?with some exaples, tutorials, exercises and such. > > > Python can do web services just fine both as server or > client. But what kind of web service? > > REST? > SOAP? > XMLRPC? > AJAX? > > What do you want to do then we can point you in a > useful direction. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 2 > Date: Wed, 18 Sep 2013 17:57:58 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Copy and paste python on Microsoft word > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 18/09/13 05:59, Sammy Cornet wrote: > > I'm using python 3.3.0, I have made a program on my > > script and output it. I have tried several times to > > copy and paste the output and the script on Microsoft word, > > How are you creating and running your script? > I'm guessing this is an IDE issue rather than > a python one, but we need to know what toolset > you are using. > > How do you create the program? What tool do you > use to write the code? How do you run the program? > Where does the output appear? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 3 > Date: Wed, 18 Sep 2013 19:13:10 +0200 > From: Timo > To: tutor at python.org > Subject: Re: [Tutor] flask/sqlite3 problem - 'OperationalError: no > such table'? > Message-ID: <5239DF26.6070505 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Op 18-09-13 15:37, Alan Gauld schreef: > > On 18/09/13 09:10, memilanuk wrote: > > > > > >> def main(): > >> g.db = connect_db() > >> cur = g.db.execute('SELECT * FROM posts') > > > > You are trying to execute on the database rather > > than on a cursor. You need to create a cursor > > first to hold your results. > > > > Something like; > > > > cur = g.db.cursor() > > cur.execute(.....) > Not really. > > sqlite3.connect() returns a sqlite3.Connection object which has a > execute method. It will create a cursor object for you. > > Cheers, > Timo > > > > > HTH > > > > ------------------------------ > > Message: 4 > Date: Wed, 18 Sep 2013 22:34:12 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] flask/sqlite3 problem - 'OperationalError: no > such table'? > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 18/09/13 18:13, Timo wrote: > > >> You are trying to execute on the database rather > >> than on a cursor. You need to create a cursor > >> first to hold your results. > >> > >> Something like; > >> > >> cur = g.db.cursor() > >> cur.execute(.....) > > Not really. > > > > sqlite3.connect() returns a sqlite3.Connection object which has a > > execute method. It will create a cursor object for you. > > Interesting. > I didn't know that, I've always created a separate cursor > explicitly. But that's probably because I'm used to > Oracle which requires me to do that from C++ > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 5 > Date: Wed, 18 Sep 2013 12:50:51 -0400 > From: Jenny Allar > To: tutor at python.org > Subject: [Tutor] Field Width > Message-ID: > < > CADXZeCYO94G9JDzkYwad6azM+_cKKZp67ZP1_Rq7oB78ObRcfA at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I'm only a few days in to learning Python, so please bear with me. > > I need to line up the decimals on the printed information but I cannot get > the text to look uniform at all. > > > Here is my code: > > def main(): > > # Set up constants for cost per yard, flat fee, and tax rate > cost_carpet = 5.50 > fee = 25 > tax = .06 > > # Ask for yards needed > yards_needed = float(input('Please enter the total number of yards > needed ')) > > # Calculate subtotal > subtotal = yards_needed * cost_carpet + fee > > # Calculate tax_rate > tax_rate = subtotal * tax > > # Calculate total_due > total_due = subtotal + tax_rate > > # Print blank line > print() > > # Print infomation > print("The cost of the carpet is $", format(subtotal,'9,.2f')) > print("The flat fee is $", format(fee,'9,.2f')) > print("The tax is $", format(tax_rate,'9,.2f')) > print("The total due is $", format(total_due,'9,.2f')) > > > main () > > > > > Thank you in advance, > Jenny > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130918/4bcabc75/attachment-0001.html > > > > ------------------------------ > > Message: 6 > Date: Thu, 19 Sep 2013 15:59:40 +0800 (SGT) > From: Naman Kothari > To: "tutor at python.org" > Subject: [Tutor] How to add modules? > Message-ID: > <1379577580.55612.YahooMailNeo at web193805.mail.sg3.yahoo.com> > Content-Type: text/plain; charset="utf-8" > > Can you please suggest a link from where i can download SendKeys module > for python. Also provide an explanation to add the module to my library. > PS: I am a Windows user. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130919/d48e158e/attachment-0001.html > > > > ------------------------------ > > Message: 7 > Date: Thu, 19 Sep 2013 11:24:20 +0200 > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Subject: Re: [Tutor] Field Width > Message-ID: > Content-Type: text/plain; charset="ISO-8859-1" > > Jenny Allar wrote: > > > I'm only a few days in to learning Python, so please bear with me. > > Welcome! > > > I need to line up the decimals on the printed information but I cannot > get > > the text to look uniform at all. > > > print("The cost of the carpet is $", format(subtotal,'9,.2f')) > > print("The flat fee is $", format(fee,'9,.2f')) > > Just add some spaces manually: > > print("The cost of the carpet is $", format(subtotal,'9,.2f')) > print("The flat fee is $", format(fee,'9,.2f')) > > This is usually written as > > print("The cost of the carpet is $ {:9,.2f}".format(subtotal)) > print("The flat fee is $ {:9,.2f}".format(fee)) > > If this is not what you want you need to give more details; for instance: > the above won't look "uniform" when it is displayed in a proportional font. > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 115, Issue 35 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.sheeha at gmail.com Thu Sep 19 14:21:51 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Thu, 19 Sep 2013 14:21:51 +0200 Subject: [Tutor] Tutor Digest, Vol 115, Issue 35 In-Reply-To: References: Message-ID: also, i would like to know more about XML - what is the best way to parse it, and send soap calls for xml methods.i've used lxml to modify some xml files which i need to send to a server, as a request.what is the logic behind that?how can i do that with, for example, suds python library? On Thu, Sep 19, 2013 at 1:43 PM, Ismar Sehic wrote: > I'm especially interested in SOAP and XMLRPC, for now. > > > On Thu, Sep 19, 2013 at 11:24 AM, wrote: > >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> https://mail.python.org/mailman/listinfo/tutor >> or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >> You can reach the person managing the list at >> tutor-owner at python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: >> >> 1. Re: Web Services with python (Alan Gauld) >> 2. Re: Copy and paste python on Microsoft word (Alan Gauld) >> 3. Re: flask/sqlite3 problem - 'OperationalError: no such >> table'? (Timo) >> 4. Re: flask/sqlite3 problem - 'OperationalError: no such >> table'? (Alan Gauld) >> 5. Field Width (Jenny Allar) >> 6. How to add modules? (Naman Kothari) >> 7. Re: Field Width (Peter Otten) >> >> >> ---------------------------------------------------------------------- >> >> Message: 1 >> Date: Wed, 18 Sep 2013 17:55:34 +0100 >> From: Alan Gauld >> To: tutor at python.org >> Subject: Re: [Tutor] Web Services with python >> Message-ID: >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> On 18/09/13 10:05, Ismar Sehic wrote: >> > Hello, can someone point me to some good guality resources to learn Web >> > Services with Python?with some exaples, tutorials, exercises and such. >> >> >> Python can do web services just fine both as server or >> client. But what kind of web service? >> >> REST? >> SOAP? >> XMLRPC? >> AJAX? >> >> What do you want to do then we can point you in a >> useful direction. >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.flickr.com/photos/alangauldphotos >> >> >> >> ------------------------------ >> >> Message: 2 >> Date: Wed, 18 Sep 2013 17:57:58 +0100 >> From: Alan Gauld >> To: tutor at python.org >> Subject: Re: [Tutor] Copy and paste python on Microsoft word >> Message-ID: >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> On 18/09/13 05:59, Sammy Cornet wrote: >> > I'm using python 3.3.0, I have made a program on my >> > script and output it. I have tried several times to >> > copy and paste the output and the script on Microsoft word, >> >> How are you creating and running your script? >> I'm guessing this is an IDE issue rather than >> a python one, but we need to know what toolset >> you are using. >> >> How do you create the program? What tool do you >> use to write the code? How do you run the program? >> Where does the output appear? >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.flickr.com/photos/alangauldphotos >> >> >> >> ------------------------------ >> >> Message: 3 >> Date: Wed, 18 Sep 2013 19:13:10 +0200 >> From: Timo >> To: tutor at python.org >> Subject: Re: [Tutor] flask/sqlite3 problem - 'OperationalError: no >> such table'? >> Message-ID: <5239DF26.6070505 at gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> Op 18-09-13 15:37, Alan Gauld schreef: >> > On 18/09/13 09:10, memilanuk wrote: >> > >> > >> >> def main(): >> >> g.db = connect_db() >> >> cur = g.db.execute('SELECT * FROM posts') >> > >> > You are trying to execute on the database rather >> > than on a cursor. You need to create a cursor >> > first to hold your results. >> > >> > Something like; >> > >> > cur = g.db.cursor() >> > cur.execute(.....) >> Not really. >> >> sqlite3.connect() returns a sqlite3.Connection object which has a >> execute method. It will create a cursor object for you. >> >> Cheers, >> Timo >> >> > >> > HTH >> >> >> >> ------------------------------ >> >> Message: 4 >> Date: Wed, 18 Sep 2013 22:34:12 +0100 >> From: Alan Gauld >> To: tutor at python.org >> Subject: Re: [Tutor] flask/sqlite3 problem - 'OperationalError: no >> such table'? >> Message-ID: >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> On 18/09/13 18:13, Timo wrote: >> >> >> You are trying to execute on the database rather >> >> than on a cursor. You need to create a cursor >> >> first to hold your results. >> >> >> >> Something like; >> >> >> >> cur = g.db.cursor() >> >> cur.execute(.....) >> > Not really. >> > >> > sqlite3.connect() returns a sqlite3.Connection object which has a >> > execute method. It will create a cursor object for you. >> >> Interesting. >> I didn't know that, I've always created a separate cursor >> explicitly. But that's probably because I'm used to >> Oracle which requires me to do that from C++ >> >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.flickr.com/photos/alangauldphotos >> >> >> >> ------------------------------ >> >> Message: 5 >> Date: Wed, 18 Sep 2013 12:50:51 -0400 >> From: Jenny Allar >> To: tutor at python.org >> Subject: [Tutor] Field Width >> Message-ID: >> < >> CADXZeCYO94G9JDzkYwad6azM+_cKKZp67ZP1_Rq7oB78ObRcfA at mail.gmail.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> I'm only a few days in to learning Python, so please bear with me. >> >> I need to line up the decimals on the printed information but I cannot get >> the text to look uniform at all. >> >> >> Here is my code: >> >> def main(): >> >> # Set up constants for cost per yard, flat fee, and tax rate >> cost_carpet = 5.50 >> fee = 25 >> tax = .06 >> >> # Ask for yards needed >> yards_needed = float(input('Please enter the total number of yards >> needed ')) >> >> # Calculate subtotal >> subtotal = yards_needed * cost_carpet + fee >> >> # Calculate tax_rate >> tax_rate = subtotal * tax >> >> # Calculate total_due >> total_due = subtotal + tax_rate >> >> # Print blank line >> print() >> >> # Print infomation >> print("The cost of the carpet is $", format(subtotal,'9,.2f')) >> print("The flat fee is $", format(fee,'9,.2f')) >> print("The tax is $", format(tax_rate,'9,.2f')) >> print("The total due is $", format(total_due,'9,.2f')) >> >> >> main () >> >> >> >> >> Thank you in advance, >> Jenny >> -------------- next part -------------- >> An HTML attachment was scrubbed... >> URL: < >> http://mail.python.org/pipermail/tutor/attachments/20130918/4bcabc75/attachment-0001.html >> > >> >> ------------------------------ >> >> Message: 6 >> Date: Thu, 19 Sep 2013 15:59:40 +0800 (SGT) >> From: Naman Kothari >> To: "tutor at python.org" >> Subject: [Tutor] How to add modules? >> Message-ID: >> <1379577580.55612.YahooMailNeo at web193805.mail.sg3.yahoo.com> >> Content-Type: text/plain; charset="utf-8" >> >> Can you please suggest a link from where i can download SendKeys module >> for python. Also provide an explanation to add the module to my library. >> PS: I am a Windows user. >> -------------- next part -------------- >> An HTML attachment was scrubbed... >> URL: < >> http://mail.python.org/pipermail/tutor/attachments/20130919/d48e158e/attachment-0001.html >> > >> >> ------------------------------ >> >> Message: 7 >> Date: Thu, 19 Sep 2013 11:24:20 +0200 >> From: Peter Otten <__peter__ at web.de> >> To: tutor at python.org >> Subject: Re: [Tutor] Field Width >> Message-ID: >> Content-Type: text/plain; charset="ISO-8859-1" >> >> Jenny Allar wrote: >> >> > I'm only a few days in to learning Python, so please bear with me. >> >> Welcome! >> >> > I need to line up the decimals on the printed information but I cannot >> get >> > the text to look uniform at all. >> >> > print("The cost of the carpet is $", format(subtotal,'9,.2f')) >> > print("The flat fee is $", format(fee,'9,.2f')) >> >> Just add some spaces manually: >> >> print("The cost of the carpet is $", format(subtotal,'9,.2f')) >> print("The flat fee is $", format(fee,'9,.2f')) >> >> This is usually written as >> >> print("The cost of the carpet is $ {:9,.2f}".format(subtotal)) >> print("The flat fee is $ {:9,.2f}".format(fee)) >> >> If this is not what you want you need to give more details; for instance: >> the above won't look "uniform" when it is displayed in a proportional >> font. >> >> >> >> ------------------------------ >> >> Subject: Digest Footer >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> https://mail.python.org/mailman/listinfo/tutor >> >> >> ------------------------------ >> >> End of Tutor Digest, Vol 115, Issue 35 >> ************************************** >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jennyallar at gmail.com Thu Sep 19 14:09:55 2013 From: jennyallar at gmail.com (Jenny Allar) Date: Thu, 19 Sep 2013 08:09:55 -0400 Subject: [Tutor] Field Width In-Reply-To: References: Message-ID: Thanks, Dave. Your statement "it does nothing to guess what else you put on the line" was like a light bulb that went off in my head. I think I was relating the field width to a left, center, or right justification, and that's not the case at all. Well now I feel silly! Thanks, Jenny On Thu, Sep 19, 2013 at 5:24 AM, Dave Angel wrote: > On 18/9/2013 12:50, Jenny Allar wrote: > > > I'm only a few days in to learning Python, so please bear with me. > > > > I need to line up the decimals on the printed information but I cannot > get > > the text to look uniform at all. > > > > > > Here is my code: > > > > > > > > > # Print infomation > > print("The cost of the carpet is $", format(subtotal,'9,.2f')) > > print("The flat fee is $", format(fee,'9,.2f')) > > print("The tax is $", format(tax_rate,'9,.2f')) > > print("The total due is $", format(total_due,'9,.2f')) > > > > Have you tried lining it up in the source? > > # Print infomation > print("The cost of the carpet is $", format(subtotal,'9,.2f')) > print("The flat fee is $", format(fee,'9,.2f')) > print("The tax is $", format(tax_rate,'9,.2f')) > print("The total due is $", format(total_due,'9,.2f')) > > The format() method can handle variability in the floating point number, > but it does nothing to guess what else you put on the line. > > Does that help? > > > -- > DaveA > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 19 20:03:32 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Sep 2013 19:03:32 +0100 Subject: [Tutor] Web services was: Re: Tutor Digest, Vol 115, Issue 35 In-Reply-To: References: Message-ID: On 19/09/13 12:43, Ismar Sehic wrote: > I'm especially interested in SOAP and XMLRPC, for now. Please do not forward the entire digest. Some people have to pay by the byte and it also clutters up inboxes. Also please use a sensible subject line rather than: Re: Tutor Digest, Vol 115, Issue 35 As for SOAP and XMLRPC there are modules for both and tutorials on their use. Start here: XMLRPC is supported in the standard library: http://docs.python.org/2/library/xmlrpclib.html And SOAP has SOAPpy www.python.org/pyvault/SRPMS/.../python-soappy-0-0.11.6-1.html? Its quite old but may lead to more modern sources. HTH > > On Thu, Sep 19, 2013 at 11:24 AM, > wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Web Services with python (Alan Gauld) > 2. Re: Copy and paste python on Microsoft word (Alan Gauld) > 3. Re: flask/sqlite3 problem - 'OperationalError: no such > table'? (Timo) > 4. Re: flask/sqlite3 problem - 'OperationalError: no such > table'? (Alan Gauld) > 5. Field Width (Jenny Allar) > 6. How to add modules? (Naman Kothari) > 7. Re: Field Width (Peter Otten) > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From fomcl at yahoo.com Thu Sep 19 21:05:37 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 19 Sep 2013 12:05:37 -0700 (PDT) Subject: [Tutor] How to add modules? In-Reply-To: References: <1379577580.55612.YahooMailNeo@web193805.mail.sg3.yahoo.com> Message-ID: <1379617537.30105.YahooMailNeo@web163804.mail.gq1.yahoo.com> ________________________________ > From: eryksun >To: Naman Kothari >Cc: tutor at python.org >Sent: Thursday, September 19, 2013 2:37 PM >Subject: Re: [Tutor] How to add modules? > > >On Thu, Sep 19, 2013 at 6:05 AM, Peter Otten <__peter__ at web.de> wrote: >> As I'm not a windows user have no first-hand experience with the above. Once >> you have pip installed you can search the Python package index (aka "Cheese >> Shop", ) with > >pip requires a C compiler, such as VC++ or MinGW, in order to install >source packages that include C extensions. > >pip doesn't support exe installers, but these can be converted to the >Wheel format that pip 1.4 supports. > >https://pypi.python.org/pypi/wheel > >pip is great for virtual environments. But for system installations, >it's simpler to use exe/msi installers that can be uninstalled from >the Windows control panel. > >> $ pip search sendkeys >> SendKeys? ? ? ? ? ? ? ? ? - An implementation of Visual Basic's SendKeys >> function > >Christoph Gohlke distributes a Python 2.7 installer for SendKeys: >http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys > >The SendKeys site on rutherfurd.net is down, but archived (2012-10-25): >http://web.archive.org/web/20121025123135/http://www.rutherfurd.net/python/sendkeys I recently used this version: http://code.google.com/p/sendkeys-ctypes/downloads/list SendKeys started as a ctypes implementation, then as something else, then as a reimplementation of ctypes. This is the latter. I don't recall the details but I chose the ctypes reimplementation because the other didn't work for me. Just imported it after adding the path to sys.path. Worked nicely but it's highly sensitive to interrupting screens such as chat/mail notifications. From amitsaha.in at gmail.com Sun Sep 22 02:18:23 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 22 Sep 2013 10:18:23 +1000 Subject: [Tutor] Checking that the input is float()-able Message-ID: Hi all, I want my program to report an error if anything other than a number which I can then convert to float using float() is entered as input: # Python 3 try: a = float(input('Enter a number: ')) except ValueError: print('Wrong input') else: print('Right input') This seems to do the job for me. python3 input_number.py $ Enter a number: 34.563 Right input $ python3 input_number.py Enter a number: abcd Wrong input $ python3 input_number.py Enter a number: {} Wrong input I have two queries: - Is this the best way to do this? - Is this is the easiest way to tell a beginner to do this? (Even though it introduces try..except) Thanks for any comments. Best, Amit. -- http://echorand.me From joel.goldstick at gmail.com Sun Sep 22 02:26:27 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 21 Sep 2013 20:26:27 -0400 Subject: [Tutor] Checking that the input is float()-able In-Reply-To: References: Message-ID: On Sat, Sep 21, 2013 at 8:18 PM, Amit Saha wrote: > Hi all, > > I want my program to report an error if anything other than a number > which I can then convert to float using float() is entered as input: > > # Python 3 > try: > a = float(input('Enter a number: ')) > > except ValueError: > print('Wrong input') > else: > print('Right input') > > > This seems to do the job for me. > > python3 input_number.py > $ Enter a number: 34.563 > Right input > > $ python3 input_number.py > Enter a number: abcd > Wrong input > > $ python3 input_number.py > Enter a number: {} > Wrong input > > > I have two queries: > > - Is this the best way to do this? > - Is this is the easiest way to tell a beginner to do this? (Even > though it introduces try..except) > I think its exactly the right way. Python philosophy is ask for forgiveness not permission. This does just that. Assume things are as you like and if they aren't, raise an exception. > > Thanks for any comments. > > Best, > Amit. > > > > -- > http://echorand.me > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Sep 22 03:28:44 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 22 Sep 2013 11:28:44 +1000 Subject: [Tutor] Checking that the input is float()-able In-Reply-To: References: Message-ID: <20130922012839.GB19939@ando> On Sun, Sep 22, 2013 at 10:18:23AM +1000, Amit Saha wrote: > Hi all, > > I want my program to report an error if anything other than a number > which I can then convert to float using float() is entered as input: > > # Python 3 > try: > a = float(input('Enter a number: ')) > > except ValueError: > print('Wrong input') > else: > print('Right input') > > > This seems to do the job for me. [...] > I have two queries: > > - Is this the best way to do this? > - Is this is the easiest way to tell a beginner to do this? (Even > though it introduces try..except) Yes, and yes. -- Steven From amitsaha.in at gmail.com Sun Sep 22 05:01:17 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 22 Sep 2013 13:01:17 +1000 Subject: [Tutor] A demon command line interpreter using the 'cmd' module Message-ID: I wrote this demo command line interpreter to demonstrate using the cmd module: https://gist.github.com/amitsaha/6047955 $ python3 demo_cmd_interpreter.py Welcome to Dummy shell. Type help or ? to list commands. dummyshell>> help Documented commands (type help ): ======================================== exit help shell whoami dummyshell>> whoami gene dummyshell>> !date Sun Sep 22 13:00:01 EST 2013 dummyshell>> quit Bye! To learn more about the cmd module: http://docs.python.org/3/library/cmd.html Hope someone finds this useful in their learning/teaching. Best, Amit. -- http://echorand.me From amitsaha.in at gmail.com Sun Sep 22 23:27:25 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 23 Sep 2013 07:27:25 +1000 Subject: [Tutor] Checking that the input is float()-able In-Reply-To: <20130922012839.GB19939@ando> References: <20130922012839.GB19939@ando> Message-ID: On Sun, Sep 22, 2013 at 11:28 AM, Steven D'Aprano wrote: > On Sun, Sep 22, 2013 at 10:18:23AM +1000, Amit Saha wrote: >> Hi all, >> >> I want my program to report an error if anything other than a number >> which I can then convert to float using float() is entered as input: >> >> # Python 3 >> try: >> a = float(input('Enter a number: ')) >> >> except ValueError: >> print('Wrong input') >> else: >> print('Right input') >> >> >> This seems to do the job for me. > [...] >> I have two queries: >> >> - Is this the best way to do this? >> - Is this is the easiest way to tell a beginner to do this? (Even >> though it introduces try..except) > > Yes, and yes. > > Thank you Joel and Steven. Best, Amit. -- http://echorand.me From arronjsutcliffe at gmail.com Sun Sep 22 00:44:58 2013 From: arronjsutcliffe at gmail.com (Arron Sutcliffe) Date: Sat, 21 Sep 2013 23:44:58 +0100 Subject: [Tutor] Expected indented block error Message-ID: Hi i have been working on a currency converter for school and i have been having a hard time with this syntax error "Expected indented block" and i don't understand why it isn't working. i am fairly new to Python thus my sloppy and unfinished code hope you can help :) My code - v_fallback = 1 while v_fallback == 1: print("Please enter your current currency") v_current = input() if v_current == ("USD" or "usd" or "US Dollars" or "us dollars"): print("Please enter the name of the currency you wish to convert to") print("Your options are GBP, EUR, INR, AUD, CAD, AED or BACK to return to the Main Menu") v_final = input() if v_final ==("GBP" or "gpb"): if v_final == ("EUR" or "eur"): if v_final == ("INR" or "inr"): if v_final == ("AUD" or "aud"): if v_final == ("CAD" or "cad"): if v_final == ("AED" or "aed"): if v_final == ("BACK" or "back"): else: print ("ERROR - Please enter a valid currency, if incorrect currency is entered again program will close") print("Your options are GBP, EUR, INR, AUD, CAD, AED or BACK to return to the main menu") v_final = input() if v_final == ("GBP" or "gbp"): if v_final == ("EUR" or "eur"): if v_final == ("INR" or "inr"): if v_final == ("AUD" or "aud"): if v_final ==("CAD" or "cad"): if v_final == ("AED" or "aed"): if v_final == ("BACK" or "back"): else print ("ERROR - Program will close"): v_fallback = 0 #if v_current == ("GBP" or "gbp" or "pounds" or "Pounds" or "pounds sterling"): #v_exrate = #v_fallback = 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.sheeha at gmail.com Fri Sep 20 15:25:54 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Fri, 20 Sep 2013 15:25:54 +0200 Subject: [Tutor] Suds, Lxml - sending an xml request Message-ID: i'm probably very annoying and boring with these python web service :)and sorry for the previous message reply subject,wont happen again... the thing is, i'm provided with some service provider documentation, including xml request example, xml response example, wsdl file for the protocol defintion, and xsd file for every request type. i've played around with LXML and SUDS, and i got this : xml parsing (i don't really know if i need this, but i made it just to see how it works ): try: > from lxml import etree > except ImportError: > import xml.etree.ElementTree as etree > # > document = etree.parse("HotelValuedAvailRQ.xml") > root = document.getroot() > #namespaces used > xmlns = '' > xsi = '{http://www.hotelbeds.com/schemas/2005/06/messages}' > # > user = document.find('//{namespace}User'.format(namespace=namespace)) > user.text = '' #set hotelbeds user(text) > > password = > document.find('//{namespace}Password'.format(namespace=namespace)) > password.text = '' #set hotelbeds password(text) > > language = > document.find('//{namespace}Language'.format(namespace=namespace)) > language.text = '' #set hotelbeds response language(text) > > > #set number of pages for xml response(attribute) > PaginationData = root[2].set('pageNumber', '4') > #set check in date, format :'20130509' > CheckInDate = root[3].set('date', '') > #set check out date > CheckOutDate = root[4].set('date', '') > #set dest code, set dest type > Destination = root[5].set('code', ''); root[5].set('type', '') > > #set the room count > RoomCount = > document.find('//{namespace}RoomCount'.format(namespace=namespace)) > RoomCount.text = '' > #set number of adults > AdultCount = > document.find('//{namespace}AdultCount'.format(namespace=namespace)) > RoomCount.text = '' > #set number of children > ChildCount = > document.find('//{namespace}ChildCount'.format(namespace=namespace)) > ChildCount.text = '3' > > document.write('HotelValuedAvailRQ.xml') > print '--->Changes saved' > > and i also made this, some suds experiment : import logging > logging.basicConfig(level = logging.INFO) > logging.getLogger('suds.client').setLevel(logging.DEBUG) > #logging.getLogger('suds.wsdl').setLevel(logging.DEBUG) > #logging.getLogger('suds.transport').setLevel(logging.DEBUG) > #logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) > logging.getLogger('suds.wsse').setLevel(logging.DEBUG) > from suds.client import Client > url = 'http://xxx.xxx.xxx.xxx/appservices/ws/FrontendService?wsdl' > client = Client(url) > print client > which gives me following result : > Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: > R699-20100913 > > Service ( FrontendServiceService ) tns=" > http://www.hotelbeds.com/wsdl/2005/06" > Prefixes (0) > Ports (1): > (FrontendService) > Methods (34): > cancelProtectionAdd(xs:anyType cancelProtectionAdd, ) > cancelProtectionRemove(xs:anyType cancelProtectionRemove, ) > getCancelProtectionAvail(xs:anyType getCancelProtectionAvail, ) > getCarCountryList(xs:anyType getCarCountryList, ) > getCarInfoSet(xs:anyType getCarInfoSet, ) > getCarValuedAvail(xs:anyType getCarValuedAvail, ) > getCountryList(xs:anyType getCountryList, ) > getDestinationGroupList(xs:anyType getDestinationGroupList, ) > getHotelBoardGroupList(xs:anyType getHotelBoardGroupList, ) > getHotelBoardList(xs:anyType getHotelBoardList, ) > getHotelCategoryGroupList(xs:anyType > getHotelCategoryGroupList, ) > getHotelCategoryList(xs:anyType getHotelCategoryList, ) > getHotelCountryList(xs:anyType getHotelCountryList, ) > getHotelDetail(xs:anyType getHotelDetail, ) > getHotelList(xs:anyType getHotelList, ) > getHotelRoomTypeGroupList(xs:anyType > getHotelRoomTypeGroupList, ) > getHotelValuedAvail(xs:anyType getHotelValuedAvail, ) > getIncomingOfficeDetail(xs:anyType getIncomingOfficeDetail, ) > getIncomingOfficeList(xs:anyType getIncomingOfficeList, ) > getPurchaseDetail(xs:anyType getPurchaseDetail, ) > getPurchaseList(xs:anyType getPurchaseList, ) > getTicketAvail(xs:anyType getTicketAvail, ) > getTicketClassificationList(xs:anyType > getTicketClassificationList, ) > getTicketCountryList(xs:anyType getTicketCountryList, ) > getTicketDetail(xs:anyType getTicketDetail, ) > getTicketValuation(xs:anyType getTicketValuation, ) > getTransferCountryList(xs:anyType getTransferCountryList, ) > getTransferValuedAvail(xs:anyType getTransferValuedAvail, ) > getZoneGroupList(xs:anyType getZoneGroupList, ) > purchaseCancel(xs:anyType purchaseCancel, ) > purchaseConfirm(xs:anyType purchaseConfirm, ) > purchaseFlush(xs:anyType purchaseFlush, ) > serviceAdd(xs:anyType serviceAdd, ) > serviceRemove(xs:anyType serviceRemove, ) > Types (0): > > can you tell me, what next?i'm reading suds documentation, i have some clue about the next step, but i'm not sure.do i generate xml request from wsdl file's methods or do i edit existing xml files provided by the provider, and send them, and what about xsd files?i'm,interested only in getHotelValuedAvail,serviceAdd,serviceRemove,and purchaseFlush methods. and sorry if the message is too big... -------------- next part -------------- An HTML attachment was scrubbed... URL: From jugurtha.hadjar at gmail.com Fri Sep 20 16:50:10 2013 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Fri, 20 Sep 2013 15:50:10 +0100 Subject: [Tutor] AntiSpam measures circumventing Message-ID: <523C60A2.3090902@gmail.com> Hello, I shared some assembly code (microcontrollers) and I had a comment wit my e-mail address for contact purposes. Supposing my name is John Doe and the e-mail is john.doe at hotmail.com, my e-mail was written like this: REMOVEMEjohn.doSPAMeSPAM at REMOVEMEhotmail.com' With a note saying to remove the capital letters. Now, I wrote this : for character in my_string: ... if (character == character.upper()) and (character !='@') and (character != '.'): ... my_string = my_string.replace(character,'') And the end result was john.doe at hotmail.com. Is there a better way to do that ? Without using regular expressions (Looked *really* ugly and it doesn't really make sense, unlike the few lines I've written, which are obvious even to a beginner like me). I obviously don't like SPAM, but I just thought "If I were a spammer, how would I go about it". Eventually, some algorithm of detecting the johndoehotmailcom must exist. Also, what would in your opinion make it *harder* for a non-human to retrieve the original e-mail address? Maybe a function with no inverse function ? Generating an image that can't be converted back to text, etc.. If this is off-topic, you can just answer the "what is a better way to do that" part. Thanks, -- ~Jugurtha Hadjar, From znxm0i at yahoo.com Sat Sep 21 05:26:41 2013 From: znxm0i at yahoo.com (znxm0i at yahoo.com) Date: Fri, 20 Sep 2013 20:26:41 -0700 (PDT) Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: <1379708827.67739.BPMail_high_noncarrier@web184705.mail.ne1.yahoo.com> References: <1379708827.67739.BPMail_high_noncarrier@web184705.mail.ne1.yahoo.com> Message-ID: <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> Can anyone please help me figure out what I am NOT doing to make this program work properly.....PLEASE !! I need to be able to take the user input that is entered in the two graphical boxes of the first window and evaluate it to generate a graph chart which is suppose to display in the second window.? I am totally at a loss for what I am NOT doing, and I know it is something so simple that I am overlooking because I am making this harder that what it most likely really is. But I just cannot get it to work properly.? Please HELP !!!? Help me understand what I am doing wrong and how to fix it.? I believe I am on the right path but I'm becoming frustrated and discouraged.? I have attached a copy of the code I've compiled so far. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: futval_graph2.py Type: text/x-python Size: 1725 bytes Desc: not available URL: From chris at chrisdown.name Mon Sep 23 18:45:39 2013 From: chris at chrisdown.name (Chris Down) Date: Mon, 23 Sep 2013 18:45:39 +0200 Subject: [Tutor] AntiSpam measures circumventing In-Reply-To: <523C60A2.3090902@gmail.com> References: <523C60A2.3090902@gmail.com> Message-ID: <20130923164539.GA16403@chrisdown.name> On 2013-09-20 15:50, Jugurtha Hadjar wrote: > I obviously don't like SPAM, but I just thought "If I were a > spammer, how would I go about it". You wouldn't, it's not effective to do this. You would just grab plain text e-mail addresses and leave it at that, anyone who tries to obfuscate their e-mail address is not worth spamming anyway. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From alan.gauld at btinternet.com Mon Sep 23 19:14:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Sep 2013 18:14:48 +0100 Subject: [Tutor] Expected indented block error In-Reply-To: References: Message-ID: On 21/09/13 23:44, Arron Sutcliffe wrote: > Hi i have been working on a currency converter for school and i have > been having a hard time with this syntax error "Expected indented block" > and i don't understand why it isn't working. It tells you, it's expecting an indented block... > v_fallback = 1 > while v_fallback == 1: > print("Please enter your current currency") > v_current = input() > if v_current == ("USD" or "usd" or "US Dollars" or "us dollars"): > print("Please enter the name of the currency you wish to > convert to") > print("Your options are GBP, EUR, INR, AUD, CAD, AED or BACK to > return to the Main Menu") > v_final = input() > if v_final ==("GBP" or "gpb"): Python is expecting an indented block of code to do something when the if is true. So eoitrher you put some code here or... > if v_final == ("EUR" or "eur"): You indent this line. But thats probably a bad idea. > if v_final == ("INR" or "inr"): > if v_final == ("AUD" or "aud"): > if v_final == ("CAD" or "cad"): BTW these lines are almost certainly not doing what you think they are. This is not testing whether v_final is one of the values in the if tet, it is testing whether v_final has the same truth(boolewan0 vale as the expression (str1 or str2) which is always True. You probably want something like if v_final.upper() == "GBP": # do something or, more likely in this case: if v_final.upper() in ("GBP", "INR", "AUD", ...other values): #do this > if v_final == ("AED" or "aed"): > if v_final == ("BACK" or "back"): > else: > print ("ERROR - Please enter a valid currency, if incorrect > currency is entered again program will close") > print("Your options are GBP, EUR, INR, AUD, CAD, AED or > BACK to return to the main menu") > v_final = input() > if v_final == ("GBP" or "gbp"): > if v_final == ("EUR" or "eur"): > if v_final == ("INR" or "inr"): > if v_final == ("AUD" or "aud"): > if v_final ==("CAD" or "cad"): > if v_final == ("AED" or "aed"): > if v_final == ("BACK" or "back"): > else print ("ERROR - Program will close"): > v_fallback = 0 And there is a programming principle called DRY (Don't Repeat Yourself). You have the same set of tests here as above. Rather than limit the user to 2 goes you could wrap the tests into a while loop and only have them once. That way there is never any risk of them getting out of step with each other. (You could also encapsulate them in a function but you might not have covered functions yet!) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 23 19:21:03 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Sep 2013 18:21:03 +0100 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> References: <1379708827.67739.BPMail_high_noncarrier@web184705.mail.ne1.yahoo.com> <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> Message-ID: On 21/09/13 04:26, znxm0i at yahoo.com wrote: > Can anyone please help me figure out what I am NOT doing to make this > program work properly.....PLEASE !! First you need to tell us what "graphics" module you are using since there is no standard library module by that name. Second, you should probably ask for help on their forum since this list is really for those learning Python and its standard library. However, if we know the library we might be able to help or someone may have some experience. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From fomcl at yahoo.com Mon Sep 23 20:13:50 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 23 Sep 2013 11:13:50 -0700 (PDT) Subject: [Tutor] AntiSpam measures circumventing In-Reply-To: <523C60A2.3090902@gmail.com> References: <523C60A2.3090902@gmail.com> Message-ID: <1379960030.84358.YahooMailNeo@web163805.mail.gq1.yahoo.com> ----- Original Message ----- > From: Jugurtha Hadjar > To: tutor at python.org > Cc: > Sent: Friday, September 20, 2013 4:50 PM > Subject: [Tutor] AntiSpam measures circumventing > > Hello, > > I shared some assembly code (microcontrollers) and I had a comment wit > my e-mail address for contact purposes. > > Supposing my name is John Doe and the e-mail is john.doe at hotmail.com, my > e-mail was written like this: > > REMOVEMEjohn.doSPAMeSPAM at REMOVEMEhotmail.com' > > With a note saying to remove the capital letters. > > Now, I wrote this : > > for character in my_string: > ...? ? if (character == character.upper()) and (character !='@') and > (character != '.'): > ...? ? ? ? ? ? my_string = my_string.replace(character,'') > > > And the end result was john.doe at hotmail.com. > > Is there a better way to do that ? Without using regular expressions > (Looked *really* ugly and it doesn't really make sense, unlike the few > lines I've written, which are obvious even to a beginner like me). I used this a while ago. It's not Python, but it's effective:? http://www.jottings.com/obfuscator/ From fomcl at yahoo.com Mon Sep 23 21:28:10 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 23 Sep 2013 12:28:10 -0700 (PDT) Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' Message-ID: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> Hi, I just wanted to type "git status" in my Linux terminal but I made a typo and I got a long Python 3.3 traceback message. Just curious: What does it mean? gigt status Traceback (most recent call last): ? File "/usr/lib/python3.3/site.py", line 631, in ??? main() ? File "/usr/lib/python3.3/site.py", line 616, in main ??? known_paths = addusersitepackages(known_paths) ? File "/usr/lib/python3.3/site.py", line 284, in addusersitepackages ??? user_site = getusersitepackages() ? File "/usr/lib/python3.3/site.py", line 260, in getusersitepackages ??? user_base = getuserbase() # this will also set USER_BASE ? File "/usr/lib/python3.3/site.py", line 250, in getuserbase ??? USER_BASE = get_config_var('userbase') ? File "/usr/lib/python3.3/sysconfig.py", line 580, in get_config_var ??? return get_config_vars().get(name) ? File "/usr/lib/python3.3/sysconfig.py", line 530, in get_config_vars ??? _init_posix(_CONFIG_VARS) ? File "/usr/lib/python3.3/sysconfig.py", line 403, in _init_posix ??? from _sysconfigdata import build_time_vars ? File "/usr/lib/python3.3/_sysconfigdata.py", line 6, in ??? from _sysconfigdata_m import * ImportError: No module named '_sysconfigdata_m' ? Thank you! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Sep 23 22:00:16 2013 From: wprins at gmail.com (Walter Prins) Date: Mon, 23 Sep 2013 21:00:16 +0100 Subject: [Tutor] Suds, Lxml - sending an xml request In-Reply-To: References: Message-ID: Hi, On 20 September 2013 14:25, Ismar Sehic wrote: > i'm probably very annoying and boring with these python web service :)and > sorry for the previous message reply subject,wont happen again... > the thing is, i'm provided with some service provider documentation, > including xml request example, xml response example, wsdl file for the > protocol defintion, and xsd file for every request type. > > You should not need to mess with lxml yourself if you're using a SOAP library like suds. Also, you might try SOAPpy, or alternatively, try ZSI if you can get it working -- the project seems kind of dead and not recently updated and I seem to remember it was rather fiddly to get it working last time I had to work with it. (That said I might add that we've had good success with ZSI. Usefully, it can generate wrapper classes for your WSDL which means you get a concrete native Python representation that you can refer to, of the webservice interface you're trying to work with. SOAPpy and other more recent frameworks takes a more minimalist approach and does everything dynamically which can sometimes make it a bit tricky to work with a new interface.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Sep 24 00:23:22 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 23 Sep 2013 18:23:22 -0400 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: On Mon, Sep 23, 2013 at 3:28 PM, Albert-Jan Roskam wrote: > I just wanted to type "git status" in my Linux terminal but I made a typo > and I got a long Python 3.3 traceback message. Just curious: What does it > mean? > > gigt status > Traceback (most recent call last): "gigt"? Why is that trying to run Python? > File "/usr/lib/python3.3/_sysconfigdata.py", line 6, in > from _sysconfigdata_m import * > ImportError: No module named '_sysconfigdata_m' _sysconfigdata.build_time_vars updates sysconfig._CONFIG_VARS. build_time_vars was parsed from pyconfig.h when Python was built: http://hg.python.org/cpython/file/d047928ae3f6/Lib/sysconfig.py#l364 http://hg.python.org/cpython/file/d047928ae3f6/pyconfig.h.in On Debian systems the dict is actually stored in the platform-specific module _sysconfigdata_m. I doubt it's a sys.path issue since the platform subdirectory is baked in to the interpreter binary. Check that the module exists: /usr/lib/python3.3/plat-x86_64-linux-gnu/_sysconfigdata_m.py or /usr/lib/python3.3/plat-i386-linux-gnu/_sysconfigdata_m.py From ljetibo at gmail.com Mon Sep 23 23:17:00 2013 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Mon, 23 Sep 2013 23:17:00 +0200 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code (znxm0i@yahoo.com) Message-ID: Hello, > I have attached a copy of the code I've compiled so far. Next time just post the code in here, I think that's the general consensus around here. You should only attach it or use a pastebin if it's really really long. Considering that usually the only valid entries here are snippets of code you've isolated that do not work (functions/methods...), code that gets posted here is usually not too long. Anyhow the graphics.py module is unbeknownst to me, but I presume you're reffering to this one: http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/graphics.html What you're doing wrong is your input: principal = eval(input.getText()) apr = eval(input2.getText()) Those commands are in order, however their position in programing is not. Let's examine: 1. you draw your input screen and define standard inputs for boxes 2. during the drawing session you read in values for which you have provided input boxes 3. you plot the values in a bar graph. When this runs it goes like this: 1. you draw your input screen, set values in input boxes to 0.0 and 0.0 2. apr and principal get set to 0.0 and 0.0 3. plot graph and values and of course every single bar gets ploted to 0, because those are the values of your inputs. If there is no principal to add apr to there is no net result. You should make it so that apr and principal get set AFTER the initial screen drawing session but BEFORE plotting, therefore after the mouse-click. You're also making a mistake of not actually changing any values as the year progresses: bar = Rectangle(Point(year, 0), Point(year+1, principal)) every bar will have the same height, that of the inputed principal value. I don't know if it's encouraged here or not, to give straight away answers, but here it goes anyway because I think znx is missing couple of other things as well: To sort out the wrong inputing move the eval() lines after the win.getMouse() statement, preferably right before the for loop statement. Your principal grows each year by the value of apr, so if you have a 1000$ in the bank and the bank awards you with 500$ each year (good luck with that) then by the end of the first year you should have 1500$, by the end of the 2nd year 2000$ because the 1st year becomes the principal for the 2nd year, by 3rd year it's 2500$ and so on.... To introduce the changing values you have to have a new variable to store the increased original value, let's call that variable "newvalue". Then you have to increase the value of the new variable every complete step of the for loop. Each full circle of for loop should see at least 1 newvalue = newvalue +apr (or newvalue+=apr in short). This solution removes the need for the # Draw bar for initial principal set of orders so delete it: # read values in input boxes AFTER the button click principal = eval(input.getText()) apr = eval(input2.getText()) #create new value that you'll increase every year by apr newvalue = principal+apr #this is the net money by the end of 1st year # Draw a bar for each subsequent year for year in range(0, 11): #by going from 0 you don't have to specifically plot 1st year bar = Rectangle(Point(year, 0), Point(year+1, newvalue)) newvalue = newvalue+apr bar.setFill("green") bar.setWidth(2) #I don't know if this serves any purpose because the width of your bar is defined with year to year+1 values. Maybe it's the line width? bar.draw(win) and that should do it. For a test run use print statement to check that the for loop does what you want it too and use simple numbers as principal=1000 and apr=500, you should get 1500, 2000, 2500...... (This looked a lot like a fixed interest rate assignment so I guess that's the purpose, note that because of the set scale of the graph you should always use larger numbers because smaller ones will not be visible). You can make your y axis change by the value of input if you: 1. read input after button click but before setting the scale 2. set scale from 0 to maximal achievable value + some aditional "height" that you can see the entire graph (p.s. maximal achievable value is principal+final_year*apr, so in your case, principal+11*apr+500 [for spacing]) 3. plot the rest Good luck, Dino From steve at pearwood.info Tue Sep 24 02:25:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 24 Sep 2013 10:25:34 +1000 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <20130924002534.GC7989@ando> On Mon, Sep 23, 2013 at 12:28:10PM -0700, Albert-Jan Roskam wrote: > Hi, > > I just wanted to type "git status" in my Linux terminal but I made a > typo and I got a long Python 3.3 traceback message. Just curious: What > does it mean? Unless this was at the Python prompt, it's not really a Python question. It's a question about your Linux installation, and why "gigt" ends up calling Python. Start with: man gigt which gigt locate gigt to try to identify what it is. If nothing relevant comes up, that suggests that your Linux system is set up to try to help when you mistype a command. E.g. on one Ubuntu system, I get this: steve at flora:~$ gigt No command 'gigt' found, did you mean: Command 'gitg' from package 'gitg' (universe) Command 'gist' from package 'yorick' (universe) Command 'gift' from package 'gnuift' (universe) Command 'git' from package 'git-core' (main) gigt: command not found I don't know the technology behind this feature, but it may be built using Python. That explains why you're going a Python traceback. Which implies that you've broken the system Python. Very few Linux distros use Python 3.3 as their system Python. Your error suggests that you've replaced the expected Python installation, probably 2.7, with 3.3 instead of installing in parallel. That's not a good idea. You can test this by su'ing to some user other than yourself, to ensure you have a clean environment, and then run python -V to see the version. If I do this as both the "steve" and "root" users, you can see I get two different versions: [steve at ando ~]$ python -V Python 2.7.2 [steve at ando ~]$ su - Password: [root at ando ~]# python -V Python 2.4.3 That's because the "steve" user has a line in my .bashrc file that sets an alias python=python2.7, while the system Python on this machine is Python 2.4. Last but not least, the error message you get hints that your Python 3.3 installation may be broken. What happens if you try to run it normally? The error ends with: > ? File "/usr/lib/python3.3/sysconfig.py", line 403, in _init_posix > ??? from _sysconfigdata import build_time_vars > ? File "/usr/lib/python3.3/_sysconfigdata.py", line 6, in > ??? from _sysconfigdata_m import * > ImportError: No module named '_sysconfigdata_m' If you can reliably reproduce this error, it should be reported as a bug. Assuming you didn't break it yourself :-) I note that in my version of Python 3.3, line 6 of _sysconfigdata is not an import, and the line "from _sysconfigdata_m import *" does not exist anywhere in the file. -- Steven From kevgathuku at gmail.com Tue Sep 24 08:20:59 2013 From: kevgathuku at gmail.com (Kevin Ndung'u) Date: Tue, 24 Sep 2013 09:20:59 +0300 Subject: [Tutor] Please help with beautifulsoup and web scraping Message-ID: http://stackoverflow.com/q/18974172/2390312 -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Sep 24 13:47:49 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 24 Sep 2013 12:47:49 +0100 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: On 23 September 2013 20:28, Albert-Jan Roskam wrote: > Hi, > > I just wanted to type "git status" in my Linux terminal but I made a typo > and I got a long Python 3.3 traceback message. Just curious: What does it > mean? > > gigt status > Traceback (most recent call last): > File "/usr/lib/python3.3/site.py", line 631, in > main() > File "/usr/lib/python3.3/site.py", line 616, in main > known_paths = addusersitepackages(known_paths) > File "/usr/lib/python3.3/site.py", line 284, in addusersitepackages > user_site = getusersitepackages() > File "/usr/lib/python3.3/site.py", line 260, in getusersitepackages > user_base = getuserbase() # this will also set USER_BASE > File "/usr/lib/python3.3/site.py", line 250, in getuserbase > USER_BASE = get_config_var('userbase') > File "/usr/lib/python3.3/sysconfig.py", line 580, in get_config_var > return get_config_vars().get(name) > File "/usr/lib/python3.3/sysconfig.py", line 530, in get_config_vars > _init_posix(_CONFIG_VARS) > File "/usr/lib/python3.3/sysconfig.py", line 403, in _init_posix > from _sysconfigdata import build_time_vars > File "/usr/lib/python3.3/_sysconfigdata.py", line 6, in > from _sysconfigdata_m import * > ImportError: No module named '_sysconfigdata_m' This message comes as Steven says from the Python code that checks unrecognised commands against the apt database to offer suggestions for how to install the command you want. The error message either results from a bug in Ubuntu (assuming it is Ubuntu) or it is because you've screwed with your system in some way (or both). Which version of Ubuntu are you using and did it come with Python 3.3 or did you install that separately somehow? I've had problems before that come from installing newer Python versions that haven't yet been appropriately patched for Ubuntu. Oscar From fomcl at yahoo.com Tue Sep 24 14:18:52 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 24 Sep 2013 05:18:52 -0700 (PDT) Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> ________________________________ > From: Oscar Benjamin >To: Albert-Jan Roskam >Cc: Python Mailing List >Sent: Tuesday, September 24, 2013 1:47 PM >Subject: Re: [Tutor] ImportError: No module named '_sysconfigdata_m' > > >On 23 September 2013 20:28, Albert-Jan Roskam wrote: >> Hi, >> >> I just wanted to type "git status" in my Linux terminal but I made a typo >> and I got a long Python 3.3 traceback message. Just curious: What does it >> mean? >> >> gigt status >> Traceback (most recent call last): >>???File "/usr/lib/python3.3/site.py", line 631, in >>? ???main() >>???File "/usr/lib/python3.3/site.py", line 616, in main >>? ???known_paths = addusersitepackages(known_paths) >>???File "/usr/lib/python3.3/site.py", line 284, in addusersitepackages >>? ???user_site = getusersitepackages() >>???File "/usr/lib/python3.3/site.py", line 260, in getusersitepackages >>? ???user_base = getuserbase() # this will also set USER_BASE >>???File "/usr/lib/python3.3/site.py", line 250, in getuserbase >>? ???USER_BASE = get_config_var('userbase') >>???File "/usr/lib/python3.3/sysconfig.py", line 580, in get_config_var >>? ???return get_config_vars().get(name) >>???File "/usr/lib/python3.3/sysconfig.py", line 530, in get_config_vars >>? ???_init_posix(_CONFIG_VARS) >>???File "/usr/lib/python3.3/sysconfig.py", line 403, in _init_posix >>? ???from _sysconfigdata import build_time_vars >>???File "/usr/lib/python3.3/_sysconfigdata.py", line 6, in >>? ???from _sysconfigdata_m import * >> ImportError: No module named '_sysconfigdata_m' > >This message comes as Steven says from the Python code that checks >unrecognised commands against the apt database to offer suggestions >for how to install the command you want. The error message either >results from a bug in Ubuntu (assuming it is Ubuntu) or it is because >you've screwed with your system in some way (or both). > >Which version of Ubuntu are you using and did it come with Python 3.3 >or did you install that separately somehow? I've had problems before >that come from installing newer Python versions that haven't yet been >appropriately patched for Ubuntu. Hi all, I was planning to reply after I had the chance to do some checks that were suggested (I am on a Windows computer now) but I can't resist replying now.? I am using Linux Mint XFCE. I have to look up the exact version number. I recently downloaded and installed Python 3.3. I downloaded the tarball and compiled, tested and installed everything as per instructions in the (readme? install?) file. There where hundreds of tests and I confess I didn't closely study the test results (some would fail anyway, such as winreg). Apart from the behavior that I posted, everything appears to work normally (phew) If I type "python", python 2.7 fires up. Also, I entirely removed python 3.2 (sudo rm -rf $(which python3.2), IIRC), which came with Linux Mint. Not sure if this is relevant, but I also installed Tox ,which is a wrapper for virtualenv that makes it easy to e.g. run nosetests with different python versions. OoooOoOoh, I hope Steven is not correct that I messed up the Python version that my OS uses. ;-) regards, Albert-Jan From oscar.j.benjamin at gmail.com Tue Sep 24 14:33:23 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 24 Sep 2013 13:33:23 +0100 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On 24 September 2013 13:18, Albert-Jan Roskam wrote: >> >>On 23 September 2013 20:28, Albert-Jan Roskam wrote: >>> Hi, >>> >>> I just wanted to type "git status" in my Linux terminal but I made a typo >>> and I got a long Python 3.3 traceback message. Just curious: What does it >>> mean? >>> >>> gigt status >>> Traceback (most recent call last): >>> File "/usr/lib/python3.3/site.py", line 631, in >>> main() >>> File "/usr/lib/python3.3/site.py", line 616, in main >>> known_paths = addusersitepackages(known_paths) >>> File "/usr/lib/python3.3/site.py", line 284, in addusersitepackages >>> user_site = getusersitepackages() >>> File "/usr/lib/python3.3/site.py", line 260, in getusersitepackages >>> user_base = getuserbase() # this will also set USER_BASE >>> File "/usr/lib/python3.3/site.py", line 250, in getuserbase >>> USER_BASE = get_config_var('userbase') >>> File "/usr/lib/python3.3/sysconfig.py", line 580, in get_config_var >>> return get_config_vars().get(name) >>> File "/usr/lib/python3.3/sysconfig.py", line 530, in get_config_vars >>> _init_posix(_CONFIG_VARS) >>> File "/usr/lib/python3.3/sysconfig.py", line 403, in _init_posix >>> from _sysconfigdata import build_time_vars >>> File "/usr/lib/python3.3/_sysconfigdata.py", line 6, in >>> from _sysconfigdata_m import * >>> ImportError: No module named '_sysconfigdata_m' >> >>This message comes as Steven says from the Python code that checks >>unrecognised commands against the apt database to offer suggestions >>for how to install the command you want. The error message either >>results from a bug in Ubuntu (assuming it is Ubuntu) or it is because >>you've screwed with your system in some way (or both). >> >>Which version of Ubuntu are you using and did it come with Python 3.3 >>or did you install that separately somehow? I've had problems before >>that come from installing newer Python versions that haven't yet been >>appropriately patched for Ubuntu. > > I was planning to reply after I had the chance to do some checks that were suggested (I am on a Windows computer now) but I can't resist replying now. I am using Linux Mint XFCE. I have to look up the exact version number. I recently downloaded and installed Python 3.3. I downloaded the tarball and compiled, tested and installed everything as per instructions in the (readme? install?) file. There where hundreds of tests and I confess I didn't closely study the test results (some would fail anyway, such as winreg). Apart from the behavior that I posted, everything appears to work normally (phew) If I type "python", python 2.7 fires up. Also, I entirely removed python 3.2 (sudo rm -rf $(which python3.2), IIRC), which came with Linux Mint. Not sure if this is relevant, but I also installed Tox ,which is a wrapper for virtualenv that makes it easy to e.g. run nosetests with different python versions. > > > OoooOoOoh, I hope Steven is not correct that I messed up the Python version that my OS uses. ;-) If you want to mess with your system 'sudo rm -rf' is definitely the way to go. Don't bother reporting this as a bug since you've *definitely* voided the warranty (that your free software didn't come with). Debian/Ubuntu and other derivatives such as Mint do not use the python.org tarball as it comes out of the box. They apply a whole bunch of system specific patches so that Python fits in with their Debian way of doing things. This may be why you're seeing the error with your un-patched CPython. BTW why did you feel the need to delete it? If you say what you were trying to achieve I guarantee that someone will suggest a better way of achieving the same thing. Oscar From davea at davea.name Tue Sep 24 15:06:54 2013 From: davea at davea.name (Dave Angel) Date: Tue, 24 Sep 2013 13:06:54 +0000 (UTC) Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On 24/9/2013 08:18, Albert-Jan Roskam wrote: >, everything appears to work normally (phew) If I type "python", python > 2.7 fires up. Also, I entirely removed python 3.2 (sudo rm -rf $(which python3.2), IIRC), which came with Linux Mint. Right there is your mistake. > > > OoooOoOoh, I hope Steven is not correct that I messed up the Python version that my OS uses. ;-) > That's what you just said. -- DaveA From fomcl at yahoo.com Tue Sep 24 15:20:37 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 24 Sep 2013 06:20:37 -0700 (PDT) Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> ----- Original Message ----- > From: Oscar Benjamin > To: Albert-Jan Roskam > Cc: Python Mailing List > Sent: Tuesday, September 24, 2013 2:33 PM > Subject: Re: [Tutor] ImportError: No module named '_sysconfigdata_m' >> I was planning to reply after I had the chance to do some checks that were > suggested (I am on a Windows computer now) but I can't resist replying now.? > I am using Linux Mint XFCE. I have to look up the exact version number. I > recently downloaded and installed Python 3.3. I downloaded the tarball and > compiled, tested and installed everything as per instructions in the (readme? > install?) file. There where hundreds of tests and I confess I didn't closely > study the test results (some would fail anyway, such as winreg). Apart from the > behavior that I posted, everything appears to work normally (phew) If I type > "python", python 2.7 fires up. Also, I entirely removed python 3.2 > (sudo rm -rf $(which python3.2), IIRC), which came with Linux Mint. Not sure if > this is relevant, but I also installed Tox ,which is a wrapper for virtualenv > that makes it easy to e.g. run nosetests with different python versions. >> >> >> OoooOoOoh, I hope Steven is not correct that I messed up the Python version > that my OS uses. ;-) > > If you want to mess with your system 'sudo rm -rf' is definitely the > way to go. Don't bother reporting this as a bug since you've > *definitely* voided the warranty (that your free software didn't come > with). And the 'f' (force) makes it particularly bad? I guess I learnt something the hard way today. > Debian/Ubuntu and other derivatives such as Mint do not use the > python.org tarball as it comes out of the box. They apply a whole > bunch of system specific patches so that Python fits in with their > Debian way of doing things. This may be why you're seeing the error > with your un-patched CPython. Ok, I did not know that. I am surprised that Mint uses Python 3.2 internally. I thought only Python 2.7 was used. ? > BTW why did you feel the need to delete it? If you say what you were > trying to achieve I guarantee that someone will suggest a better way > of achieving the same thing. I just didn't want to have more versions than I actually need. Python 3.3 is closer to Python 2.7 than earlier Python 3 versions. I am now planning to reinstall Python 3.2 using "sudo apt-get install python3" From davea at davea.name Tue Sep 24 15:47:50 2013 From: davea at davea.name (Dave Angel) Date: Tue, 24 Sep 2013 13:47:50 +0000 (UTC) Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 24/9/2013 09:20, Albert-Jan Roskam wrote: > I just didn't want to have more versions than I actually need. Python 3.3 is closer to Python 2.7 than earlier Python 3 versions. > I am now planning to reinstall Python 3.2 using "sudo apt-get install python3" I suspect you'd be better off trying to install it using Mint's update manager (which I have no experience with). Or maybe the package manager. That way you have at least a chance at getting the distribution-specific patches. -- DaveA From fluca1978 at infinito.it Tue Sep 24 13:31:26 2013 From: fluca1978 at infinito.it (Luca Ferrari) Date: Tue, 24 Sep 2013 13:31:26 +0200 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <20130924002534.GC7989@ando> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130924002534.GC7989@ando> Message-ID: On Tue, Sep 24, 2013 at 2:25 AM, Steven D'Aprano wrote: > Unless this was at the Python prompt, it's not really a Python question. > It's a question about your Linux installation, and why "gigt" ends up > calling Python. Start with: > > man gigt > > which gigt > > locate gigt > As far as I know this is a git viewer based on GTK+. For the rest, it depends on some installation misplaced file I guess. Luca From fluca1978 at infinito.it Tue Sep 24 14:00:54 2013 From: fluca1978 at infinito.it (Luca Ferrari) Date: Tue, 24 Sep 2013 14:00:54 +0200 Subject: [Tutor] AntiSpam measures circumventing In-Reply-To: <523C60A2.3090902@gmail.com> References: <523C60A2.3090902@gmail.com> Message-ID: On Fri, Sep 20, 2013 at 4:50 PM, Jugurtha Hadjar wrote: > Supposing my name is John Doe and the e-mail is john.doe at hotmail.com, my > e-mail was written like this: > > REMOVEMEjohn.doSPAMeSPAM at REMOVEMEhotmail.com' This is the point: how easy you want to make the email for a human being. I mean, you can also reverse letters, substitute dots with commas, and so on, and you will find a kind of email that is useless, but it will be really hard for a human being to use it out of the box. So far I guess the best anti spam countermesure is: - publish something like "name surname domain1 domain2" where you do not reveal explicitly name and surname (that is, the information requires a little reasoning) - use a good antispam filter. An image is not a solution, in my opinion, since users (human beings) are not good at copying one character at a time, so you need to provide some kind of copy and paste functionality, that steps back to the original problem. Luca From eryksun at gmail.com Tue Sep 24 17:25:35 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 24 Sep 2013 11:25:35 -0400 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On Tue, Sep 24, 2013 at 8:18 AM, Albert-Jan Roskam wrote: > am using Linux Mint XFCE. I have to look up the exact version number. I recently > downloaded and installed Python 3.3. I downloaded the tarball > and compiled, tested and installed everything as per instructions in the > (readme? install?) file. Building from the official source defaults to /usr/local as the prefix directory, which doesn't interfere with the platform Python in /usr. Did you configure with --prefix=/usr? Also, it defaults to using _sysconfigdata for build_time_vars -- not _sysconfigdata_m in the platform subdirectory. That's a Debian patch, which you can see in the following diff: http://ftp.de.debian.org/debian/pool/main/p/python3.3/python3.3_3.3.2-5.diff.gz The "command-not-found" script uses 3.x on Ubuntu/Mint: http://packages.ubuntu.com/saucy/command-not-found It's 2.x on Debian, but thankfully it isn't part of the default install. From alan.gauld at btinternet.com Tue Sep 24 18:23:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Sep 2013 17:23:27 +0100 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 24/09/13 14:20, Albert-Jan Roskam wrote: >> "python", python 2.7 fires up. Also, I entirely removed python 3.2 >> (sudo rm -rf $(which python3.2), IIRC), which came with Linux Mint. That's almost never the right way to remove a package that came with the OS. You should have used the package manager or Synaptic. That would have cleaned up any links and aliases that had been set. The good news is that I don't believe Python3.2 is used by Mint its just there for convenience (I think!). Reinstalling and then uninstalling 3.2 via Synaptic may help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From oscar.j.benjamin at gmail.com Tue Sep 24 19:07:20 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 24 Sep 2013 18:07:20 +0100 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On 24 September 2013 16:25, eryksun wrote: > > The "command-not-found" script uses 3.x on Ubuntu/Mint: > > http://packages.ubuntu.com/saucy/command-not-found > > It's 2.x on Debian, but thankfully it isn't part of the default install. I actually find it useful. I wish I could get the same for import errors in the Python interactive terminal: >>> import numpy ImportError: module numpy not found, install it with 'sudo apt-get install python3-numpy' Oscar From bgailer at gmail.com Tue Sep 24 19:40:25 2013 From: bgailer at gmail.com (bob gailer) Date: Tue, 24 Sep 2013 13:40:25 -0400 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> References: <1379708827.67739.BPMail_high_noncarrier@web184705.mail.ne1.yahoo.com> <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> Message-ID: <5241CE89.60303@gmail.com> In addition to Alan's comment: Saying "it work properly" is totally uninformative. Tell us what is happening that you want different. -- Bob Gailer 919-636-4239 Chapel Hill NC From fomcl at yahoo.com Tue Sep 24 19:42:12 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 24 Sep 2013 10:42:12 -0700 (PDT) Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <1380044532.27370.YahooMailNeo@web163805.mail.gq1.yahoo.com> ----- Original Message ----- > From: eryksun > To: Albert-Jan Roskam > Cc: Python Mailing List > Sent: Tuesday, September 24, 2013 5:25 PM > Subject: Re: [Tutor] ImportError: No module named '_sysconfigdata_m' > > On Tue, Sep 24, 2013 at 8:18 AM, Albert-Jan Roskam > wrote: >> am using Linux Mint XFCE. I have to look up the exact version number. Just in case anybody ever looks in the archives: antonia at antonia-HP-2133 ~ $ uname -a Linux antonia-HP-2133 3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:32:08 UTC 2012 i686 i686 i686 GNU/Linux > I recently >> downloaded and installed Python 3.3. I downloaded the tarball >> and compiled, tested and installed everything as per instructions in the >> (readme? install?) file. > > Building from the official source defaults to /usr/local as the prefix > directory, which doesn't interfere with the platform Python in /usr. > Did you configure with --prefix=/usr? Also, it defaults to using > _sysconfigdata for build_time_vars? -- not _sysconfigdata_m in the > platform subdirectory.? That's a Debian patch, which you can see in > the following diff: I did not use "--prefix". I just reinstalled Python 3.2 via the package manager, and it everything is working again --THANK YOU ALL! antonia at antonia-HP-2133 ~ $ which python3.3 /usr/local/bin/python3.3 antonia at antonia-HP-2133 ~ $ which python3.2 /usr/bin/python3.2 ? Are the Python-3 versions considered to be too different that apt-get update does not replace e.g. 3.2 with 3.3? Or is that also related to the Debian-specific patches, which may cause the Debian-specific release to be (much) behind with the "generic" Python release? > http://ftp.de.debian.org/debian/pool/main/p/python3.3/python3.3_3.3.2-5.diff.gz > > The "command-not-found" script uses 3.x on Ubuntu/Mint: > > http://packages.ubuntu.com/saucy/command-not-found > > It's 2.x on Debian, but thankfully it isn't part of the default install. > From ramit.prasad at jpmorgan.com.dmarc.invalid Tue Sep 24 20:22:20 2013 From: ramit.prasad at jpmorgan.com.dmarc.invalid (Prasad, Ramit) Date: Tue, 24 Sep 2013 18:22:20 +0000 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474187693A8@SCACMX008.exchad.jpmchase.net> Alan Gauld wrote: > > On 24/09/13 14:20, Albert-Jan Roskam wrote: > > >> "python", python 2.7 fires up. Also, I entirely removed python 3.2 > >> (sudo rm -rf $(which python3.2), IIRC), which came with Linux Mint. > > That's almost never the right way to remove a package that came with the OS. > > You should have used the package manager or Synaptic. That would have > cleaned up any links and aliases that had been set. > > The good news is that I don't believe Python3.2 is used by Mint its just > there for convenience (I think!). Reinstalling and then uninstalling 3.2 > via Synaptic may help. > Why uninstall via Synaptic? If he manually installed from source (I assume he did not make a .deb) then I would think that manually re-installing from source and then uninstalling from source might work better (assuming the install script has an uninstall option). That will clean up any files that might have installed to places other (e.g. /usr/share) than the main install (/usr/local). Not sure if CPython does install other places. sudo make install sudo make uninstall? ~Ramit 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. From Robert.Treder at morganstanley.com Tue Sep 24 22:33:20 2013 From: Robert.Treder at morganstanley.com (Treder, Robert) Date: Tue, 24 Sep 2013 16:33:20 -0400 Subject: [Tutor] How to create dictionaries loadable with import Message-ID: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> Hi Python tutors, I'm fairly new to Python. I'm working with Python v2.7.4 and the nltk package on a couple of text mining projects. I create several dictionaries that are pretty static. Will probably only be updated every or month or every couple of months. I want to turn those dictionaries into loadable data sets prior to running a module which uses them. If I define several dictionaries, dict1, dict2 and dict3, in a single module named myDict, I'd like to do from myDict import * I've tried defining the dictionaries in a the myDict module as follows: Dict1 = {} with open('file1, 'rb') as infile: reader = csv.reader(infile, delimiter = ',') for row in reader: try: Dict1[ row[1] ].append(row[0]) except: Dict1[ row[1] ] = [ row[0], ] Dict2 = {} with open('file2, 'rb') as infile: reader = csv.reader(infile, delimiter = ',') for row in reader: try: Dict2[ row[1] ].append(row[0]) except: Dict2[ row[1] ] = [ row[0], ] These are simple dictionary structures with no additional structure, i.e., not embedded in classes or functions. The try/except sequence is because some of the keys may be duplicated in the files and I want to append the values rather than overwrite. Now when I build the module with setup tools python setup.py install -prefix=C:\PY_MODULES it builds without error but I can't find the dictionaries when I load the module from myDict import * AttributeError: 'module' object has no attribute 'Dict1' How can I make the dictionaries loadable using import? Thanks, Bob ________________________________ NOTICE: Morgan Stanley is not acting as a municipal advisor and the opinions or views contained herein are not intended to be, and do not constitute, advice within the meaning of Section 975 of the Dodd-Frank Wall Street Reform and Consumer Protection Act. If you have received this communication in error, please destroy all electronic and paper copies and notify the sender immediately. Mistransmission is not intended to waive confidentiality or privilege. Morgan Stanley reserves the right, to the extent permitted under applicable law, to monitor electronic communications. This message is subject to terms available at the following link: http://www.morganstanley.com/disclaimers If you cannot access these links, please notify us by reply message and we will send the contents to you. By messaging with Morgan Stanley you consent to the foregoing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Sep 24 23:08:45 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 24 Sep 2013 17:08:45 -0400 Subject: [Tutor] How to create dictionaries loadable with import In-Reply-To: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> References: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> Message-ID: On Tue, Sep 24, 2013 at 4:33 PM, Treder, Robert < Robert.Treder at morganstanley.com> wrote: > Hi Python tutors, **** > > ** ** > > I?m fairly new to Python. I?m working with Python v2.7.4 and the nltk > package on a couple of text mining projects. I create several dictionaries > that are pretty static. Will probably only be updated every or month or > every couple of months. I want to turn those dictionaries into loadable > data sets prior to running a module which uses them. If I define several > dictionaries, dict1, dict2 and dict3, in a single module named myDict, I?d > like to do**** > > ** ** > > from myDict import ***** > > ** ** > > I?ve tried defining the dictionaries in a the myDict module as follows: ** > ** > > ** ** > > Dict1 = {}**** > > with open(*?file1*, *'rb'*) as infile:**** > > reader = csv.reader(infile, delimiter = *','*)**** > > for row in reader:**** > > try:**** > > Dict1[ row[1] ].append(row[0])**** > > except:**** > > Dict1[ row[1] ] = [ row[0], ]**** > > ** ** > > Dict2 = {}**** > > with open(*?file2*, *'rb'*) as infile:**** > > reader = csv.reader(infile, delimiter = *','*)**** > > for row in reader:**** > > try:**** > > Dict2[ row[1] ].append(row[0])**** > > except:**** > > Dict2[ row[1] ] = [ row[0], ]**** > > ** ** > > These are simple dictionary structures with no additional structure, i.e., > not embedded in classes or functions.**** > > The try/except sequence is because some of the keys may be duplicated in > the files and I want to append the values rather than overwrite. **** > > ** ** > > Now when I build the module with setup tools**** > > ** ** > > python setup.py install ?prefix=C:\PY_MODULES**** > > ** ** > > it builds without error but I can?t find the dictionaries when I load the > module**** > > ** ** > > from myDict import ***** > > AttributeError: 'module' object has no attribute 'Dict1' > Rather than snip this error, can you show the complete traceback, which will show what line it occurs in your code. Does the error occur in the MyDict module or in code that imports it? A couple of things. It is considered sketchy to do from xxx import * Better is to do import MyDict then you can access your dictionaries as MyDict.Dict1 and so on. > **** > > ** ** > > How can I make the dictionaries loadable using import? **** > > ** ** > > Thanks, **** > > Bob**** > > ** ** > > ** ** > > > ------------------------------ > > NOTICE: Morgan Stanley is not acting as a municipal advisor and the > opinions or views contained herein are not intended to be, and do not > constitute, advice within the meaning of Section 975 of the Dodd-Frank Wall > Street Reform and Consumer Protection Act. If you have received this > communication in error, please destroy all electronic and paper copies and > notify the sender immediately. Mistransmission is not intended to waive > confidentiality or privilege. Morgan Stanley reserves the right, to the > extent permitted under applicable law, to monitor electronic > communications. This message is subject to terms available at the following > link: http://www.morganstanley.com/disclaimers If you cannot access these > links, please notify us by reply message and we will send the contents to > you. By messaging with Morgan Stanley you consent to the foregoing. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Sep 24 22:48:21 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 24 Sep 2013 16:48:21 -0400 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1380044532.27370.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1380044532.27370.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: On Tue, Sep 24, 2013 at 1:42 PM, Albert-Jan Roskam wrote: > I did not use "--prefix". I just reinstalled Python 3.2 via the package manager, and > it everything is working again --THANK YOU ALL! > > antonia at antonia-HP-2133 ~ $ which python3.3 > /usr/local/bin/python3.3 This is the version you built from source, using the default /usr/local prefix, right? Debian also uses /usr/local/lib/python3.3 for locally installed modules (e.g. pip install), but it uses the "dist-packages" directory instead of "site-packages", so there's no conflict. If you need to uninstall, you can use the checkinstall program to build a .deb. For example, as root: # ./configure # make # checkinstall -D --pkgname=python332 --pkgversion=3.3.2 \ > --fstrans=no make install Change the last part to "make altinstall" if that's what you used originally. Answer yes and enter to start the installation. You may be asked to exclude some files; say yes. Wait a long while for the package to be built and installed... Then remove it using dpkg: # dpkg -r python332 > antonia at antonia-HP-2133 ~ $ which python3.2 > /usr/bin/python3.2 > > Are the Python-3 versions considered to be too different that apt-get update does > not replace e.g. 3.2 with 3.3? Or is that also related to the Debian-specific patches, > which may cause the Debian-specific release to be (much) behind with the > "generic" Python release? 3.2 and 3.3 coexist since .pyc and .so filenames are tagged. Debian installs 3.x modules in /usr/lib/python3/dist-packages. The standard library is separate in /usr/lib/python3.2, /usr/lib/python3.3, and so on. From northriptl at s.dcsdk12.org Tue Sep 24 22:36:00 2013 From: northriptl at s.dcsdk12.org (School) Date: Tue, 24 Sep 2013 14:36:00 -0600 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> References: <1379708827.67739.BPMail_high_noncarrier@web184705.mail.ne1.yahoo.com> <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> Message-ID: <26330B59-B893-4127-AA60-ECAD3D33E96E@s.dcsdk12.org> What is the error you received? What lines does it say are causing the error? Also, this smells like classwork. On Sep 20, 2013, at 21:26, znxm0i at yahoo.com wrote: > Can anyone please help me figure out what I am NOT doing to make this program work properly.....PLEASE !! > > I need to be able to take the user input that is entered in the two graphical boxes of the first window and evaluate it to generate a graph chart which is suppose to display in the second window. I am totally at a loss for what I am NOT doing, and I know it is something so simple that I am overlooking because I am making this harder that what it most likely really is. > > But I just cannot get it to work properly. Please HELP !!! Help me understand what I am doing wrong and how to fix it. I believe I am on the right path but I'm becoming frustrated and discouraged. > > I have attached a copy of the code I've compiled so far. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com.dmarc.invalid Wed Sep 25 00:23:06 2013 From: ramit.prasad at jpmorgan.com.dmarc.invalid (Prasad, Ramit) Date: Tue, 24 Sep 2013 22:23:06 +0000 Subject: [Tutor] How to create dictionaries loadable with import In-Reply-To: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> References: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418769739@SCACMX008.exchad.jpmchase.net> Treder, Robert wrote: > Hi Python tutors, > > I'm fairly new to Python. ?I'm working with Python v2.7.4 and the nltk package on a couple of text > mining projects.? I create several dictionaries that are pretty static. Will probably only be updated > every or month or every couple of months. ?I want to turn those dictionaries into loadable data sets > prior to running a module which uses them.? If I define several dictionaries, dict1, dict2 and dict3, > in a single module named myDict, I'd like to do > > from myDict import * > > I've tried defining the dictionaries in a the myDict module as follows: > > Dict1 = {} > with open('file1, 'rb') as infile: Without the closing quote for file1, this is a SyntaxError. > ??? reader = csv.reader(infile, delimiter = ',') > ??? for row in reader: > ??????? try: > ??????????? Dict1[ row[1] ].append(row[0]) > ??????? except: > ??????????? Dict1[ row[1] ] = [ row[0], ] > > Dict2 = {} > with open('file2, 'rb') as infile: Without the closing quote for file2, this is a SyntaxError. > ??? reader = csv.reader(infile, delimiter = ',') > ??? for row in reader: > ??????? try: > ??????????? Dict2[ row[1] ].append(row[0]) > ??????? except: > ??????????? Dict2[ row[1] ] = [ row[0], ] > > These are simple dictionary structures with no additional structure, i.e., not embedded in classes or > functions. > The try/except sequence is because some of the keys may be duplicated in the files and I want to > append the values rather than overwrite. Hmm, I think you are incorrect. The try/except logic is used when there is not row[1] in the dictionary (i.e. every first entry of a key). I guess that handles multiple keys, but it would be clearer if you used the setdefault method on the dictionary. Dict1.setdefault( row[1], [] ).append( row[0] ) > Now when I build the module with setup tools > > python setup.py install -prefix=C:\PY_MODULES Unless you have a non-standard environment (at least not one I am familiar with), you do not need setup tools as long as the script is somewhere on the PYTHONPATH. Also, the dictionaries are not created except on first import of the module (at run-time not compile-time). If they are static or mostly so, you may want to just hard code them in the myDict module (lowercase for module names is the community standard) for easier modification. In addition, that means you can get rid of the source files file1 and file2. You can use `print repr(Dict1)` to copy paste the dictionaries into the code. > > it builds without error but I can't find the dictionaries when I load the module > ??? from myDict import * > AttributeError: 'module' object has no attribute 'Dict1' > > How can I make the dictionaries loadable using import? The import and the error do not seem to match. Can you please copy/paste (do not paraphrase or try to retype) the FULL error? > > Thanks, > Bob ~Ramit 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. From steve at pearwood.info Wed Sep 25 01:16:12 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 25 Sep 2013 09:16:12 +1000 Subject: [Tutor] How to create dictionaries loadable with import In-Reply-To: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> References: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> Message-ID: <20130924231611.GJ7989@ando> On Tue, Sep 24, 2013 at 04:33:20PM -0400, Treder, Robert wrote: > Hi Python tutors, > > I'm fairly new to Python. I'm working with Python v2.7.4 and the nltk > package on a couple of text mining projects. I create several > dictionaries that are pretty static. Will probably only be updated > every or month or every couple of months. I want to turn those > dictionaries into loadable data sets prior to running a module which > uses them. If I define several dictionaries, dict1, dict2 and dict3, > in a single module named myDict, I'd like to do > > from myDict import * Hopefully you'll actually use more meaningful names, but otherwise, this is perfectly doable. > I've tried defining the dictionaries in a the myDict module as follows: > > Dict1 = {} > with open('file1, 'rb') as infile: > reader = csv.reader(infile, delimiter = ',') > for row in reader: > try: > Dict1[ row[1] ].append(row[0]) > except: > Dict1[ row[1] ] = [ row[0], ] > > Dict2 = {} > with open('file2, 'rb') as infile: > reader = csv.reader(infile, delimiter = ',') > for row in reader: > try: > Dict2[ row[1] ].append(row[0]) > except: > Dict2[ row[1] ] = [ row[0], ] I can tell that these aren't the *actual* code you use, copy and pasted, not just because of the fake file names, but because of the SyntaxError that they both have. So the error that the code you show above is different from the error that you actually get. > These are simple dictionary structures with no additional structure, > i.e., not embedded in classes or functions. The try/except sequence is > because some of the keys may be duplicated in the files and I want to > append the values rather than overwrite. A minor point, it is better to avoid bare "except" since that can mask real errors. You should use "except KeyError" here. But other than that, the basic principle is fine. > Now when I build the module with setup tools > > python setup.py install -prefix=C:\PY_MODULES > > it builds without error but I can't find the dictionaries when I load the module > > from myDict import * > AttributeError: 'module' object has no attribute 'Dict1' Please show us the complete traceback, not just the last line. Copy and paste the entire thing, starting with the line Traceback (most recent call last) all the way to the final error message. > How can I make the dictionaries loadable using import? Dicts are no different from any other object, be it classes or functions or strings, they are automatically importable. Without seeing the entire traceback, and your actual code, I can't be sure, but my *guess* is that your actual module looks something like this: dict1 = {} with open('file1', 'rb') as infile: reader = csv.reader(infile, delimiter = ',') for row in reader: try: Dict1[ row[1] ].append(row[0]) except: Dict1[ row[1] ] = [ row[0], ] Notice the difference is name between "dict1" and "Dict1"? Python, like most programming languages, is case-sensitive. As is English itself, of course -- as they say, capitalization is the difference between helping your Uncle Jack off a horse, and helping your uncle jack off a horse. Anyway, that's my guess as to what's going wrong. Without seeing your actual code, and the actual traceback, that's as far as I can go. -- Steven From steve at pearwood.info Wed Sep 25 01:25:31 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 25 Sep 2013 09:25:31 +1000 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <20130924232531.GK7989@ando> On Tue, Sep 24, 2013 at 01:33:23PM +0100, Oscar Benjamin wrote: > If you want to mess with your system 'sudo rm -rf' is definitely the > way to go. Don't bother reporting this as a bug since you've > *definitely* voided the warranty (that your free software didn't come > with). I first read that as "sudo rm -rf ." and thought "That's a bit harsh, isn't it?" > Debian/Ubuntu and other derivatives such as Mint do not use the > python.org tarball as it comes out of the box. They apply a whole > bunch of system specific patches so that Python fits in with their > Debian way of doing things. This may be why you're seeing the error > with your un-patched CPython. Just to be clear, this only applies when replacing the *system Python* with an unpatched version. I normally build multiple versions of Python from source, and install them parallel to the system Python, and they work fine on Debian. -- Steven From steve at pearwood.info Wed Sep 25 01:44:45 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 25 Sep 2013 09:44:45 +1000 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <20130924234445.GL7989@ando> On Tue, Sep 24, 2013 at 06:20:37AM -0700, Albert-Jan Roskam wrote: > > If you want to mess with your system 'sudo rm -rf' is definitely the > > way to go. Don't bother reporting this as a bug since you've > > *definitely* voided the warranty (that your free software didn't come > > with). > > And the 'f' (force) makes it particularly bad? I guess I learnt something the hard way today. Yes, and no. sudo means that you're running the command with root (Admin) privileges. "sudo" stands for "Super User DO" so you can guess what that means. rm -rf deletes everything recursively, forcing deletion even if they are marked as unwritable, without asking for confirmation. So it's not that its *bad* exactly, just that it will delete everything you tell it to delete, whether you want it deleted or not. > > Debian/Ubuntu and other derivatives such as Mint do not use the > > python.org tarball as it comes out of the box. They apply a whole > > bunch of system specific patches so that Python fits in with their > > Debian way of doing things. This may be why you're seeing the error > > with your un-patched CPython. > > Ok, I did not know that. I am surprised that Mint uses Python 3.2 > internally. I thought only Python 2.7 was used. ? I would be surprised too. Normally, when you build from source, you have a pythonX.Y executable, and a symbolic link "python" that points to the most recently installed pythonX.Y executable. Than way, just typing "python" on the command line or in a script will get the most recent version. That's not usually what you want, since it affects system tools as well. Some system tool calls "python", expecting one version, and gets a different version, and breakage happens. Worse, if you reinstall the same X.Y version from source, it will overwrite the system version, which is likely to be patched, with an unpatched version. [...] > I just didn't want to have more versions than I actually need. Python > 3.3 is closer to Python 2.7 than earlier Python 3 versions. I am now > planning to reinstall Python 3.2 using "sudo apt-get install python3" My advice is: - If your distro supports the version of Python you want, install it using your distro's package management tools. - If it doesn't, or if you need special built-time options that your distro doesn't support, then build from source, but make sure you use the "altinstall" option to avoid changing the "python" symbolic link. You may even want to install into a directory different from the default, which allows you to have multiple installations of the same X.Y version. -- Steven From alan.gauld at btinternet.com Wed Sep 25 02:37:09 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Sep 2013 01:37:09 +0100 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474187693A8@SCACMX008.exchad.jpmchase.net> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1380028837.84275.YahooMailNeo@web163801.mail.gq1.yahoo.com> <5B80DD153D7D744689F57F4FB69AF474187693A8@SCACMX008.exchad.jpmchase.net> Message-ID: On 24/09/13 19:22, Prasad, Ramit wrote: > Why uninstall via Synaptic? If he manually installed from source He installed 3.3 from source. 3.2 was already there courtesy of Mint. Therefore, he should have uninstalled 3.2 via Synaptic. Reinstalling 3.2 via synaptic and then uninstalling it, may clean things up a bit better than rm -rf... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From brianjamesarb at gmail.com Wed Sep 25 03:14:47 2013 From: brianjamesarb at gmail.com (brian arb) Date: Tue, 24 Sep 2013 21:14:47 -0400 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: <26330B59-B893-4127-AA60-ECAD3D33E96E@s.dcsdk12.org> References: <1379708827.67739.BPMail_high_noncarrier@web184705.mail.ne1.yahoo.com> <1379734001.35687.YahooMailNeo@web184701.mail.ne1.yahoo.com> <26330B59-B893-4127-AA60-ECAD3D33E96E@s.dcsdk12.org> Message-ID: http://mcsp.wartburg.edu/zelle/python/ppics1/code/chapter05/futval_graph2.py On Tue, Sep 24, 2013 at 4:36 PM, School wrote: > What is the error you received? What lines does it say are causing the > error? > > Also, this smells like classwork. > > On Sep 20, 2013, at 21:26, znxm0i at yahoo.com wrote: > > Can anyone please help me figure out what I am NOT doing to make this > program work properly.....PLEASE !! > > I need to be able to take the user input that is entered in the two > graphical boxes of the first window and evaluate it to generate a graph > chart which is suppose to display in the second window. I am totally at a > loss for what I am NOT doing, and I know it is something so simple that I > am overlooking because I am making this harder that what it most likely > really is. > > But I just cannot get it to work properly. Please HELP !!! Help me > understand what I am doing wrong and how to fix it. I believe I am on the > right path but I'm becoming frustrated and discouraged. > > I have attached a copy of the code I've compiled so far. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Sep 25 05:54:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 25 Sep 2013 13:54:34 +1000 Subject: [Tutor] AntiSpam measures circumventing In-Reply-To: References: <523C60A2.3090902@gmail.com> Message-ID: <20130925035434.GM7989@ando> On Tue, Sep 24, 2013 at 02:00:54PM +0200, Luca Ferrari wrote: > On Fri, Sep 20, 2013 at 4:50 PM, Jugurtha Hadjar > wrote: > > > Supposing my name is John Doe and the e-mail is john.doe at hotmail.com, my > > e-mail was written like this: > > > > REMOVEMEjohn.doSPAMeSPAM at REMOVEMEhotmail.com' I don't think very many spammers bother with harvesting email addresses from web sites these days. It's much easier to just buy a list of 20 million email addresses from some marketing company, which probably got them from Facebook, or harvest them from people's Outlook address book via spyware. > This is the point: how easy you want to make the email for a human > being. I use a tiny bit of Javascript, like this: plus a bit of HTML like this: If a visitor has Javascript enabled, which I expect will cover 95% of visitors, they see a mailto link. The rest see something trivial to reverse into a real email address. And even that, I'm wondering if I'm being too cautious. -- Steven From chris at chrisdown.name Wed Sep 25 08:45:27 2013 From: chris at chrisdown.name (Chris Down) Date: Wed, 25 Sep 2013 08:45:27 +0200 Subject: [Tutor] AntiSpam measures circumventing In-Reply-To: <20130925035434.GM7989@ando> References: <523C60A2.3090902@gmail.com> <20130925035434.GM7989@ando> Message-ID: <20130925064526.GE604@chrisdown.name> On 2013-09-25 13:54, Steven D'Aprano wrote: > And even that, I'm wondering if I'm being too cautious. Well, if you post on mailing lists, undoubtedly your e-mail has been posted in plaintext somewhere. I personally have my e-mail in plaintext on chrisdown.name, and very rarely receive spam through this e-mail address. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From ljetibo at gmail.com Wed Sep 25 03:15:32 2013 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Wed, 25 Sep 2013 03:15:32 +0200 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code Message-ID: Hello, I wrote a response on the subject in the title about creating a graph in Python using the Graphics module presented in the standard python tutorial on 23rd detailing full explanations but I still saw repeated responses asking more of the same question (lines causing the error, which graphics module are you referring to etc...) which is ok because I don't mind multiple answers to the question, not everything usually gets covered in only one and it's a check up if I answered something wrong. But it still kind of bothered me that so many of same questions got repeated so I googled to see the archives and it seems my response was not placed in the same archive "thread" as it should have been, and doesn't appear in the response list of the question. original question: http://code.activestate.com/lists/python-tutor/96889/ my response: http://code.activestate.com/lists/python-tutor/96897/ For someone browsing through Tutor in archive form I can see how this is a tad confusing, is it fixable? I'm guessing that my mail wasn't put in the response list because of different titles? Regards, Dino From oscar.j.benjamin at gmail.com Wed Sep 25 11:58:27 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 25 Sep 2013 10:58:27 +0100 Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: <20130924232531.GK7989@ando> References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <20130924232531.GK7989@ando> Message-ID: On 25 September 2013 00:25, Steven D'Aprano wrote: > On Tue, Sep 24, 2013 at 01:33:23PM +0100, Oscar Benjamin wrote: > >> If you want to mess with your system 'sudo rm -rf' is definitely the >> way to go. Don't bother reporting this as a bug since you've >> *definitely* voided the warranty (that your free software didn't come >> with). > > I first read that as "sudo rm -rf ." and thought "That's a bit harsh, > isn't it?" I guess it does seem harsh but it's definitely true. Albert-Jan still hasn't explained what he was trying to achieve with that command but I stand by my claim that whatever it was can be achieved in a better and safer way. If you try 'sudo apt-get remove python3' then apt will check the database of installed packages to see if anything depends on the python3 package. If nothing depends on it then it will be safely removed and the apt database will be updated to reflect the fact that it is no longer installed. Otherwise it will report the full list of packages that would also need to be removed because they depend on python3 and ask if you want to remove all of them. At this point you'll probably think "What on earth are all those packages? Maybe I need them." and then answer no. On the other hand 'sudo rm -rf /some/system/dir' will check nothing and will simply remove the files. The combination of sudo and the -f flag means "I know what I'm doing so shut up and do what I say". I rarely feel confident enough to do that and I can't think of the last time I had a reason to do it. I regularly use 'rm -rf' because that's needed to delete e.g. a git repository which contains a whole load of files marked as read-only. Without the -f you'll have to answer 'y' thousands of times. But I don't usually have git repositories that are owned by root so I don't need the sudo part (I have sometimes used git to manage system files like fstab, grub etc.). Oscar From eryksun at gmail.com Wed Sep 25 12:29:30 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 25 Sep 2013 06:29:30 -0400 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: References: Message-ID: On Tue, Sep 24, 2013 at 9:15 PM, Dino Bekte?evi? wrote: > > original question: http://code.activestate.com/lists/python-tutor/96889/ > my response: http://code.activestate.com/lists/python-tutor/96897/ > > For someone browsing through Tutor in archive form I can see how this > is a tad confusing, is it fixable? I'm guessing that my mail wasn't > put in the response list because of different titles? Alan's reply, for example, has an In-Reply-To field: In-Reply-To: <1379734001.35687.YahooMailNeo at web184701.mail.ne1.yahoo.com> Your message's header doesn't have this field: From ljetibo at gmail.com Mon Sep 23 23:17:00 2013 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Mon, 23 Sep 2013 23:17:00 +0200 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code (znxm0i at yahoo.com) Message-ID: Source: http://mail.python.org/pipermail/tutor From davea at davea.name Wed Sep 25 12:45:57 2013 From: davea at davea.name (Dave Angel) Date: Wed, 25 Sep 2013 10:45:57 +0000 (UTC) Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code References: Message-ID: On 24/9/2013 21:15, Dino Bekte?evi? wrote: > Hello, > > I wrote a response on the subject in the title about creating a graph > in Python using the Graphics module presented in the standard python > tutorial on 23rd detailing full explanations but I still saw repeated > responses asking more of the same question (lines causing the error, > which graphics module are you referring to etc...) which is ok because > I don't mind multiple answers to the question, not everything usually > gets covered in only one and it's a check up if I answered something > wrong. > > But it still kind of bothered me that so many of same questions got > repeated so I googled to see the archives and it seems my response was > not placed in the same archive "thread" as it should have been, and > doesn't appear in the response list of the question. > > original question: http://code.activestate.com/lists/python-tutor/96889/ > my response: http://code.activestate.com/lists/python-tutor/96897/ > > For someone browsing through Tutor in archive form I can see how this > is a tad confusing, is it fixable? I'm guessing that my mail wasn't > put in the response list because of different titles? > I can't answer for some third-party archive of the list. But your message on the current mailing list doesn't seem to be a reply to any existing one. I'm viewing the list through the news.gmane.org feed, and it is happy to thread messages and their responses nicely, regardless of subject line. How did you respond to the earlier message? Did you just compose a new one and address it to the mailing list? -- DaveA From znxm0i at yahoo.com Wed Sep 25 13:48:44 2013 From: znxm0i at yahoo.com (znxm0i at yahoo.com) Date: Wed, 25 Sep 2013 04:48:44 -0700 (PDT) Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code Message-ID: <1380109724.43081.BPMail_high_carrier@web184702.mail.ne1.yahoo.com> Thanks Brian for replying but I already figured out what I was not doing correctly....also the link you supplied was not what I needed.....I had to make the user input statements appear as graphical input boxes and not just text and I figured out how to do it, so it now works like a charm ------------------------------ On Tue, Sep 24, 2013 8:14 PM CDT brian arb wrote: >http://mcsp.wartburg.edu/zelle/python/ppics1/code/chapter05/futval_graph2.py > > >On Tue, Sep 24, 2013 at 4:36 PM, School wrote: > >> What is the error you received? What lines does it say are causing the >> error? >> >> Also, this smells like classwork. >> >> On Sep 20, 2013, at 21:26, znxm0i at yahoo.com wrote: >> >> Can anyone please help me figure out what I am NOT doing to make this >> program work properly.....PLEASE !! >> >> I need to be able to take the user input that is entered in the two >> graphical boxes of the first window and evaluate it to generate a graph >> chart which is suppose to display in the second window. I am totally at a >> loss for what I am NOT doing, and I know it is something so simple that I >> am overlooking because I am making this harder that what it most likely >> really is. >> >> But I just cannot get it to work properly. Please HELP !!! Help me >> understand what I am doing wrong and how to fix it. I believe I am on the >> right path but I'm becoming frustrated and discouraged. >> >> I have attached a copy of the code I've compiled so far. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> From Robert.Treder at morganstanley.com Wed Sep 25 18:09:35 2013 From: Robert.Treder at morganstanley.com (Treder, Robert) Date: Wed, 25 Sep 2013 12:09:35 -0400 Subject: [Tutor] How to create dictionaries loadable with import In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47418769739@SCACMX008.exchad.jpmchase.net> References: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> <5B80DD153D7D744689F57F4FB69AF47418769739@SCACMX008.exchad.jpmchase.net> Message-ID: <1887C2BD364F214092B7A9942539179A022D41872EC2@NYWEXMBX2127.msad.ms.com> Thanks for the suggestions and sorry about the errors when I tried to anonymize my code. It's turns out when I ran the code through setup, I had an __init__.py file incorrectly defined which generated the error. The error from the traceback was at the line where I was importing the module. I have it working now. Bob -----Original Message----- From: Prasad, Ramit [mailto:ramit.prasad at jpmorgan.com] Sent: Tuesday, September 24, 2013 6:23 PM To: Treder, Robert (Research); tutor at python.org Subject: RE: How to create dictionaries loadable with import Treder, Robert wrote: > Hi Python tutors, > > I'm fairly new to Python. ?I'm working with Python v2.7.4 and the nltk package on a couple of text > mining projects.? I create several dictionaries that are pretty static. Will probably only be updated > every or month or every couple of months. ?I want to turn those dictionaries into loadable data sets > prior to running a module which uses them.? If I define several dictionaries, dict1, dict2 and dict3, > in a single module named myDict, I'd like to do > > from myDict import * > > I've tried defining the dictionaries in a the myDict module as follows: > > Dict1 = {} > with open('file1, 'rb') as infile: Without the closing quote for file1, this is a SyntaxError. > ??? reader = csv.reader(infile, delimiter = ',') > ??? for row in reader: > ??????? try: > ??????????? Dict1[ row[1] ].append(row[0]) > ??????? except: > ??????????? Dict1[ row[1] ] = [ row[0], ] > > Dict2 = {} > with open('file2, 'rb') as infile: Without the closing quote for file2, this is a SyntaxError. > ??? reader = csv.reader(infile, delimiter = ',') > ??? for row in reader: > ??????? try: > ??????????? Dict2[ row[1] ].append(row[0]) > ??????? except: > ??????????? Dict2[ row[1] ] = [ row[0], ] > > These are simple dictionary structures with no additional structure, i.e., not embedded in classes or > functions. > The try/except sequence is because some of the keys may be duplicated in the files and I want to > append the values rather than overwrite. Hmm, I think you are incorrect. The try/except logic is used when there is not row[1] in the dictionary (i.e. every first entry of a key). I guess that handles multiple keys, but it would be clearer if you used the setdefault method on the dictionary. Dict1.setdefault( row[1], [] ).append( row[0] ) > Now when I build the module with setup tools > > python setup.py install -prefix=C:\PY_MODULES Unless you have a non-standard environment (at least not one I am familiar with), you do not need setup tools as long as the script is somewhere on the PYTHONPATH. Also, the dictionaries are not created except on first import of the module (at run-time not compile-time). If they are static or mostly so, you may want to just hard code them in the myDict module (lowercase for module names is the community standard) for easier modification. In addition, that means you can get rid of the source files file1 and file2. You can use `print repr(Dict1)` to copy paste the dictionaries into the code. > > it builds without error but I can't find the dictionaries when I load the module > ??? from myDict import * > AttributeError: 'module' object has no attribute 'Dict1' > > How can I make the dictionaries loadable using import? The import and the error do not seem to match. Can you please copy/paste (do not paraphrase or try to retype) the FULL error? > > Thanks, > Bob ~Ramit 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. -------------------------------------------------------------------------------- NOTICE: Morgan Stanley is not acting as a municipal advisor and the opinions or views contained herein are not intended to be, and do not constitute, advice within the meaning of Section 975 of the Dodd-Frank Wall Street Reform and Consumer Protection Act. If you have received this communication in error, please destroy all electronic and paper copies and notify the sender immediately. Mistransmission is not intended to waive confidentiality or privilege. Morgan Stanley reserves the right, to the extent permitted under applicable law, to monitor electronic communications. This message is subject to terms available at the following link: http://www.morganstanley.com/disclaimers. If you cannot access these links, please notify us by reply message and we will send the contents to you. By messaging with Morgan Stanley you consent to the foregoing. From fomcl at yahoo.com Wed Sep 25 19:35:51 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 25 Sep 2013 10:35:51 -0700 (PDT) Subject: [Tutor] How to create dictionaries loadable with import In-Reply-To: <1887C2BD364F214092B7A9942539179A022D41872EC2@NYWEXMBX2127.msad.ms.com> References: <1887C2BD364F214092B7A9942539179A022D41872E35@NYWEXMBX2127.msad.ms.com> <5B80DD153D7D744689F57F4FB69AF47418769739@SCACMX008.exchad.jpmchase.net> <1887C2BD364F214092B7A9942539179A022D41872EC2@NYWEXMBX2127.msad.ms.com> Message-ID: <1380130551.91040.YahooMailNeo@web163802.mail.gq1.yahoo.com> ----- Original Message ----- > From: "Treder, Robert" > To: "tutor at python.org" > Cc: > Sent: Wednesday, September 25, 2013 6:09 PM > Subject: Re: [Tutor] How to create dictionaries loadable with import > >T hanks for the suggestions and sorry about the errors when I tried to anonymize > my code. Talking about anonymizing, this is legal: #!/usr/bin/python # -*- coding: rot13 -*-qrs fbzrShap(*netf, **xjnetf): ?????????? cnff ...because: >>> print """qrs fbzrShap(*netf, **xjnetf): ??? cnff""".decode("rot13") def someFunc(*args, **kwargs): ??? pass fun, isn't it? From rafael.knuth at gmail.com Wed Sep 25 19:42:12 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Wed, 25 Sep 2013 19:42:12 +0200 Subject: [Tutor] Writing program: To Do List in Python 3.0 Message-ID: Hej there, I want to write a simple program (To Do List) that stores the input data (action items on To Do List). Currently I can only input items but the program I wrote doesn't store them. Can you help? Thanks, Rafael Here's the code I wrote so far: print("This is my to do list") Monday = input("Monday ") Tuesday = input("Tuesday ") Wednesday = input("Wednesday ") Thursday = input("Thursday ") Friday = input("Friday ") Saturday = input("Saturday ") Sunday = input("Sunday ") print("So, here are your plans for:" + "\nMonday " + Monday + "\nTuesday " + Tuesday + "\nWednesday " + Wednesday + "\nThursday " + Thursday + "\nFriday " + Friday + "\nSaturday " + Saturday + "\nSunday " + Sunday) From fomcl at yahoo.com Wed Sep 25 20:18:06 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 25 Sep 2013 11:18:06 -0700 (PDT) Subject: [Tutor] ImportError: No module named '_sysconfigdata_m' In-Reply-To: References: <1379964490.65242.YahooMailNeo@web163805.mail.gq1.yahoo.com> <1380025132.55290.YahooMailNeo@web163804.mail.gq1.yahoo.com> <20130924232531.GK7989@ando> Message-ID: <1380133086.50808.YahooMailNeo@web163802.mail.gq1.yahoo.com> ----- Original Message ----- > From: Oscar Benjamin > To: Steven D'Aprano > Cc: "Tutor at python.org" > Sent: Wednesday, September 25, 2013 11:58 AM > Subject: Re: [Tutor] ImportError: No module named '_sysconfigdata_m' > > On 25 September 2013 00:25, Steven D'Aprano > wrote: >> On Tue, Sep 24, 2013 at 01:33:23PM +0100, Oscar Benjamin wrote: >> >>> If you want to mess with your system 'sudo rm -rf' is > definitely the >>> way to go. Don't bother reporting this as a bug since you've >>> *definitely* voided the warranty (that your free software didn't > come >>> with). >> >> I first read that as "sudo rm -rf ." and thought "That's > a bit harsh, >> isn't it?" > > I guess it does seem harsh but it's definitely true. Albert-Jan still > hasn't explained what he was trying to achieve with that command but I > stand by my claim that whatever it was can be achieved in a better and > safer way. I just wanted to get rid of Python 3.2 as I thought it had no purpose. Maybe I also could have done apt-get install --only-upgrade python3. apt-get update does not update python 3.2 to 3.3. ? > If you try 'sudo apt-get remove python3'? then apt will check the > database of installed packages to see if anything depends on the > python3 package. Thanks. I will use that from now on. Much better indeed. But isn't it safer to also specify the minor python version? If nothing depends on it then it will be safely > removed and the apt database will be updated to reflect the fact that > it is no longer installed. Otherwise it will report the full list of > packages that would also need to be removed because they depend on > python3 and ask if you want to remove all of them. At this point > you'll probably think "What on earth are all those packages? Maybe I > need them." and then answer no. > > On the other hand 'sudo rm -rf /some/system/dir' will check nothing > and will simply remove the files. The combination of sudo and the -f > flag means "I know what I'm doing so shut up and do what I say". I > rarely feel confident enough to do that and I can't think of the last > time I had a reason to do it. > > I regularly use 'rm -rf' because that's needed to delete e.g. a git > repository which contains a whole load of files marked as read-only. > Without the -f you'll have to answer 'y' thousands of times. But I > don't usually have git repositories that are owned by root so I don't > need the sudo part (I have sometimes used git to manage system files > like fstab, grub etc.). > > > Oscar > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From davea at davea.name Wed Sep 25 21:00:12 2013 From: davea at davea.name (Dave Angel) Date: Wed, 25 Sep 2013 19:00:12 +0000 (UTC) Subject: [Tutor] Writing program: To Do List in Python 3.0 References: Message-ID: On 25/9/2013 13:42, Rafael Knuth wrote: > Hej there, > > I want to write a simple program (To Do List) that stores the input > data (action items on To Do List). Currently I can only input items > but the program I wrote doesn't store them. > > Can you help? > > Thanks, > > Rafael > > Here's the code I wrote so far: > > print("This is my to do list") > > Monday = input("Monday ") > Tuesday = input("Tuesday ") > Wednesday = input("Wednesday ") > Thursday = input("Thursday ") > Friday = input("Friday ") > Saturday = input("Saturday ") > Sunday = input("Sunday ") > > print("So, here are your plans for:" + > "\nMonday " + Monday + > "\nTuesday " + Tuesday + > "\nWednesday " + Wednesday + > "\nThursday " + Thursday + > "\nFriday " + Friday + > "\nSaturday " + Saturday + > "\nSunday " + Sunday) > To have data still available next time you run the program, you need to write it to a file. outfile = open("statefile.txt", "w") outfile.write("Monday") outfile.close() Naturally, if you store non-trivial data, you'll have to organize it somehow, so you can parse it when you read it back in. Alternatively, you can use a module like configparser: http://docs.python.org/3.3/library/configparser.html#module-configparser or several other alternatives. -- DaveA From fomcl at yahoo.com Wed Sep 25 20:51:27 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 25 Sep 2013 11:51:27 -0700 (PDT) Subject: [Tutor] OT: docopt Message-ID: <1380135087.22920.YahooMailNeo@web163803.mail.gq1.yahoo.com> Hi, Docopt is an alternative to optparse and argparse. Incredibly cool, and fun (check out the youtube movie!): http://docopt.org/ Just in case you missed it (like me). Regards, Albert-Jan ?ps: sorry if I posted this twice. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From alan.gauld at btinternet.com Wed Sep 25 21:11:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Sep 2013 20:11:44 +0100 Subject: [Tutor] Writing program: To Do List in Python 3.0 In-Reply-To: References: Message-ID: On 25/09/13 18:42, Rafael Knuth wrote: > I want to write a simple program (To Do List) that stores the input > data (action items on To Do List). Currently I can only input items > but the program I wrote doesn't store them. You need to write the data to a file or database when the program closes and then, when you start the program, read the data from that file or database. > Here's the code I wrote so far: OK, This is very basic and can be improved in lots of ways so I'm guessing you are a new programmer and studying via some kind of course or tutorial? At some stage it will cover reading and writing to files as well as data structures that will help store your data more effectively and looping constructs that will help you process it more effectively. You can read up on reading and writing to files if you want but it may be better not to run before you can walk... > print("This is my to do list") > > Monday = input("Monday ") > Tuesday = input("Tuesday ") > Wednesday = input("Wednesday ") > Thursday = input("Thursday ") > Friday = input("Friday ") > Saturday = input("Saturday ") > Sunday = input("Sunday ") > > print("So, here are your plans for:" + > "\nMonday " + Monday + > "\nTuesday " + Tuesday + > "\nWednesday " + Wednesday + > "\nThursday " + Thursday + > "\nFriday " + Friday + > "\nSaturday " + Saturday + > "\nSunday " + Sunday) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ljetibo at gmail.com Thu Sep 26 00:24:41 2013 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Thu, 26 Sep 2013 00:24:41 +0200 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code Message-ID: > Message: 1 > Date: Wed, 25 Sep 2013 06:29:30 -0400 > From: eryksun > To: Dino Bekte?evi? > Cc: tutor at python.org > Subject: Re: [Tutor] HELP Please!!!....How Do I Make a Graph Chart > Generate in Python Based on my Code > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Tue, Sep 24, 2013 at 9:15 PM, Dino Bekte?evi? wrote: >> >> original question: http://code.activestate.com/lists/python-tutor/96889/ >> my response: http://code.activestate.com/lists/python-tutor/96897/ >> >> For someone browsing through Tutor in archive form I can see how this >> is a tad confusing, is it fixable? I'm guessing that my mail wasn't >> put in the response list because of different titles? > > Alan's reply, for example, has an In-Reply-To field: > > In-Reply-To: <1379734001.35687.YahooMailNeo at web184701.mail.ne1.yahoo.com> > > Your message's header doesn't have this field: > > From ljetibo at gmail.com Mon Sep 23 23:17:00 2013 > From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) > Date: Mon, 23 Sep 2013 23:17:00 +0200 > Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate > in Python Based on my Code (znxm0i at yahoo.com) > Message-ID: > > > Source: > > http://mail.python.org/pipermail/tutor > Where did you find that In-Reply-To: field? In example Alan's response header, including the quoted section is shown to me as: Message: 4 Date: Mon, 23 Sep 2013 18:21:03 +0100 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 21/09/13 04:26, znxm0i at yahoo.com wrote: > Can anyone please help me figure out what I am NOT doing to make this > program work properly.....PLEASE !! Which is the same for any response header I see. It doesn't seem to be something I edit at all. > Message: 2 > Date: Wed, 25 Sep 2013 10:45:57 +0000 (UTC) > From: Dave Angel > To: tutor at python.org > Subject: Re: [Tutor] HELP Please!!!....How Do I Make a Graph Chart > Generate in Python Based on my Code > Message-ID: > Content-Type: text/plain; charset=ISO-8859-2 > > On 24/9/2013 21:15, Dino Bekte?evi? wrote: > > I can't answer for some third-party archive of the list. But your > message on the current mailing list doesn't seem to be a reply to any > existing one. I'm viewing the list through the news.gmane.org feed, and > it is happy to thread messages and their responses nicely, regardless of > subject line. > > How did you respond to the earlier message? Did you just compose a new > one and address it to the mailing list? > > > -- > DaveA I use gmail and just use the "funny" looking arrow at the top that says "reply" and I can see that in the news.gmane.org feed my mail is sorted nicely in the response section but it isn't on either code.activestate or on mail.python.org as eryksun stated as well. I just want to be able to make my responses easily visible in most of the online archives since otherwise they don't make sense for anyone not subscribed to the daily mailing list. Regards, Dino From davea at davea.name Thu Sep 26 03:34:48 2013 From: davea at davea.name (Dave Angel) Date: Thu, 26 Sep 2013 01:34:48 +0000 (UTC) Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code References: Message-ID: On 25/9/2013 18:24, Dino Bekte?evi? wrote: > > Where did you find that In-Reply-To: field? In example Alan's response > header, including the quoted section is shown to me as: > > Message: 4 > Date: Mon, 23 Sep 2013 18:21:03 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] HELP Please!!!....How Do I Make a Graph Chart > Generate in Python Based on my Code > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > Clearly gmail isn't showing you all the headers. I looked for Alan's message in one of these threads with the same subject, and see about 60 lines of header information. Does gmail have a View->Source menu item? Here's a small excerpt: User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20130804 Thunderbird/17.0.8 In-Reply-To: <1379734001.35687.YahooMailNeo at web184701.mail.ne1.yahoo.com> X-BeenThere: tutor at python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: Discussion for learning programming with Python List-Unsubscribe: , -- DaveA From eryksun at gmail.com Thu Sep 26 04:35:49 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 25 Sep 2013 22:35:49 -0400 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: References: Message-ID: On Wed, Sep 25, 2013 at 6:24 PM, Dino Bekte?evi? wrote: > > Where did you find that In-Reply-To: field? In example Alan's response > header Gmail has a "Show original" link in the message drop-down menu. But in this case I just searched the September text archive: https://mail.python.org/pipermail/tutor/2013-September.txt I replied to you using Gmail's "Reply to all" in the webmail interface, which added "In-Reply-To" and "References" to the header. RFC 2822: http://www.ietf.org/rfc/rfc2822.txt The "In-Reply-To:" and "References:" fields are used when creating a reply to a message. They hold the message identifier of the original message and the message identifiers of other messages (for example, in the case of a reply to a message which was itself a reply). The "In-Reply-To:" field may be used to identify the message (or messages) to which the new message is a reply, while the "References:" field may be used to identify a "thread" of conversation. When creating a reply to a message, the "In-Reply-To:" and "References:" fields of the resultant message are constructed as follows: The "In-Reply-To:" field will contain the contents of the "Message- ID:" field of the message to which this one is a reply (the "parent message"). If there is more than one parent message, then the "In- Reply-To:" field will contain the contents of all of the parents' "Message-ID:" fields. If there is no "Message-ID:" field in any of the parent messages, then the new message will have no "In-Reply-To:" field. The "References:" field will contain the contents of the parent's "References:" field (if any) followed by the contents of the parent's "Message-ID:" field (if any). If the parent message does not contain a "References:" field but does have an "In-Reply-To:" field containing a single message identifier, then the "References:" field will contain the contents of the parent's "In-Reply-To:" field followed by the contents of the parent's "Message-ID:" field (if any). If the parent has none of the "References:", "In-Reply-To:", or "Message-ID:" fields, then the new message will have no "References:" field. Note: Some implementations parse the "References:" field to display the "thread of the discussion". These implementations assume that each new message is a reply to a single parent and hence that they can walk backwards through the "References:" field to find the parent of each message listed there. Therefore, trying to form a "References:" field for a reply that has multiple parents is discouraged and how to do so is not defined in this document. From steve at pearwood.info Thu Sep 26 13:14:49 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 26 Sep 2013 21:14:49 +1000 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: References: Message-ID: <20130926111449.GN7989@ando> On Thu, Sep 26, 2013 at 12:24:41AM +0200, Dino Bekte?evi? wrote: > > Message: 1 and later: > Message: 4 I don't suppose you are replying to a message digest, are you? If so, thank you for changing the subject line to something more useful than just "Re Digest", and thank you even more for trimming the content of your reply. But by replying to digests, you lose useful threading information. In my opinion, digests are not terribly useful. If they have any use at all, it is only for those who want to read emails in the mailing list, then either keep them all, or delete them all. If you want to select which threads or messages to keep, digests are useless, and if you intend to carry on a conversation or discussion, they're even more useless. Of course, I may be misinterpreting the "Message" numbers above, in which case, sorry for the noise. -- Steven From rafael.knuth at gmail.com Thu Sep 26 13:29:23 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 26 Sep 2013 13:29:23 +0200 Subject: [Tutor] Writing program: To Do List in Python 3.0 In-Reply-To: References: Message-ID: Alan, On Wed, Sep 25, 2013 at 9:11 PM, Alan Gauld wrote: > On 25/09/13 18:42, Rafael Knuth wrote: > >> I want to write a simple program (To Do List) that stores the input >> data (action items on To Do List). Currently I can only input items >> but the program I wrote doesn't store them. > > > You need to write the data to a file or database when the program closes and > then, when you start the program, read the data from > that file or database. Thank you for the clarification. > > >> Here's the code I wrote so far: > > > OK, This is very basic and can be improved in lots of ways so I'm guessing > you are a new programmer and studying via some kind of > course or tutorial? Self study, yes. Intermediate beginner. I just started writing games such as Hangman, Tic Tac Toe. Now I wanted to write a small To Do List which requires reading and writing to files as you explained (which is exactly what I want to learn now). > > At some stage it will cover reading and writing to files as well as data > structures that will help store your data more effectively and looping > constructs that will help you process it more effectively. > > You can read up on reading and writing to files if you want but > it may be better not to run before you can walk... Consider me a toddler. Can you advise how I should proceed in order to improve my To Do List program based on the code I wrote so far (insofar it's usable at all) ..? Weirdly, writing and reading to files is not covered in those tutorials I am working with. Thank you, Rafael > >> print("This is my to do list") >> >> Monday = input("Monday ") >> Tuesday = input("Tuesday ") >> Wednesday = input("Wednesday ") >> Thursday = input("Thursday ") >> Friday = input("Friday ") >> Saturday = input("Saturday ") >> Sunday = input("Sunday ") >> >> print("So, here are your plans for:" + >> "\nMonday " + Monday + >> "\nTuesday " + Tuesday + >> "\nWednesday " + Wednesday + >> "\nThursday " + Thursday + >> "\nFriday " + Friday + >> "\nSaturday " + Saturday + >> "\nSunday " + Sunday) > > > > -- > 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From davea at davea.name Thu Sep 26 14:02:41 2013 From: davea at davea.name (Dave Angel) Date: Thu, 26 Sep 2013 12:02:41 +0000 (UTC) Subject: [Tutor] Writing program: To Do List in Python 3.0 References: Message-ID: On 26/9/2013 07:29, Rafael Knuth wrote: > Can you advise how I should proceed in order to > improve my To Do List program based on the code I wrote so far > (insofar it's usable at all) ..? Weirdly, writing and reading to files > is not covered in those tutorials I am working with. > >> >>> print("This is my to do list") >>> >>> Monday = input("Monday ") >>> Tuesday = input("Tuesday ") >>> Wednesday = input("Wednesday ") >>> Thursday = input("Thursday ") >>> Friday = input("Friday ") >>> Saturday = input("Saturday ") >>> Sunday = input("Sunday ") >>> >>> print("So, here are your plans for:" + >>> "\nMonday " + Monday + >>> "\nTuesday " + Tuesday + >>> "\nWednesday " + Wednesday + >>> "\nThursday " + Thursday + >>> "\nFriday " + Friday + >>> "\nSaturday " + Saturday + >>> "\nSunday " + Sunday) >> First comment: learn to use functions. Don't put anything in top-level code except: imports global constant values, in all uppercase NAMES the canonical if __name__ == "__main__": main() Later, with more experience, you'll find times to make exceptions to that rule. Your functions should usually take paramaters and return their results. Avoid writable global values. If you need to return more than one results, learn to use tuples for that, with automatic tuple unpacking where appropriate. Next, look for places where you do practically the same thing many times. They are a good candidate for factoring into a loop, or a loop calling a common function. Next, look for data structures that can naturally describe the data you're manipulating. For example, instead of the variables "Monday", "Tuesday", etc, you could make a dict where those are the keys, and the "todo items" are the values. Once you're used to writing (small) functions, figure on separating input, output, and data manipulation into three (usually) functions. For example, you'll be filling in those values from the user, and also from an input file. You'll be saving the results to the screen, and also to an output file. Now, consider the user and what he'll want to do. He may not know all 7 days items at the same time, or he may be entering Friday's value, and suddenly remember a change needed on Tuesday's. So give him a way to tell-the-program what he wants to do next. In my earlier message, I mentioned the standard module configparser. That's because it's similar to a dictionary. And also because it can be readily understood and edited with a text editor. It's not the most commonly used tool for the purpose, but it'd suit your present needs pretty well, and be easy to experiment. My reason is the next comment. Try to write functions that can be tested independently. So if you're saving and reloading data, if you can manually create the data (file) easily, then you can test your "reloading" function independently of the "saving" function. -- DaveA From rafael.knuth at gmail.com Thu Sep 26 14:18:08 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 26 Sep 2013 14:18:08 +0200 Subject: [Tutor] Writing program: To Do List in Python 3.0 In-Reply-To: References: Message-ID: Dave, thank you so much, I will proceed as you suggested. Currently, I am not 100% sure I get it right, but I will start iterating now. All the best, Rafael > > Can you advise how I should proceed in order to > > improve my To Do List program based on the code I wrote so far > > (insofar it's usable at all) ..? Weirdly, writing and reading to files > > is not covered in those tutorials I am working with. > > > First comment: learn to use functions. Don't put anything in top-level > > Your functions should usually take paramaters and return their results. > Avoid writable global values. If you need to return more than one > results, learn to use tuples for that, with automatic tuple unpacking > where appropriate. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Sep 26 14:57:52 2013 From: davea at davea.name (Dave Angel) Date: Thu, 26 Sep 2013 12:57:52 +0000 (UTC) Subject: [Tutor] Writing program: To Do List in Python 3.0 References: Message-ID: On 26/9/2013 08:18, Rafael Knuth wrote: > Dave, > > thank you so much, I will proceed as you suggested. > Currently, I am not 100% sure I get it right, but I will start iterating > now. > Please don't top-post. Put your comments under the relevant part(s) of the previous message, and delete the rest. Do include the attribution line, of course. Next, i'd say: try just one of these ideas, and if it's at all confusing, post the errant code here, with a corresponding question. if something doesn't work, indicate what you expected, and in what way it didn't meet those expectations. And if you're puzzled about an error (exception), post the full traceback including the error. And don't forget all the built-in and online help available directly from python. All of us use help() and dir() to remind ourselves of something, even if we already "know" it. And it's not hard to search for things online, especially on the python.org site. When I used to use Windows, I installed the ActivePython from ActiveState website. Not only does it have some additional win32 functionality, but it also has a chm file which I found was easier to find stuff in than other formats. I don't know if that's still true. http://www.activestate.com/activepython -- DaveA From drobinow at gmail.com Thu Sep 26 15:06:13 2013 From: drobinow at gmail.com (David Robinow) Date: Thu, 26 Sep 2013 09:06:13 -0400 Subject: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code In-Reply-To: References: Message-ID: On Wed, Sep 25, 2013 at 9:34 PM, Dave Angel wrote: > Clearly gmail isn't showing you all the headers. I looked for Alan's > message in one of these threads with the same subject, and see about 60 > lines of header information. Does gmail have a View->Source menu item? > In gmail the menu item is "Show Original" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 26 16:02:37 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Sep 2013 15:02:37 +0100 Subject: [Tutor] Writing program: To Do List in Python 3.0 In-Reply-To: References: Message-ID: On 26/09/13 12:29, Rafael Knuth wrote: >> At some stage it will cover reading and writing to files as well as data >> structures that will help store your data more effectively and looping >> constructs that will help you process it more effectively. >> ... > (insofar it's usable at all) ..? Weirdly, writing and reading to files > is not covered in those tutorials I am working with. Really? Then I'd consider finding another tutorial file access is pretty fundamental to any non trivial program. You could try mine(see below) or any of the many other tutorials available. >>> print("This is my to do list") >>> >>> Monday = input("Monday ") >>> Tuesday = input("Tuesday ") >>> Wednesday = input("Wednesday ") >>> Thursday = input("Thursday ") >>> Friday = input("Friday ") >>> Saturday = input("Saturday ") >>> Sunday = input("Sunday ") This has lots of problems. What happens if you have more than one thing to do on any given day? What if you want more than one week? Data collections such as lists and dictionaries can cope with those situations much better. days = {} days['Monday'] = input('What to do on Monday?') print days['Monday'] etc. Using loops covers the multi-todo situation: events = [] for current in ('Monday','Tuesday',...etc): while True: event = input('What to do?') if not event: break # exit loop on empty input else: events.append(event) days[current] = events Or you could pick a day from a menu... >>> print("So, here are your plans for:" + >>> "\nMonday " + Monday + >>> "\nTuesday " + Tuesday + >>> "\nWednesday " + Wednesday + >>> "\nThursday " + Thursday + >>> "\nFriday " + Friday + >>> "\nSaturday " + Saturday + >>> "\nSunday " + Sunday) Again a loop will do this: for day in days: print day for event in events: print '\t' + event That would produce output like: Monday go to doctor go to funeral parlour Tuesday die Wednesday get buried 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 at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jackiexxduh3 at gmail.com Fri Sep 27 07:48:26 2013 From: jackiexxduh3 at gmail.com (Jacqueline Canales) Date: Fri, 27 Sep 2013 00:48:26 -0500 Subject: [Tutor] List Python Question..Please help Message-ID: So I have been trying to do this program using ifs and or loops. I am having a hard time solving this question, If you could please assist me in the right direction. Write a program that lists all the composers on the list ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and ends with the same letter (so Nielsen gets lsited, but Antheil doesn't). I know below it prints the entire list of composers but i dont know how to do the program above. I think I am thinking to much into but ive looked at all my notes and online resources and having a hard time coming up with anything. Please help! composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] for person in composers: print(person) -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Fri Sep 27 09:44:49 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 27 Sep 2013 17:44:49 +1000 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales wrote: > So I have been trying to do this program using ifs and or loops. > I am having a hard time solving this question, If you could please assist me > in the right direction. > > Write a program that lists all the composers on the list ['Antheil', > 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and ends > with the same letter (so Nielsen gets lsited, but Antheil doesn't). > > I know below it prints the entire list of composers but i dont know how to > do the program above. I think I am thinking to much into but ive looked at > all my notes and online resources and having a hard time coming up with > anything. > Please help! > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > for person in composers: > print(person) So, here you are printing every compose as you rightly state above. What you now need to do is: For each of the composers (`person'), you need to check if the first letter and the last letter are the same. Here;s a hint: >>> s='abba' The first letter: >>> s[0] 'a' The last letter: >>> s[-1] 'a' If you now compare these, you will know if they are the same and hence you print him/her. Hope that helps. -Amit. -- http://echorand.me From shahdharmit at gmail.com Fri Sep 27 09:57:45 2013 From: shahdharmit at gmail.com (Dharmit Shah) Date: Fri, 27 Sep 2013 13:27:45 +0530 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the same. Hope that helps. :) On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha wrote: > On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales > wrote: >> So I have been trying to do this program using ifs and or loops. >> I am having a hard time solving this question, If you could please assist me >> in the right direction. >> >> Write a program that lists all the composers on the list ['Antheil', >> 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and ends >> with the same letter (so Nielsen gets lsited, but Antheil doesn't). >> >> I know below it prints the entire list of composers but i dont know how to >> do the program above. I think I am thinking to much into but ive looked at >> all my notes and online resources and having a hard time coming up with >> anything. >> Please help! >> >> composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] >> for person in composers: >> print(person) > > So, here you are printing every compose as you rightly state above. > What you now need to do is: > > For each of the composers (`person'), you need to check if the first > letter and the last letter are the same. Here;s a hint: > >>>> s='abba' > > The first letter: > >>>> s[0] > 'a' > > The last letter: > >>>> s[-1] > 'a' > > > If you now compare these, you will know if they are the same and hence > you print him/her. > > Hope that helps. > -Amit. > > > -- > http://echorand.me > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Dharmit Shah www.about.me/dharmit From alan.gauld at btinternet.com Fri Sep 27 10:01:00 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Sep 2013 09:01:00 +0100 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: On 27/09/13 06:48, Jacqueline Canales wrote: > So I have been trying to do this program using ifs and or loops. > I am having a hard time solving this question, If you could please > assist me in the right direction. Happy to. We won't do the homework for you but we will ask leading questions and give hints. > I know below it prints the entire list of composers but i dont know how > to do the program above. OK, breaking it into three parts: 1) print names from the list - you can do that already 2) test if a name starts and ends with the same letter - Amit has shown you how to get the letters, do you know how to test for equality (using the == operator)? 3) Filter the printout based on the test in (2) - Do you know how to use an if statement to take action depending on the outcome of a test? Your code should then look like for person in persons: if print person If there are still things you are unclear about ask here and we will break it down further. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Fri Sep 27 11:52:13 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 27 Sep 2013 19:52:13 +1000 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: <20130927095213.GO7989@ando> Hi Jacqueline, and welcome! Further information below... On Fri, Sep 27, 2013 at 12:48:26AM -0500, Jacqueline Canales wrote: > Write a program that lists all the composers on the list ['Antheil', > 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and > ends with the same letter (so Nielsen gets lsited, but Antheil doesn't). > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > for person in composers: > print(person) One of the secrets to programming is to write out the instructions to solve the problem in English (or whatever your native language is), as if you were giving instructions to some other person, telling them what to do. Then you just need to make those instructions more and more precise, more and more detailed, as computers are much dumber than any person. For instance, you might start off with: Look at each composer's name, and print it only if it begins and ends with the same letter. The computer doesn't understand "look at each composer's name", but you know how to tell the computer the same thing: composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] for person in composers: so you're already half-way there. "print it only if" needs to be written the other way around: if it begins and ends with the same letter, print it The computer doesn't know what "it" is, so you have to spell it out explicitly: if person begins and ends with the same letter, print person Change the syntax to match what the Python programming language expects: if person begins and ends with the same letter: print person Now the only bit still to be solved is to work out the "begins and ends" part. I'm not going to give you the answer to this, but I will give you a few hints. If you copy and paste the following lines into the Python interpreter and see what they print, they should point you in the right direction: name = "Beethovan" print "The FIRST letter of his name is", name[0] print "The LAST letter of his name is", name[-1] print "Are the SECOND and THIRD letters equal?", name[1] == name[2] print "Does X equal x?", 'X' == 'x' print "Convert a string to lowercase:", name.lower() Good luck, and don't hesitate to come back if you need any further help. -- Steven From bharathks123 at yahoo.com Fri Sep 27 16:07:39 2013 From: bharathks123 at yahoo.com (bharath ks) Date: Fri, 27 Sep 2013 22:07:39 +0800 (SGT) Subject: [Tutor] Help on class Message-ID: <1380290859.63743.YahooMailNeo@web192501.mail.sg3.yahoo.com> Hello, May i know why object 'c' does not prompt for employee name and employee id in the following code i get out put as? Enter employee name:john Enter employee id:56 Employee name is: john Employee id is: 56 ---------------------------------------------------- Employee name is: test Employee id is: 1003 ---------------------------------------------------- Employee name is: john Employee id is: 56 class employee: ? ? emp_name="" ? ? emp_id=0 ? ? def collect_name(): ? ? ? ? return(input("Enter employee name:")) ? ? ? ?? ? ? def collect_id(): ? ? ? ? return(input("Enter employee id:")) ? ? ? ? ? ?? ? ? def show(self): ? ? ? ? print("Employee name is:",self.emp_name) ? ? ? ? print("Employee id is:",self.emp_id) ? ? ? ?? ? ? def __init__(self,name=collect_name(),id=collect_id()): ? ? ? ? self.emp_name=name ? ? ? ? self.emp_id=id ? ? ? ?? ?? a=employee() a.show() print("----------------------------------------------------") b=employee("test",1003) b.show() print("----------------------------------------------------") c=employee() c.show() ? Thanks & BR, Bharath Shetty -------------- next part -------------- An HTML attachment was scrubbed... URL: From jackiexxduh3 at gmail.com Fri Sep 27 19:04:38 2013 From: jackiexxduh3 at gmail.com (Jacqueline Canales) Date: Fri, 27 Sep 2013 12:04:38 -0500 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] x = 'Antheil' s = 'Saint-Saens' h = 'Beethoven' y = 'Easdale' k = 'Nielsen' if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': print(s,k,y) else: print(" ") ####Answer i Got Below >>> Saint-Saens Nielsen Easdale >>> Is this what i was going for in the direction i was a bit confused if we were suppose create loops or if statements that are verified in the actual composers list. I don't know i feel as if i know what i need to do i just cant put it together. On Fri, Sep 27, 2013 at 3:14 AM, ?? wrote: > Maybe the length of each name matters, too. You should consider whether to > skip null('') and single-character('a'). > > > On Fri, Sep 27, 2013 at 3:57 PM, Dharmit Shah wrote: > >> Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the same. >> >> Hope that helps. :) >> >> On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha wrote: >> > On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales >> > wrote: >> >> So I have been trying to do this program using ifs and or loops. >> >> I am having a hard time solving this question, If you could please >> assist me >> >> in the right direction. >> >> >> >> Write a program that lists all the composers on the list ['Antheil', >> >> 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts >> and ends >> >> with the same letter (so Nielsen gets lsited, but Antheil doesn't). >> >> >> >> I know below it prints the entire list of composers but i dont know >> how to >> >> do the program above. I think I am thinking to much into but ive >> looked at >> >> all my notes and online resources and having a hard time coming up with >> >> anything. >> >> Please help! >> >> >> >> composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', >> 'Nielsen'] >> >> for person in composers: >> >> print(person) >> > >> > So, here you are printing every compose as you rightly state above. >> > What you now need to do is: >> > >> > For each of the composers (`person'), you need to check if the first >> > letter and the last letter are the same. Here;s a hint: >> > >> >>>> s='abba' >> > >> > The first letter: >> > >> >>>> s[0] >> > 'a' >> > >> > The last letter: >> > >> >>>> s[-1] >> > 'a' >> > >> > >> > If you now compare these, you will know if they are the same and hence >> > you print him/her. >> > >> > Hope that helps. >> > -Amit. >> > >> > >> > -- >> > http://echorand.me >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > https://mail.python.org/mailman/listinfo/tutor >> >> >> >> -- >> Dharmit Shah >> www.about.me/dharmit >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From luopeng.he at gmail.com Fri Sep 27 10:14:45 2013 From: luopeng.he at gmail.com (=?UTF-8?B?572X5b2t?=) Date: Fri, 27 Sep 2013 16:14:45 +0800 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: Maybe the length of each name matters, too. You should consider whether to skip null('') and single-character('a'). On Fri, Sep 27, 2013 at 3:57 PM, Dharmit Shah wrote: > Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the same. > > Hope that helps. :) > > On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha wrote: > > On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales > > wrote: > >> So I have been trying to do this program using ifs and or loops. > >> I am having a hard time solving this question, If you could please > assist me > >> in the right direction. > >> > >> Write a program that lists all the composers on the list ['Antheil', > >> 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and > ends > >> with the same letter (so Nielsen gets lsited, but Antheil doesn't). > >> > >> I know below it prints the entire list of composers but i dont know > how to > >> do the program above. I think I am thinking to much into but ive looked > at > >> all my notes and online resources and having a hard time coming up with > >> anything. > >> Please help! > >> > >> composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', > 'Nielsen'] > >> for person in composers: > >> print(person) > > > > So, here you are printing every compose as you rightly state above. > > What you now need to do is: > > > > For each of the composers (`person'), you need to check if the first > > letter and the last letter are the same. Here;s a hint: > > > >>>> s='abba' > > > > The first letter: > > > >>>> s[0] > > 'a' > > > > The last letter: > > > >>>> s[-1] > > 'a' > > > > > > If you now compare these, you will know if they are the same and hence > > you print him/her. > > > > Hope that helps. > > -Amit. > > > > > > -- > > http://echorand.me > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > -- > Dharmit Shah > www.about.me/dharmit > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From xrandomheartzx at aim.com Fri Sep 27 21:56:59 2013 From: xrandomheartzx at aim.com (Katie) Date: Fri, 27 Sep 2013 15:56:59 -0400 (EDT) Subject: [Tutor] (no subject) Message-ID: <8D089D2DCB1B617-1BB4-1A086@webmail-vm004.sysops.aol.com> Hello, I am trying to write a program using Python v. 2.7.5 that will compute the area under the curve y=sin(x) between x = 0 and x = pi. Perform this calculation varying the n divisions of the range of x between 1 and 10 inclusive and print the approximate value, the true value, and the percent error (in other words, increase the accuracy by increasing the number of trapezoids). Print all the values to three decimal places. I am not sure what the code should look like. I was told that I should only have about 12 lines of code for these calculations to be done. I am using Wing IDE. I have very basic knowledge in Python. I would appreciate help. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sat Sep 28 01:29:03 2013 From: davea at davea.name (Dave Angel) Date: Fri, 27 Sep 2013 23:29:03 +0000 (UTC) Subject: [Tutor] List Python Question..Please help References: Message-ID: On 27/9/2013 13:04, Jacqueline Canales wrote: > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > x = 'Antheil' > s = 'Saint-Saens' > h = 'Beethoven' > y = 'Easdale' > k = 'Nielsen' > > if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': > if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': > if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': > print(s,k,y) > else: > print(" ") > > ####Answer i Got Below >>>> > Saint-Saens Nielsen Easdale >>>> > > Is this what i was going for in the direction i was a bit confused if we > were suppose create loops or if statements that are verified in the actual > composers list. I don't know i feel as if i know what i need to do i just > cant put it together. > At this stage of your experience, don't try to solve the whole thing in one monolithic piece of code. Those names shouldn't be in separate variables. For now, just write a function that takes a name as a parameter, and attempts to return either True or False, to indicate whether it matches. Then after you've debugged that, put those names back into a list, and write a loop which calls the function you just wrote. >
--
> Dharmit Shah
> www.about.me/dharmit
>
_______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

>
> Please post in text mode. html mail will mess you up, sooner or later. Besides, it adds unnecessary bulk to the message, which matters to those of us who pay by the byte. -- DaveA From davea at davea.name Sat Sep 28 01:39:33 2013 From: davea at davea.name (Dave Angel) Date: Fri, 27 Sep 2013 23:39:33 +0000 (UTC) Subject: [Tutor] Help on class References: <1380290859.63743.YahooMailNeo@web192501.mail.sg3.yahoo.com> Message-ID: On 27/9/2013 10:07, bharath ks wrote: > Hello, > > May i know why object 'c' does not prompt for employee name and employee id in the following code > i get out put as? > > Enter employee name:john > Enter employee id:56 > Employee name is: john > Employee id is: 56 > ---------------------------------------------------- > Employee name is: test > Employee id is: 1003 > ---------------------------------------------------- > Employee name is: john > Employee id is: 56 > > class employee: > > ? ? emp_name="" > ? ? emp_id=0 Those 2 class attributes are never used. Good thing, since you really want each employee to have his own name. > ? ? def collect_name(): > ? ? ? ? return(input("Enter employee name:")) > ? ? > ? ?? > ? ? def collect_id(): > ? ? ? ? return(input("Enter employee id:")) > ? ? ? ? ? ?? > ? ? def show(self): > ? ? ? ? print("Employee name is:",self.emp_name) > ? ? ? ? print("Employee id is:",self.emp_id) > ? ? ? ?? > ? ? def __init__(self,name=collect_name(),id=collect_id()): Those 2 function calls will happen only once, long before you instantiate any instance of employee. Put those inside the method, not as default values. > ? ? ? ? self.emp_name=name > ? ? ? ? self.emp_id=id > ? ? ? > ?? ?? > > a=employee() > a.show() > print("----------------------------------------------------") > b=employee("test",1003) > b.show() > print("----------------------------------------------------") > c=employee() > c.show() > The __init__() method should look something like this. That way, collect_name() and/or collect_id() will be called if the corresponding argument is not given. ? ? def __init__(self,name = None, id=None): if name: ? ? ? ? self.emp_name=name else: name=collect_name() if id: ? ? ? ? self.emp_id=id else: self.id=collect_id() > >
Hello,

May i know why object 'c' does not prompt for employee name and employee id in the following code
i get out put as 

Enter employee name:john
Enter employee id:56
Employee name is: john
Employee id is: 56
----------------------------------------------------
Employee name is: test
Employee id is: 1003
----------------------------------------------------
Employee name is: Please switch to text mail, as the html will mess things up, sooner or later. -- DaveA From breamoreboy at yahoo.co.uk Sat Sep 28 01:44:27 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 28 Sep 2013 00:44:27 +0100 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: On 27/09/2013 18:04, Jacqueline Canales wrote: > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > x = 'Antheil' > s = 'Saint-Saens' > h = 'Beethoven' > y = 'Easdale' > k = 'Nielsen' > > if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': > if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': > if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': > print(s,k,y) > else: > print(" ") > > ####Answer i Got Below > >>> > Saint-Saens Nielsen Easdale > >>> > > Is this what i was going for in the direction i was a bit confused if we > were suppose create loops or if statements that are verified in the > actual composers list. I don't know i feel as if i know what i need to > do i just cant put it together. > Yuck :( What happens if the list changes? I suggest that you reread the post from Steven D'Aprano but slightly restate your original post such that you are looking for names where the final letter is the lower case equivalent of the first letter. In that way your code should consist of four lines, the list of names, one for loop, one if statement and one print function, the latter assuming Python 3. Hope this helps. -- Cheers. Mark Lawrence From bgailer at gmail.com Sat Sep 28 01:46:03 2013 From: bgailer at gmail.com (bob gailer) Date: Fri, 27 Sep 2013 19:46:03 -0400 Subject: [Tutor] Help on class Message-ID: <524618BB.5000306@gmail.com> On 9/27/2013 10:07 AM, bharath ks wrote: > Hello, > Hi welcome to the tutor list. Please post in plain text rather than tiny hard-to-read formatted text. > May i know why object 'c' does not prompt for employee name and employee id in the following code You may - see comment below > i get out put as > > Enter employee name:john > Enter employee id:56 > Employee name is: john > Employee id is: 56 > ---------------------------------------------------- > Employee name is: test > Employee id is: 1003 > ---------------------------------------------------- > Employee name is: john > Employee id is: 56 > > class employee: > emp_name="" > emp_id=0 > def collect_name(): > return(input("Enter employee name:")) > > > def collect_id(): > return(input("Enter employee id:")) > > def show(self): > print("Employee name is:",self.emp_name) > print("Employee id is:",self.emp_id) > > def __init__(self,name=collect_name(),id=collect_id()): name=collect_name() and id=collect_id() are executed when the def is executed. The values are saved as the default values of name and id. That happens once, and the default values are used whenever __init__ is called without arguments. > self.emp_name=name > self.emp_id=id > > > > a=employee() > a.show() > print("----------------------------------------------------") > b=employee("test",1003) > b.show() > print("----------------------------------------------------") > c=employee() > c.show() -- Bob Gailer 919-636-4239 Chapel Hill NC From davea at davea.name Sat Sep 28 01:46:44 2013 From: davea at davea.name (Dave Angel) Date: Fri, 27 Sep 2013 23:46:44 +0000 (UTC) Subject: [Tutor] (no subject) References: <8D089D2DCB1B617-1BB4-1A086@webmail-vm004.sysops.aol.com> Message-ID: On 27/9/2013 15:56, Katie wrote: > > Hello, >

>
Please post your messages in text mode, not html. > >
I am trying to write a program using Python v. 2.7.5 that will compute the area under the curve y=sin(x) between x = 0 and x = pi. Perform this calculation varying the n divisions of the range of x between 1 and 10 inclusive and print the approximate value, the true value, and the percent error (in other words, increase the accuracy by increasing the number of trapezoids). Print all the values to three decimal places. 
> >

>
> >
I am not sure what the code should look like. I was told that I should only have about 12 lines of code for these calculations to be done. 
> >

>
> >
I am using Wing IDE. I have very basic knowledge in Python.
> >

>
> >
I would appreciate help. 
> >

>
> >
Thank you. 
>
> What part do you NOT understand? Don't worry yet about the line count. Just write one function that represents some aspect of the problem that you do understand. When that works, write a second function for some other aspect. -- DaveA From wescpy at gmail.com Sat Sep 28 01:59:43 2013 From: wescpy at gmail.com (wesley chun) Date: Fri, 27 Sep 2013 16:59:43 -0700 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: hello, well, i have to say that you've at least made a good start at a solution. right now you're thinking about it very much like a human. try to put yourself into the shoes of a computer: how can we solve this task for just ONE name? once you have that solution, then you can apply the same solution for all names by looping over or iterating through them. in your solution, you tried to do everything at once using brute force. i recommend you take the lessons learned you borrow some of that code and solve it for a single name. for example, take a look at this pseudocode: name = 'Guido' if name first letter == name last letter: # turn this into real Python using what you have print 'match' else: print 'not a match' then add the collection and a loop, and you'll be at your solution! best of luck! --wesley On Fri, Sep 27, 2013 at 10:04 AM, Jacqueline Canales wrote: > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > x = 'Antheil' > s = 'Saint-Saens' > h = 'Beethoven' > y = 'Easdale' > k = 'Nielsen' > > if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': > if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': > if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': > print(s,k,y) > else: > print(" ") > > ####Answer i Got Below > >>> > Saint-Saens Nielsen Easdale > >>> > > Is this what i was going for in the direction i was a bit confused if we > were suppose create loops or if statements that are verified in the actual > composers list. I don't know i feel as if i know what i need to do i just > cant put it together. > > > On Fri, Sep 27, 2013 at 3:14 AM, ?? wrote: > >> Maybe the length of each name matters, too. You should consider whether >> to skip null('') and single-character('a'). >> >> >> On Fri, Sep 27, 2013 at 3:57 PM, Dharmit Shah wrote: >> >>> Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the >>> same. >>> >>> Hope that helps. :) >>> >>> On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha >>> wrote: >>> > On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales >>> > wrote: >>> >> So I have been trying to do this program using ifs and or loops. >>> >> I am having a hard time solving this question, If you could please >>> assist me >>> >> in the right direction. >>> >> >>> >> Write a program that lists all the composers on the list ['Antheil', >>> >> 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts >>> and ends >>> >> with the same letter (so Nielsen gets lsited, but Antheil doesn't). >>> >> >>> >> I know below it prints the entire list of composers but i dont know >>> how to >>> >> do the program above. I think I am thinking to much into but ive >>> looked at >>> >> all my notes and online resources and having a hard time coming up >>> with >>> >> anything. >>> >> Please help! >>> >> >>> >> composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', >>> 'Nielsen'] >>> >> for person in composers: >>> >> print(person) >>> > >>> > So, here you are printing every compose as you rightly state above. >>> > What you now need to do is: >>> > >>> > For each of the composers (`person'), you need to check if the first >>> > letter and the last letter are the same. Here;s a hint: >>> > >>> >>>> s='abba' >>> > >>> > The first letter: >>> > >>> >>>> s[0] >>> > 'a' >>> > >>> > The last letter: >>> > >>> >>>> s[-1] >>> > 'a' >>> > >>> > >>> > If you now compare these, you will know if they are the same and hence >>> > you print him/her. >>> > >>> > Hope that helps. >>> > -Amit >>> >> -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Sep 28 02:06:08 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 28 Sep 2013 01:06:08 +0100 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: top posting fixed > > On Fri, Sep 27, 2013 at 10:04 AM, Jacqueline Canales > > wrote: > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', > 'Nielsen'] > x = 'Antheil' > s = 'Saint-Saens' > h = 'Beethoven' > y = 'Easdale' > k = 'Nielsen' > > if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': > if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': > if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': > print(s,k,y) > else: > print(" ") > > ####Answer i Got Below > >>> > Saint-Saens Nielsen Easdale > >>> > > Is this what i was going for in the direction i was a bit confused > if we were suppose create loops or if statements that are verified > in the actual composers list. I don't know i feel as if i know what > i need to do i just cant put it together. > On 28/09/2013 00:59, wesley chun wrote:> hello, > > well, i have to say that you've at least made a good start at a > solution. right now you're thinking about it very much like a human. try > to put yourself into the shoes of a computer: how can we solve this task > for just ONE name? > > once you have that solution, then you can apply the same solution for > all names by looping over or iterating through them. in your solution, > you tried to do everything at once using brute force. > > i recommend you take the lessons learned you borrow some of that code > and solve it for a single name. for example, take a look at this pseudocode: > > name = 'Guido' > if name first letter == name last letter: # turn this into real Python > using what you have > print 'match' > else: > print 'not a match' > > then add the collection and a loop, and you'll be at your solution! > > best of luck! > --wesley > I'd like to see the above work, e.g. how do you correctly compare the letters in 'Amanda'? -- Cheers. Mark Lawrence From amitsaha.in at gmail.com Sat Sep 28 04:11:06 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sat, 28 Sep 2013 12:11:06 +1000 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: Hi Jacqueline, On Sat, Sep 28, 2013 at 3:04 AM, Jacqueline Canales wrote: > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > x = 'Antheil' > s = 'Saint-Saens' > h = 'Beethoven' > y = 'Easdale' > k = 'Nielsen' > > if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': > if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': > if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': > print(s,k,y) > else: > print(" ") > > ####Answer i Got Below >>>> > Saint-Saens Nielsen Easdale >>>> > > Is this what i was going for in the direction i was a bit confused if we > were suppose create loops or if statements that are verified in the actual > composers list. I don't know i feel as if i know what i need to do i just > cant put it together. Nothing to worry. Let us break the problem down. In your first post, you mentioned this for loop: composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] for person in composers: print(person) What does this do? It prints all the composers' names. However, what you want is to print *only* the composer whose name starts and ends with the first letter. So, what can you do? I shall try to explain with an example from every day life. Let us say, the management in your local cinema theatre says that you can choose to see all of the films playing there. So, you can see all of: 'Turbo', 'Planes' and 'The Smurfs 2'. Now, let is say that your cinema management became a little shrewd and tells you that you can only watch the films starting with 'P'. So what do you do? In your mind, you think which of 'Turbo',' Planes' and 'The Smurfs 2' starts with 'P'. So, you first check, 'Turbo' and you see that it fails the condition, but 'Planes' agree with the condition and 'The Smurfs 2' also fails. Thus, you choose 'Planes'. So, your above program is in the right direction. What you have to now do is, before printing the 'person', you need to check if the person's name starts and ends with the same letter. I already showed you how you can do so. You may find the lower() method helpful here. It returns you a capital letter into a lower one: >>> 'A'.lower() 'a' Does that make it easier? Good luck. -Amit -- http://echorand.me From steve at pearwood.info Sat Sep 28 05:15:00 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 Sep 2013 13:15:00 +1000 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: <20130928031500.GR7989@ando> On Fri, Sep 27, 2013 at 12:04:38PM -0500, Jacqueline Canales wrote: > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > x = 'Antheil' > s = 'Saint-Saens' > h = 'Beethoven' > y = 'Easdale' > k = 'Nielsen' This is a step backwards from what you had in your first post. You had the right idea in the first case: for name in composers: ... Then you just write a bit of code that checks `name`, rather than a bit of code to check `x`, another bit of code to check `s`, a third bit of code to check `h`, a fourth to check `y`, ... What if you had ten thousand names to check? A for-loop doesn't care if there's one name or ten thousand names, computers are really good at that sort of tedius grunt-work. So, go back to where you started: for name in composers: # check whether name starts and ends with the same letter You want an "if" test. In English: if first letter of name equals last letter of name: print name How do you get the first letter of name? name[0] How do you get the last letter of name? name[-1] How do you test if two things are equal? # replace x and y with the first and last letter of name, as above x == y is *almost* right. It's not quite what you want, because it is case-sensitive. 'A' == 'a' will return False, since they are not precisely them same. You need to make them the same case: x.lower() == y.lower() # or upper() if you prefer Putting it all together: for name in composers: if **** == **** : print name where you have to replace the stars **** with: first letter of name, converted to lower/upper case last letter of name, converted to lower/upper case respectively. -- Steven From steve at pearwood.info Sat Sep 28 05:52:04 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 Sep 2013 13:52:04 +1000 Subject: [Tutor] (no subject) In-Reply-To: <8D089D2DCB1B617-1BB4-1A086@webmail-vm004.sysops.aol.com> References: <8D089D2DCB1B617-1BB4-1A086@webmail-vm004.sysops.aol.com> Message-ID: <20130928035203.GS7989@ando> On Fri, Sep 27, 2013 at 03:56:59PM -0400, Katie wrote: > I am trying to write a program using Python v. 2.7.5 that will compute > the area under the curve y=sin(x) between x = 0 and x = pi. Perform > this calculation varying the n divisions of the range of x between 1 > and 10 inclusive and print the approximate value, the true value, and > the percent error (in other words, increase the accuracy by increasing > the number of trapezoids). Print all the values to three decimal > places. There are four parts to this: 1) Determine the true value of the area. You'll need some calculus for that. Do you know how to work out the area under a graph? A = integral of sin(x) between 0 and pi 2) Write some code to use the trapezoid method to calculate the approximate area under the graph, using N steps. Do you know how the trapezoid method works? I really need to draw a picture here, which I can't do. Imagine if you sliced the graph up into N equal-width slices. Each slice will be pi/N in width, since the whole graph is pi units across. (Starting at 0, going to pi, so there are pi units in total; diving into N pieces means each one in pi/N across.) Each slice will look like a trapezoid, or specifically, a rectangle with a triangle at the top. I'm going to try "drawing" the trapezoid, but rotated side-on because it is easier: x1 +----------------------------- y1 . | \ . | \ x2 +------------------------------- y2 You should notes about the trapezoid method from class, or from your text book. If all else fails, you can google for it and find *dozens* of websites that talk about it: https://duckduckgo.com/html/?q=trapezoid+method 3) Then you need some code to calculate the total area from the area of all those slices. 4) And finally you need to calculate the difference between actual area and the calculated area, and print to three decimal places. Your over-all code will look something like this: from math import pi, sin actual_area = ***something goes here*** for N in range(1, 11): # calculate the approximate area total_area = 0 width = pi/N # width of each trapezoid x1 = 0 # start at zero each time x2 = x1+width while x2 <= pi: y1 = ***something goes here*** y2 = ***something goes here*** area_of_slice = ***something goes here*** total_area += area_of_slice x1, x2 = ***something goes here*** # now print the results error = ***something goes here*** print ("N = %d; Actual = %.3f; Calculated = %.3; Error = %.3f" % (N, actual_area, total_area, error)) Oh, there's an even better way to calculate the slices, instead of using a while-loop you can use a for-loop. But give it a go with the while-loop first, see if you can work out what needs to be done to change it to a for-loop. As usual, check your notes from class. > I am not sure what the code should look like. I was told that I should > only have about 12 lines of code for these calculations to be done. Well, I could probably squeeze everything into 12 lines if I really wanted to. But in my opinion, certainly 20 lines (not counting comments or blank lines) is plenty. -- Steven From steve at pearwood.info Sat Sep 28 06:44:25 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 Sep 2013 14:44:25 +1000 Subject: [Tutor] Help on class In-Reply-To: <1380290859.63743.YahooMailNeo@web192501.mail.sg3.yahoo.com> References: <1380290859.63743.YahooMailNeo@web192501.mail.sg3.yahoo.com> Message-ID: <20130928044425.GT7989@ando> On Fri, Sep 27, 2013 at 10:07:39PM +0800, bharath ks wrote: > Hello, > > May i know why object 'c' does not prompt for employee name and > employee id in the following code i get out put as? Default values in Python functions and methods are evaluated once only, when the function or method is defined ("compile time"), not each time it is run. You can test this yourself: import time def long_function(): # Simulate a long-running calculation print("Calculation started at %s" % time.ctime()) time.sleep(30) print("Calculation completed at %s" % time.ctime()) return 42 def test(value=long_function()): print(value) If you run this code, as I did, you will get something like: py> def test(value=long_function()): ... print(value) ... Calculation started at Sat Sep 28 14:37:38 2013 Calculation completed at Sat Sep 28 14:38:08 2013 only once, when the test function is created. Then, you can run that function as often as you like without the lengthy calculation being repeated: py> test() 42 py> test() 42 py> test(23) 23 py> test() 42 This is called "eager evaluation of default arguments", as opposed to "lazy evaluation of default arguments". To get lazy evaluation, stick the code inside the function, with a sentinel value: py> def test2(value=None): ... if value is None: ... value = long_function() ... print(value) ... py> test2() Calculation started at Sat Sep 28 14:41:08 2013 Calculation completed at Sat Sep 28 14:41:38 2013 42 py> test2(23) 23 py> test2() Calculation started at Sat Sep 28 14:42:13 2013 Calculation completed at Sat Sep 28 14:42:43 2013 42 -- Steven From amitsaha.in at gmail.com Sat Sep 28 07:39:51 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sat, 28 Sep 2013 15:39:51 +1000 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: On Sat, Sep 28, 2013 at 3:36 PM, Jacqueline Canales wrote: > Thank you guys so much i was able to figure it out. I definitely thought to > much into the the problem and made it harder on myself. Cant thank you > enough for assisting me. I have one more problem with the coding tho. > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > new_list = [] > person = new_list > for person in composers: > if person[0].lower() == person[-1].lower(): > print(person) > > Output: > Saint-Saens > Easdale > Nielsen Great work! > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > new_list = [] > person = new_list > for person in composers: > if person[0].lower() == person[-1].lower(): > new_list.append(person) > print(new_list) > > output: > ['Saint-Saens'] > ['Saint-Saens', 'Easdale'] > ['Saint-Saens', 'Easdale', 'Nielsen'] > > How can i make the output of the names into just one individual list. You mean, just print it once? The last line of your output? Just print after the loop is over. -- http://echorand.me From corsam28 at hotmail.com Sat Sep 28 17:19:57 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Sat, 28 Sep 2013 10:19:57 -0500 Subject: [Tutor] Function definition Message-ID: Hello! I'm using python v2.7.5 (IDLE). I'm trying to write a nine_line function that should use three_lines to print nine blanc lines. For some reason, I only print one line. Can you please provide me with some explanation? I would be very grateful! From fp2161 at gmail.com Sat Sep 28 13:48:00 2013 From: fp2161 at gmail.com (Fabrice POMBET) Date: Sat, 28 Sep 2013 13:48:00 +0200 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <0CAFAC40-FCEC-42BE-AE1E-BAFC2A552E8D@gmail.com> > To be a little more complete, (1)A=integral of f between a and b=F(b)-F(a) where F is the primitive of f (i.e f is the derivative function of F) in your little example, f=sin(x) <=> F=-cos(x), and therefore: A=-cos(pi)-(-cos(0))=-(-1)-(-(1))=2 (2) The trapezoid method is a way of approximating the area under the curve (you are missing the 'curved' area on top of the trapezoid, hence the approximation). The more there are trapezoids, the smaller the curvy bit gets, the more accurate it gets! > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 28 Sep 2013 13:52:04 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] (no subject) > Message-ID: <20130928035203.GS7989 at ando> > Content-Type: text/plain; charset=us-ascii > > On Fri, Sep 27, 2013 at 03:56:59PM -0400, Katie wrote: > >> I am trying to write a program using Python v. 2.7.5 that will compute >> the area under the curve y=sin(x) between x = 0 and x = pi. Perform >> this calculation varying the n divisions of the range of x between 1 >> and 10 inclusive and print the approximate value, the true value, and >> the percent error (in other words, increase the accuracy by increasing >> the number of trapezoids). Print all the values to three decimal >> places. > > > There are four parts to this: > > 1) Determine the true value of the area. You'll need some calculus > for that. Do you know how to work out the area under a graph? > > A = integral of sin(x) between 0 and pi > > 2) Write some code to use the trapezoid method to calculate the > approximate area under the graph, using N steps. > > Do you know how the trapezoid method works? I really need to > draw a picture here, which I can't do. Imagine if you sliced > the graph up into N equal-width slices. Each slice will be > pi/N in width, since the whole graph is pi units across. > (Starting at 0, going to pi, so there are pi units in total; > diving into N pieces means each one in pi/N across.) > > Each slice will look like a trapezoid, or specifically, a > rectangle with a triangle at the top. I'm going to try > "drawing" the trapezoid, but rotated side-on because it is > easier: > > > x1 +----------------------------- y1 > . | \ > . | \ > x2 +------------------------------- y2 > > > You should notes about the trapezoid method from class, or > from your text book. If all else fails, you can google for > it and find *dozens* of websites that talk about it: > > https://duckduckgo.com/html/?q=trapezoid+method > > > 3) Then you need some code to calculate the total area from the > area of all those slices. > > 4) And finally you need to calculate the difference between actual > area and the calculated area, and print to three decimal places. > > > Your over-all code will look something like this: > > > from math import pi, sin > actual_area = ***something goes here*** > for N in range(1, 11): > # calculate the approximate area > total_area = 0 > width = pi/N # width of each trapezoid > x1 = 0 # start at zero each time > x2 = x1+width > while x2 <= pi: > y1 = ***something goes here*** > y2 = ***something goes here*** > area_of_slice = ***something goes here*** > total_area += area_of_slice > x1, x2 = ***something goes here*** > # now print the results > error = ***something goes here*** > print ("N = %d; Actual = %.3f; Calculated = %.3; Error = %.3f" > % (N, actual_area, total_area, error)) > > > Oh, there's an even better way to calculate the slices, instead of using > a while-loop you can use a for-loop. But give it a go with the > while-loop first, see if you can work out what needs to be done to > change it to a for-loop. As usual, check your notes from class. > >> I am not sure what the code should look like. I was told that I should >> only have about 12 lines of code for these calculations to be done. > > Well, I could probably squeeze everything into 12 lines if I really > wanted to. But in my opinion, certainly 20 lines (not counting comments > or blank lines) is plenty. > > > > -- > Steven > > > ------------------------------ > > Message: 2 > Date: Sat, 28 Sep 2013 14:44:25 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Help on class > Message-ID: <20130928044425.GT7989 at ando> > Content-Type: text/plain; charset=iso-8859-1 > > On Fri, Sep 27, 2013 at 10:07:39PM +0800, bharath ks wrote: >> Hello, >> >> May i know why object 'c' does not prompt for employee name and >> employee id in the following code i get out put as? > > Default values in Python functions and methods are evaluated once only, > when the function or method is defined ("compile time"), not each time > it is run. > > You can test this yourself: > > import time > def long_function(): > # Simulate a long-running calculation > print("Calculation started at %s" % time.ctime()) > time.sleep(30) > print("Calculation completed at %s" % time.ctime()) > return 42 > > > def test(value=long_function()): > print(value) > > > If you run this code, as I did, you will get something like: > > py> def test(value=long_function()): > ... print(value) > ... > Calculation started at Sat Sep 28 14:37:38 2013 > Calculation completed at Sat Sep 28 14:38:08 2013 > > only once, when the test function is created. Then, you can run that > function as often as you like without the lengthy calculation being > repeated: > > > py> test() > 42 > py> test() > 42 > py> test(23) > 23 > py> test() > 42 > > > This is called "eager evaluation of default arguments", as opposed to > "lazy evaluation of default arguments". To get lazy evaluation, stick > the code inside the function, with a sentinel value: > > py> def test2(value=None): > ... if value is None: > ... value = long_function() > ... print(value) > ... > py> test2() > Calculation started at Sat Sep 28 14:41:08 2013 > Calculation completed at Sat Sep 28 14:41:38 2013 > 42 > py> test2(23) > 23 > py> test2() > Calculation started at Sat Sep 28 14:42:13 2013 > Calculation completed at Sat Sep 28 14:42:43 2013 > 42 > > > -- > Steven > > > ------------------------------ > > Message: 3 > Date: Sat, 28 Sep 2013 15:39:51 +1000 > From: Amit Saha > To: Jacqueline Canales > Cc: "tutor at python.org" > Subject: Re: [Tutor] List Python Question..Please help > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > On Sat, Sep 28, 2013 at 3:36 PM, Jacqueline Canales > wrote: >> Thank you guys so much i was able to figure it out. I definitely thought to >> much into the the problem and made it harder on myself. Cant thank you >> enough for assisting me. I have one more problem with the coding tho. >> >> composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] >> new_list = [] >> person = new_list >> for person in composers: >> if person[0].lower() == person[-1].lower(): >> print(person) >> >> Output: >> Saint-Saens >> Easdale >> Nielsen > > Great work! > >> >> composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] >> new_list = [] >> person = new_list >> for person in composers: >> if person[0].lower() == person[-1].lower(): >> new_list.append(person) >> print(new_list) >> >> output: >> ['Saint-Saens'] >> ['Saint-Saens', 'Easdale'] >> ['Saint-Saens', 'Easdale', 'Nielsen'] > > > >> >> How can i make the output of the names into just one individual list. > > You mean, just print it once? The last line of your output? > > Just print after the loop is over. > > > > > > -- > http://echorand.me > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 115, Issue 60 > ************************************** From jackiexxduh3 at gmail.com Sat Sep 28 07:36:13 2013 From: jackiexxduh3 at gmail.com (Jacqueline Canales) Date: Sat, 28 Sep 2013 00:36:13 -0500 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: Thank you guys so much i was able to figure it out. I definitely thought to much into the the problem and made it harder on myself. Cant thank you enough for assisting me. I have one more problem with the coding tho. composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] new_list = [] person = new_list for person in composers: if person[0].lower() == person[-1].lower(): print(person) Output: Saint-Saens Easdale Nielsen composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] new_list = [] person = new_list for person in composers: if person[0].lower() == person[-1].lower(): new_list.append(person) print(new_list) output: ['Saint-Saens'] ['Saint-Saens', 'Easdale'] ['Saint-Saens', 'Easdale', 'Nielsen'] How can i make the output of the names into just one individual list. On Fri, Sep 27, 2013 at 9:11 PM, Amit Saha wrote: > Hi Jacqueline, > > On Sat, Sep 28, 2013 at 3:04 AM, Jacqueline Canales > wrote: > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > > x = 'Antheil' > > s = 'Saint-Saens' > > h = 'Beethoven' > > y = 'Easdale' > > k = 'Nielsen' > > > > if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': > > if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': > > if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': > > print(s,k,y) > > else: > > print(" ") > > > > ####Answer i Got Below > >>>> > > Saint-Saens Nielsen Easdale > >>>> > > > > Is this what i was going for in the direction i was a bit confused if we > > were suppose create loops or if statements that are verified in the > actual > > composers list. I don't know i feel as if i know what i need to do i just > > cant put it together. > > Nothing to worry. Let us break the problem down. > > In your first post, you mentioned this for loop: > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > for person in composers: > print(person) > > What does this do? It prints all the composers' names. However, what > you want is to print *only* the composer whose name starts and ends > with the first letter. So, what can you do? > > I shall try to explain with an example from every day life. Let us > say, the management in your local cinema theatre says that you can > choose to see all of the films playing there. So, you can see all of: > 'Turbo', 'Planes' and 'The Smurfs 2'. Now, let is say that your cinema > management became a little shrewd and tells you that you can only > watch the films starting with 'P'. So what do you do? In your mind, > you think which of 'Turbo',' Planes' and 'The Smurfs 2' starts with > 'P'. So, you first check, 'Turbo' and you see that it fails the > condition, but 'Planes' agree with the condition and 'The Smurfs 2' > also fails. Thus, you choose 'Planes'. > > So, your above program is in the right direction. What you have to now > do is, before printing the 'person', you need to check if the person's > name starts and ends with the same letter. I already showed you how > you can do so. > > You may find the lower() method helpful here. It returns you a capital > letter into a lower one: > > >>> 'A'.lower() > 'a' > > Does that make it easier? > > Good luck. > -Amit > > > -- > http://echorand.me > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jackiexxduh3 at gmail.com Sat Sep 28 07:55:41 2013 From: jackiexxduh3 at gmail.com (Jacqueline Canales) Date: Sat, 28 Sep 2013 00:55:41 -0500 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: THANK YOU!!!!!!! All of you were very helpful!! Will definitely use you guys again for any other issues, glad you challenged me to think rather than giving me the answer!!! On Sat, Sep 28, 2013 at 12:39 AM, Amit Saha wrote: > On Sat, Sep 28, 2013 at 3:36 PM, Jacqueline Canales > wrote: > > Thank you guys so much i was able to figure it out. I definitely thought > to > > much into the the problem and made it harder on myself. Cant thank you > > enough for assisting me. I have one more problem with the coding tho. > > > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > > new_list = [] > > person = new_list > > for person in composers: > > if person[0].lower() == person[-1].lower(): > > print(person) > > > > Output: > > Saint-Saens > > Easdale > > Nielsen > > Great work! > > > > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > > new_list = [] > > person = new_list > > for person in composers: > > if person[0].lower() == person[-1].lower(): > > new_list.append(person) > > print(new_list) > > > > output: > > ['Saint-Saens'] > > ['Saint-Saens', 'Easdale'] > > ['Saint-Saens', 'Easdale', 'Nielsen'] > > > > > > > How can i make the output of the names into just one individual list. > > You mean, just print it once? The last line of your output? > > Just print after the loop is over. > > > > > > -- > http://echorand.me > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Sep 28 16:54:48 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 29 Sep 2013 00:54:48 +1000 Subject: [Tutor] Function definition In-Reply-To: References: Message-ID: <20130928145448.GY7989@ando> On Sat, Sep 28, 2013 at 10:19:57AM -0500, Sammy Cornet wrote: > Hello! > I'm using python v2.7.5 (IDLE). I'm trying to write a nine_line > function that should use three_lines to print nine blanc lines. For > some reason, I only print one line. Can you please provide me with > some explanation? I would be very grateful! Yay, a guessing game! I love guessing games! Let me see... my guess is that instead of writing: sys.stdout.write("\n"*9) you have written sys.stdout.write("\n") Am I close? If by some chance I have guessed wrong, perhaps you would like to show us what code you have. It's not as much fun as playing "Guess Where The Bug Is", but it's usually much faster and more accurate. -- Steven From steve at pearwood.info Sat Sep 28 17:00:54 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 29 Sep 2013 01:00:54 +1000 Subject: [Tutor] List Python Question..Please help In-Reply-To: References: Message-ID: <20130928150054.GZ7989@ando> On Sat, Sep 28, 2013 at 12:36:13AM -0500, Jacqueline Canales wrote: > Thank you guys so much i was able to figure it out. I definitely thought to > much into the the problem and made it harder on myself. Cant thank you > enough for assisting me. I have one more problem with the coding tho. > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > new_list = [] > person = new_list This line above (person = new_list) is unnecessary, since it never gets used before the next line sets it to something else. > for person in composers: > if person[0].lower() == person[-1].lower(): > print(person) > > Output: > Saint-Saens > Easdale > Nielsen > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > new_list = [] > person = new_list > for person in composers: > if person[0].lower() == person[-1].lower(): > new_list.append(person) > print(new_list) Here you print the content of new_list each time through the loop, so you see it growing. Instead, get rid of the indentation so that it runs when the loop is finished: for person in composers: if person[0].lower() == person[-1].lower(): new_list.append(person) print(new_list) -- Steven From davea at davea.name Sat Sep 28 17:11:25 2013 From: davea at davea.name (Dave Angel) Date: Sat, 28 Sep 2013 15:11:25 +0000 (UTC) Subject: [Tutor] Function definition References: Message-ID: On 28/9/2013 11:19, Sammy Cornet wrote: > Hello! > I'm using python v2.7.5 (IDLE). I'm trying to write a nine_line function that should use three_lines to print nine blanc lines. For some reason, I only print one line. Can you please provide me with some explanation? I would be very grateful! Judging from the code sample you showed us, your problem is too much white space. ;-> If you show us the code, we might show you where you go wrong. Or are you just waiting for somebody to do your homework and steal your learning experience? -- DaveA From rafael.knuth at gmail.com Sun Sep 29 22:42:58 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sun, 29 Sep 2013 22:42:58 +0200 Subject: [Tutor] Creating To Do List Program - Question Message-ID: Hej there, I am writing a to do list program in Python 3.0. Earlier this week, I shared my first iteration on the mailing list, and the feedback was that I should learn how to create, write to and read from a text file ? which I did. Below please find my second iteration. I know my program is super cheesy & primitive, but I don?t care, it does what I expect it to do, and I will improve it in further iteration cycles. As of now, I want to understand how I can add further functionalities to my program such as: appending items to the list, removing and replacing items. Can anyone help? Thank you very much in advance! print(""" Welcome World's Most Geeky To Do List Program G E E K L I S T 1 . 0 If you want to add items to the list, enter: text_file = open("ToDoList.txt", "w") text_file.write("add your item here ") text_file.write("add action item here ") text_file.write("you get the point, right?") text_file.close() If you want to print your to do list, enter: text_file = open("ToDoList.txt", "r") print(text_file.read()) text_file.close() We are constantly improving our program, watch out for version 2.0! """) From nik at naturalnet.de Sun Sep 29 23:01:51 2013 From: nik at naturalnet.de (Dominik George) Date: Sun, 29 Sep 2013 23:01:51 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: <43f49246-88cd-455e-bfb0-ef8ba2b8d9f7@email.android.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Rafael Knuth schrieb: >Hej there, > >I am writing a to do list program in Python 3.0. > >Earlier this week, I shared my first iteration on the mailing list, >and the feedback was that I should learn how to create, write to and >read from a text file ? which I did. Below please find my second >iteration. I know my program is super cheesy & primitive, but I don?t >care, it does what I expect it to do, and I will improve it in further >iteration cycles. As of now, I want to understand how I can add >further functionalities to my program such as: appending items to the >list, removing and replacing items. Can anyone help? Thank you very >much in advance! > >print(""" > >Welcome World's Most Geeky To Do List Program > >G E E K L I S T 1 . 0 > >If you want to add items to the list, enter: > >text_file = open("ToDoList.txt", "w") >text_file.write("add your item here ") >text_file.write("add action item here ") >text_file.write("you get the point, right?") >text_file.close() > >If you want to print your to do list, enter: > >text_file = open("ToDoList.txt", "r") >print(text_file.read()) >text_file.close() > >We are constantly improving our program, watch out for version 2.0! > >""") >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor Hi, why don't you remove the first and last line and then use the "cat" interpreter instead? Seriously, you should try to write a program first, then ask for help. Just follow the instructions from your output below! - -nik - -- Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail gesendet. -----BEGIN PGP SIGNATURE----- Version: APG v1.0.8-fdroid iQFNBAEBCgA3BQJSSJU/MBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJT1IB/9l3mmERfFT7zzQo1HLharf j/bNkwpouG4rJ6dB+/4RIu9EBvUl0i3uvA9O0Lwo4B6cU4ulHLyZd/dj1vdYs4a/ 7XfUIlb78fIhHWgpgfjglXheQeUaruspfc/XfYZ0MJSwWVoAyC9C/dtOGGq3nlfM K6eE0ScoteVRsW5UsqIv5qzbEqjWGW/j8frySj7uYEr24VP/SVKT2MwAZy1zv7uy 8FwrmvGjyx8lXa/sEVfZzpNXgikENQumt6ZCUMcNf2FM/0kxzie3e8Z7V/Ofkygt ccWMoMRlmcF/l1m45bPbQ6RFw4frTOekCujNHNa5RR+OEi3HcugKMzMKDGqBn5M8 =/cCh -----END PGP SIGNATURE----- From joel.goldstick at gmail.com Sun Sep 29 23:09:34 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 29 Sep 2013 17:09:34 -0400 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: On Sun, Sep 29, 2013 at 4:42 PM, Rafael Knuth wrote: > Hej there, > > I am writing a to do list program in Python 3.0. > > Earlier this week, I shared my first iteration on the mailing list, > and the feedback was that I should learn how to create, write to and > read from a text file ? which I did. Below please find my second > iteration. I know my program is super cheesy & primitive, but I don?t > care, it does what I expect it to do, and I will improve it in further > iteration cycles. As of now, I want to understand how I can add > further functionalities to my program such as: appending items to the > list, removing and replacing items. Can anyone help? Thank you very > much in advance! > > print(""" > > Welcome World's Most Geeky To Do List Program > > G E E K L I S T 1 . 0 > > If you want to add items to the list, enter: > > text_file = open("ToDoList.txt", "w") > text_file.write("add your item here ") > text_file.write("add action item here ") > text_file.write("you get the point, right?") > text_file.close() > > If you want to print your to do list, enter: > > text_file = open("ToDoList.txt", "r") > print(text_file.read()) > text_file.close() > > We are constantly improving our program, watch out for version 2.0! > > """) > I applaud your efforts, but I don't think that code does what you think it does. First, the whole code block is triple quoted so it will print out as is. None of the statements in it will run at all. I'm guessing you want to print instructions asking the user to type something to indicate what they want to do. So, I suggest you write some code to open a file, write some stuff to it. Close it, then open it to read and print the results. That will get you going on basic file stuff. It looks like what you want to do might actually be easier to do with a database. That adds to your list of things to learn, but in the end you will have a useful companion skill and much simpler code than what you need if you stick with a text file. mysql comes with python, and you can learn the basics over a weekend using the interactive tool that comes with it. _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Sep 30 00:42:23 2013 From: wprins at gmail.com (Walter Prins) Date: Sun, 29 Sep 2013 23:42:23 +0100 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: On 29 September 2013 22:09, Joel Goldstick wrote: > mysql comes with python, and you can learn the basics over a weekend using > the interactive tool that comes with it. > Just a minor errata: I'm sure Joel meant to write "sqlite", not "mysql". (SQLite is indeed included with Python, the latter is not, though perhaps the DB module to interface to mysql might be.) Rafael, the idea would be to write your program so that the user doesn't have to enter program code to update their todo list. So, you might want to offer the user a main menu, maybe with options to, say: 1) View the outstanding todo items; 2) Edit an existing item; 3) Add a new item; 4) Complete/Delete an existing item; 5) Quit. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Sep 30 00:56:29 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 29 Sep 2013 18:56:29 -0400 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: On Sun, Sep 29, 2013 at 6:42 PM, Walter Prins wrote: > On 29 September 2013 22:09, Joel Goldstick wrote: > >> mysql comes with python, and you can learn the basics over a weekend >> using the interactive tool that comes with it. >> > > Just a minor errata: I'm sure Joel meant to write "sqlite", not "mysql". > (SQLite is indeed included with Python, the latter is not, though perhaps > the DB module to interface to mysql might be.) > Thanks Walter, yes I did mean sqlite > > Rafael, the idea would be to write your program so that the user doesn't > have to enter program code to update their todo list. So, you might want > to offer the user a main menu, maybe with options to, say: 1) View the > outstanding todo items; 2) Edit an existing item; 3) Add a new item; 4) > Complete/Delete an existing item; 5) Quit. > > Walter > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From corsam28 at hotmail.com Mon Sep 30 02:13:57 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Sun, 29 Sep 2013 19:13:57 -0500 Subject: [Tutor] Function definition In-Reply-To: <20130928145448.GY7989@ando> References: <20130928145448.GY7989@ando> Message-ID: Greets!! Your help provided to me concerning function definition was awesome Steven. Gratitude...!!! Sent from my iPhone On Sep 28, 2013, at 9:56, "Steven D'Aprano" wrote: > On Sat, Sep 28, 2013 at 10:19:57AM -0500, Sammy Cornet wrote: >> Hello! >> I'm using python v2.7.5 (IDLE). I'm trying to write a nine_line >> function that should use three_lines to print nine blanc lines. For >> some reason, I only print one line. Can you please provide me with >> some explanation? I would be very grateful! > > Yay, a guessing game! I love guessing games! > > Let me see... my guess is that instead of writing: > > sys.stdout.write("\n"*9) > > you have written > > sys.stdout.write("\n") > > Am I close? > > If by some chance I have guessed wrong, perhaps you would like to show > us what code you have. It's not as much fun as playing "Guess Where The > Bug Is", but it's usually much faster and more accurate. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Mon Sep 30 01:36:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Sep 2013 00:36:15 +0100 Subject: [Tutor] Function definition In-Reply-To: References: <20130928145448.GY7989@ando> Message-ID: On 30/09/13 01:13, Sammy Cornet wrote: > Greets!! > Your help provided to me concerning function definition > was awesome Steven. Gratitude...!!! I'm not sure who's tongue is furthest into their cheek here. But please, in future show us some code and any error messages, it does make it easier to answer your question. But if Steven's inspired guess helped then good for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 30 01:39:42 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Sep 2013 00:39:42 +0100 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: On 29/09/13 22:09, Joel Goldstick wrote: > mysql comes with python, and you can learn the basics over a weekend > using the interactive tool that comes with it. I assume you meant SQLite comes with python? MySql is a download... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 30 01:43:57 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Sep 2013 00:43:57 +0100 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: On 29/09/13 21:42, Rafael Knuth wrote: > iteration. I know my program is super cheesy & primitive, but I don?t > care, it does what I expect it to do, Really? You wrote a program that printed out a different program to the one you ran and that's what you wanted? It doesn't do anything about creating a ToDo list. It doesn't even bring you any closer to creating a ToDo list. Now, if instead of just printing it you actually ran the code you print it might actually get you somewhere closer. But at the moment your program is exactly equivalent to print('Hello world') except more verbose in its message. > print(""" > > Welcome World's Most Geeky To Do List Program > > G E E K L I S T 1 . 0 > > If you want to add items to the list, enter: > > text_file = open("ToDoList.txt", "w") > text_file.write("add your item here ") > text_file.write("add action item here ") > text_file.write("you get the point, right?") > text_file.close() > > If you want to print your to do list, enter: > > text_file = open("ToDoList.txt", "r") > print(text_file.read()) > text_file.close() > > We are constantly improving our program, watch out for version 2.0! > > """) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From rafael.knuth at gmail.com Mon Sep 30 12:17:28 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 30 Sep 2013 12:17:28 +0200 Subject: [Tutor] Creating To Do List Program - Questions Message-ID: Hej there, apologies if you're receiving my mail for a second time, I had some issues with Google and I just want to make sure you will receive my email. I am writing a to do list program in Python 3.0. Last week, I shared my first iteration on the mailing list, and the feedback was that I should learn how to create, write to and read from a text file ? which I did. Below please find my second iteration. I know my program is super cheesy & primitive, but I don?t care, it does what I expect it to do, and I will improve it in further iteration cycles. As of now, I want to understand how I can add further functionalities to my program such as: appending items to the list, removing and replacing items. Can anyone help? Thank you very much in advance! print(""" Welcome World's Most Geeky To Do List Program G E E K L I S T 1 . 0 If you want to add items to the list, enter: text_file = open("ToDoList.txt", "w") text_file.write("add your item here ") text_file.write("add action item here ") text_file.write("you get the point, right?") text_file.close() If you want to print your to do list, enter: text_file = open("ToDoList.txt", "r") print(text_file.read()) text_file.close() We are constantly improving our program, watch out for version 2.0! """) From nik at naturalnet.de Mon Sep 30 12:19:15 2013 From: nik at naturalnet.de (Dominik George) Date: Mon, 30 Sep 2013 12:19:15 +0200 Subject: [Tutor] Creating To Do List Program - Questions In-Reply-To: References: Message-ID: <15c830b9-ae9a-4b75-9d87-85ab8dc9a422@email.android.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Rafael Knuth schrieb: >Hej there, > >apologies if you're receiving my mail for a second time, I had some >issues with Google and I just want to make sure you will receive my >email. > >I am writing a to do list program in Python 3.0. > >Last week, I shared my first iteration on the mailing list, and the >feedback was that I should learn how to create, write to and read from >a text file ? which I did. Below please find my second iteration. I >know my program is super cheesy & primitive, but I don?t care, it does >what I expect it to do, and I will improve it in further iteration >cycles. As of now, I want to understand how I can add further >functionalities to my program such as: appending items to the list, >removing and replacing items. Can anyone help? Thank you very much in >advance! > >print(""" > >Welcome World's Most Geeky To Do List Program > >G E E K L I S T 1 . 0 > >If you want to add items to the list, enter: > >text_file = open("ToDoList.txt", "w") >text_file.write("add your item here ") >text_file.write("add action item here ") >text_file.write("you get the point, right?") >text_file.close() > >If you want to print your to do list, enter: > >text_file = open("ToDoList.txt", "r") >print(text_file.read()) >text_file.close() > >We are constantly improving our program, watch out for version 2.0! > >""") >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor Plonk! - -- Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail gesendet. -----BEGIN PGP SIGNATURE----- Version: APG v1.0.8-fdroid iQFNBAEBCgA3BQJSSVAiMBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJRHPCACXtUPhURIgmZJYJ9dN/3aO NsLmHWS3aQK3DBHI9Yjle8VFDjjPEE4mVEB/qsEJRddu4SbmiwPzy7P961X13aOg SSX/jvTj+CfrapxgslCgtTF3K3i65XHJ5CL8CE2TWBhaxM2ZET+q66owAYKfQBGH CoAVX4SwKHKCeFU5I40ft09kPh6LAwxogF3whVi6eYwdlDSGxsYABdqhegnR6JL+ tW6vNZiTkDa4vihmsQ5md/2Lw0c5fG+3wEXFAcwl9+Cu39cHD2btQDmSPuPo730h z4b1fa7noaNbOnuhapwEQt81kSEayzbfugy5rL3deBmQUSmrFNQc0/NxdD2+k9Ea =AYpY -----END PGP SIGNATURE----- From joel.goldstick at gmail.com Mon Sep 30 12:35:16 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 30 Sep 2013 06:35:16 -0400 Subject: [Tutor] Creating To Do List Program - Questions In-Reply-To: <15c830b9-ae9a-4b75-9d87-85ab8dc9a422@email.android.com> References: <15c830b9-ae9a-4b75-9d87-85ab8dc9a422@email.android.com> Message-ID: You restarted the same thread from yesterday where you got several replies. Go and find that thread. On Mon, Sep 30, 2013 at 6:19 AM, Dominik George wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > > > Rafael Knuth schrieb: > >Hej there, > > > >apologies if you're receiving my mail for a second time, I had some > >issues with Google and I just want to make sure you will receive my > >email. > > > >I am writing a to do list program in Python 3.0. > > > >Last week, I shared my first iteration on the mailing list, and the > >feedback was that I should learn how to create, write to and read from > >a text file ? which I did. Below please find my second iteration. I > >know my program is super cheesy & primitive, but I don?t care, it does > >what I expect it to do, and I will improve it in further iteration > >cycles. As of now, I want to understand how I can add further > >functionalities to my program such as: appending items to the list, > >removing and replacing items. Can anyone help? Thank you very much in > >advance! > > > >print(""" > > > >Welcome World's Most Geeky To Do List Program > > > >G E E K L I S T 1 . 0 > > > >If you want to add items to the list, enter: > > > >text_file = open("ToDoList.txt", "w") > >text_file.write("add your item here ") > >text_file.write("add action item here ") > >text_file.write("you get the point, right?") > >text_file.close() > > > >If you want to print your to do list, enter: > > > >text_file = open("ToDoList.txt", "r") > >print(text_file.read()) > >text_file.close() > > > >We are constantly improving our program, watch out for version 2.0! > > > >""") > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >To unsubscribe or change subscription options: > >https://mail.python.org/mailman/listinfo/tutor > > Plonk! > - -- > Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail > gesendet. > -----BEGIN PGP SIGNATURE----- > Version: APG v1.0.8-fdroid > > iQFNBAEBCgA3BQJSSVAiMBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p > a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJRHPCACXtUPhURIgmZJYJ9dN/3aO > NsLmHWS3aQK3DBHI9Yjle8VFDjjPEE4mVEB/qsEJRddu4SbmiwPzy7P961X13aOg > SSX/jvTj+CfrapxgslCgtTF3K3i65XHJ5CL8CE2TWBhaxM2ZET+q66owAYKfQBGH > CoAVX4SwKHKCeFU5I40ft09kPh6LAwxogF3whVi6eYwdlDSGxsYABdqhegnR6JL+ > tW6vNZiTkDa4vihmsQ5md/2Lw0c5fG+3wEXFAcwl9+Cu39cHD2btQDmSPuPo730h > z4b1fa7noaNbOnuhapwEQt81kSEayzbfugy5rL3deBmQUSmrFNQc0/NxdD2+k9Ea > =AYpY > -----END PGP SIGNATURE----- > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafael.knuth at gmail.com Mon Sep 30 12:42:42 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 30 Sep 2013 12:42:42 +0200 Subject: [Tutor] Creating To Do List Program - Questions In-Reply-To: References: <15c830b9-ae9a-4b75-9d87-85ab8dc9a422@email.android.com> Message-ID: Joel, I am terribly sorry, I erased that thread accidentally without having read it, and I now found it. Thank you and again - and apologies! Rafael On Mon, Sep 30, 2013 at 12:35 PM, Joel Goldstick wrote: > You restarted the same thread from yesterday where you got several replies. > Go and find that thread. From rafael.knuth at gmail.com Mon Sep 30 13:12:49 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 30 Sep 2013 13:12:49 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: Hej there, @Alan @Joel: I didn't know that pouring corn on newbies is the purpose of a tutor mailing list. Why don't you try writing a program instead? Why don't you use the cat interpreter instead? I tried my best and that's what I came up with, and I am eager to learn form experienced programmers - step by step at my own pace and in my own manner. Hence, I find your responses arrogant, self-righteous and discouraging. I do not understand why you don't consider what I wrote not a program ("Hello World!" in a more elaborate form), as the user is actually able to a list, to write to and reads from it (in a very primitive manner though). Can anyone explain? However, I find that hint to learn to use SQLite - thank you for that. All the best, Rafael Rafael On Mon, Sep 30, 2013 at 1:43 AM, Alan Gauld wrote: > On 29/09/13 21:42, Rafael Knuth wrote: > >> iteration. I know my program is super cheesy & primitive, but I don?t >> care, it does what I expect it to do, > > > Really? You wrote a program that printed out a different > program to the one you ran and that's what you wanted? > It doesn't do anything about creating a ToDo list. > It doesn't even bring you any closer to creating a ToDo list. > > Now, if instead of just printing it you actually ran > the code you print it might actually get you somewhere > closer. > > But at the moment your program is exactly equivalent to > > print('Hello world') > > except more verbose in its message. > > >> print(""" >> >> Welcome World's Most Geeky To Do List Program >> >> G E E K L I S T 1 . 0 >> >> If you want to add items to the list, enter: >> >> text_file = open("ToDoList.txt", "w") >> text_file.write("add your item here ") >> text_file.write("add action item here ") >> text_file.write("you get the point, right?") >> text_file.close() >> >> If you want to print your to do list, enter: >> >> text_file = open("ToDoList.txt", "r") >> print(text_file.read()) >> text_file.close() >> >> We are constantly improving our program, watch out for version 2.0! >> >> """) > > > -- > 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From nik at naturalnet.de Mon Sep 30 13:18:03 2013 From: nik at naturalnet.de (Dominik George) Date: Mon, 30 Sep 2013 13:18:03 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Rafael Knuth schrieb: >Hej there, > >@Alan @Joel: >I didn't know that pouring corn on newbies is the purpose of a tutor >mailing list. >Why don't you try writing a program instead? Why don't you use the cat >interpreter instead? >I tried my best and that's what I came up with, and I am eager to >learn form experienced programmers - step by step at my own pace and >in my own manner. Hence, I find your responses arrogant, >self-righteous and discouraging. > >I do not understand why you don't consider what I wrote not a program >("Hello World!" in a more elaborate form), as the user is actually >able to a list, to write to and reads from it (in a very primitive >manner though). Can anyone explain? However, I find that hint to >learn to use SQLite - thank you for that. > >All the best, > >Rafael > >Rafael > > > > >On Mon, Sep 30, 2013 at 1:43 AM, Alan Gauld >wrote: >> On 29/09/13 21:42, Rafael Knuth wrote: >> >>> iteration. I know my program is super cheesy & primitive, but I >don?t >>> care, it does what I expect it to do, >> >> >> Really? You wrote a program that printed out a different >> program to the one you ran and that's what you wanted? >> It doesn't do anything about creating a ToDo list. >> It doesn't even bring you any closer to creating a ToDo list. >> >> Now, if instead of just printing it you actually ran >> the code you print it might actually get you somewhere >> closer. >> >> But at the moment your program is exactly equivalent to >> >> print('Hello world') >> >> except more verbose in its message. >> >> >>> print(""" >>> >>> Welcome World's Most Geeky To Do List Program >>> >>> G E E K L I S T 1 . 0 >>> >>> If you want to add items to the list, enter: >>> >>> text_file = open("ToDoList.txt", "w") >>> text_file.write("add your item here ") >>> text_file.write("add action item here ") >>> text_file.write("you get the point, right?") >>> text_file.close() >>> >>> If you want to print your to do list, enter: >>> >>> text_file = open("ToDoList.txt", "r") >>> print(text_file.read()) >>> text_file.close() >>> >>> We are constantly improving our program, watch out for version 2.0! >>> >>> """) >> >> >> -- >> 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 at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor Hi Rafael, it's not your program - it's your attitude. We expect you to learn for yourself as well, and putting the commands you output into a script and execute it clearly isn't beyond what we can expect from someone who can use a mail program. This attitude even shows in your last mail - you accuse Alan and Joel, then quote *my* bad behaviour, blaming them for it. You are welcome here, but please always make at least an educated guess about your problem. - -nik - -- Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail gesendet. -----BEGIN PGP SIGNATURE----- Version: APG v1.0.8-fdroid iQFNBAEBCgA3BQJSSV3rMBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJe3UB/0UDtC1HbqL8XCTAfkuXb00 07BL9H7W/lkk8wPR8Wiq4TLjnW9lVoFn3Y68Pebity/J/MDLj10u2MgV11HV5it8 Sb/XLDSAs4fKnJaHbDUsyaAJ2aBbygUT2T4OI8sFKURikPBmgItX36H68dGF8V97 BkeFrMDzqbuzubClhfNjh9jeqsvf3Lfzy4hx6M1SXoKAHg6uv3nu+pPme0n5Phzt iUjkQR8mD86KPE4kcN0qCCpAfxJVuqHWq9ZCtxpEVYwHKo1GbGaRwBPbr6/aDJ4m IF1mwI7pOKdNNftA4+szAGUbMEKCmaPIaBTdf34rtrTj7XLTH0/Kyop4lz/fg26h =Q+KX -----END PGP SIGNATURE----- From rafael.knuth at gmail.com Mon Sep 30 13:30:55 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 30 Sep 2013 13:30:55 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: Dominik, > it's not your program - it's your attitude. We expect you to learn for yourself as well, and putting the commands you output into a script and execute it clearly isn't beyond what we can expect from someone who can use a mail program. Thanks for the clarification, you were the third kid on the block I missed to add to my feedback on behavior I find inappropriate. You are suggesting that my attitude is wrong, but what's wrong about doing baby-steps even if it's at the level of someone barely able to use a mail program? I simply want to create a To Do List program, and I couldn't find any tutorials on that, therefore I reached out to the mailing list. And here I am, justifying myself for my first clumsy attempt to accomplish my goal. I am still hoping that I will get some feedback from anyone on that list that will help me make a tiny little next step. Thank you in advance, Rafael From nik at naturalnet.de Mon Sep 30 13:41:47 2013 From: nik at naturalnet.de (Dominik George) Date: Mon, 30 Sep 2013 13:41:47 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Rafael Knuth schrieb: >Dominik, > >> it's not your program - it's your attitude. We expect you to learn >for yourself as well, and putting the commands you output into a script >and execute it clearly isn't beyond what we can expect from someone who >can use a mail program. > >Thanks for the clarification, you were the third kid on the block I >missed to add to my feedback on behavior I find inappropriate. >You are suggesting that my attitude is wrong, but what's wrong about >doing baby-steps even if it's at the level of someone barely able to >use a mail program? I simply want to create a To Do List program, and >I couldn't find any tutorials on that, therefore I reached out to the >mailing list. And here I am, justifying myself for my first clumsy >attempt to accomplish my goal. > >I am still hoping that I will get some feedback from anyone on that >list that will help me make a tiny little next step. > >Thank you in advance, > >Rafael You already got that - remove the surrounding print() and put it in a script. Why haven't you taken that advice yet? - -nik - -- Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail gesendet. -----BEGIN PGP SIGNATURE----- Version: APG v1.0.8-fdroid iQFNBAEBCgA3BQJSSWN7MBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJZPLCACyAJ1DL33nvDOZVj3/heWG zciLXGnvoINbiufZLjl5yPn/yxzJdS2knwUbE1AhuzoxiZCoLFMzZKN4BnXWdG1A cjqj8e/cin2YUWBG1eu53wcdU4iAhbwaKzLgP5soy8ZLc2cnWtf5Dmrgc+IGw02f /LZPBgw+XjngbYQ1U8RMH/15NKYuMVhy9WzRO19I4sOUCrQQspEBhvRwejS4eApO l7PwaHI3A6pxdWITaX/C8nVOpicUMVEDx9LE8+hswvGO6yIulyCkelkeAJgTcj5s MN6QDglZaguWLcDH3gGXfN6Go28RLPiC2hD1+Hv+JbCriVWxZd2WIBzh5K3It/OT =0kOH -----END PGP SIGNATURE----- From rafael.knuth at gmail.com Mon Sep 30 13:47:41 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 30 Sep 2013 13:47:41 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: Dominik, this was my original question: As of now, I want to understand how I can add further functionalities to my program such as: appending items to the list, removing and replacing items. Can anyone help? Simple as that. Rafael On Mon, Sep 30, 2013 at 1:41 PM, Dominik George wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > > > Rafael Knuth schrieb: >>Dominik, >> >>> it's not your program - it's your attitude. We expect you to learn >>for yourself as well, and putting the commands you output into a script >>and execute it clearly isn't beyond what we can expect from someone who >>can use a mail program. >> >>Thanks for the clarification, you were the third kid on the block I >>missed to add to my feedback on behavior I find inappropriate. >>You are suggesting that my attitude is wrong, but what's wrong about >>doing baby-steps even if it's at the level of someone barely able to >>use a mail program? I simply want to create a To Do List program, and >>I couldn't find any tutorials on that, therefore I reached out to the >>mailing list. And here I am, justifying myself for my first clumsy >>attempt to accomplish my goal. >> >>I am still hoping that I will get some feedback from anyone on that >>list that will help me make a tiny little next step. >> >>Thank you in advance, >> >>Rafael > > You already got that - remove the surrounding print() and put it in a script. > > Why haven't you taken that advice yet? > > - -nik > - -- > Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail gesendet. > -----BEGIN PGP SIGNATURE----- > Version: APG v1.0.8-fdroid > > iQFNBAEBCgA3BQJSSWN7MBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p > a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJZPLCACyAJ1DL33nvDOZVj3/heWG > zciLXGnvoINbiufZLjl5yPn/yxzJdS2knwUbE1AhuzoxiZCoLFMzZKN4BnXWdG1A > cjqj8e/cin2YUWBG1eu53wcdU4iAhbwaKzLgP5soy8ZLc2cnWtf5Dmrgc+IGw02f > /LZPBgw+XjngbYQ1U8RMH/15NKYuMVhy9WzRO19I4sOUCrQQspEBhvRwejS4eApO > l7PwaHI3A6pxdWITaX/C8nVOpicUMVEDx9LE8+hswvGO6yIulyCkelkeAJgTcj5s > MN6QDglZaguWLcDH3gGXfN6Go28RLPiC2hD1+Hv+JbCriVWxZd2WIBzh5K3It/OT > =0kOH > -----END PGP SIGNATURE----- > From joel.goldstick at gmail.com Mon Sep 30 14:01:39 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 30 Sep 2013 08:01:39 -0400 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: On Mon, Sep 30, 2013 at 7:47 AM, Rafael Knuth wrote: > Dominik, > > this was my original question: > > As of now, I want to understand how I can add > further functionalities to my program such as: appending items to the > list, removing and replacing items. Can anyone help? > > Simple as that. > > Rafael > > On Mon, Sep 30, 2013 at 1:41 PM, Dominik George wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA512 > > > > > > > > Rafael Knuth schrieb: > >>Dominik, > >> > >>> it's not your program - it's your attitude. We expect you to learn > >>for yourself as well, and putting the commands you output into a script > >>and execute it clearly isn't beyond what we can expect from someone who > >>can use a mail program. > >> > >>Thanks for the clarification, you were the third kid on the block I > >>missed to add to my feedback on behavior I find inappropriate. > >>You are suggesting that my attitude is wrong, but what's wrong about > >>doing baby-steps even if it's at the level of someone barely able to > >>use a mail program? I simply want to create a To Do List program, and > >>I couldn't find any tutorials on that, therefore I reached out to the > >>mailing list. And here I am, justifying myself for my first clumsy > >>attempt to accomplish my goal. > >> > >>I am still hoping that I will get some feedback from anyone on that > >>list that will help me make a tiny little next step. > >> > >>Thank you in advance, > >> > >>Rafael > > > > You already got that - remove the surrounding print() and put it in a > script. > > > > Why haven't you taken that advice yet? > > > > - -nik > > - -- > > Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail > gesendet. > > -----BEGIN PGP SIGNATURE----- > > Version: APG v1.0.8-fdroid > > > > iQFNBAEBCgA3BQJSSWN7MBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p > > a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJZPLCACyAJ1DL33nvDOZVj3/heWG > > zciLXGnvoINbiufZLjl5yPn/yxzJdS2knwUbE1AhuzoxiZCoLFMzZKN4BnXWdG1A > > cjqj8e/cin2YUWBG1eu53wcdU4iAhbwaKzLgP5soy8ZLc2cnWtf5Dmrgc+IGw02f > > /LZPBgw+XjngbYQ1U8RMH/15NKYuMVhy9WzRO19I4sOUCrQQspEBhvRwejS4eApO > > l7PwaHI3A6pxdWITaX/C8nVOpicUMVEDx9LE8+hswvGO6yIulyCkelkeAJgTcj5s > > MN6QDglZaguWLcDH3gGXfN6Go28RLPiC2hD1+Hv+JbCriVWxZd2WIBzh5K3It/OT > > =0kOH > > -----END PGP SIGNATURE----- > > > I think you are trying to jump into the middle of things without some basic foundation. Why not google 'python tutorial' and find one you like. Work thru that so you get an understanding about programming in python. Then you can come back to your 'to do list' project -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Sep 30 14:30:07 2013 From: davea at davea.name (Dave Angel) Date: Mon, 30 Sep 2013 12:30:07 +0000 (UTC) Subject: [Tutor] Creating To Do List Program - Question References: Message-ID: On 30/9/2013 07:47, Rafael Knuth wrote: > Dominik, > > this was my original question: > > As of now, I want to understand how I can add > further functionalities to my program such as: appending items to the > list, removing and replacing items. Can anyone help? > > Simple as that. > Your original program had some code that interacted with the user. So when you went from that to a giant print statement, I, and proably many others, thought you were just kidding. Are you using Python 3.3, under Windows? So let me ask some questions about your level of understanding. Do you know what an if statement is? How about a for or while statement? Can you write code in a function, have it take parameters and return results? Do you know how to call such a function? Do you know what a list is? Can you manipulate it at all? Can you create it from a literal, using the [] syntax. Do you know what a file is? Do you know the difference between text file and binary file? Can you read a text file into a list? Can you write a list of strings out to a text file? If you understand all these pieces, you're probably ready to try to construct a todo list program. If not, I second the suggestion to follow a tutorial, till it's covered at least all of these. (I may have missed quite a few items, but I think all of these are necessary.) For example, write a function that builds a list of strings by asking the user, a line at a time, till the user enters a blank string. The function should return the list. Once you think you have the function written, write a simple top-level program that calls the function and prints the results. Then have it print the results one line at a time. -- DaveA From roberto03 at gmail.com Mon Sep 30 14:49:40 2013 From: roberto03 at gmail.com (roberto) Date: Mon, 30 Sep 2013 14:49:40 +0200 Subject: [Tutor] writing python on the web Message-ID: Hi, my school is considering a massive shift to Chromebooks. I've to carefully think about how could the students go on writing their python programs on the web. Do you know any online interpreter where programs might be written, saved and modified. If sharing and collaborating were allowed, that would be a big plus. Cheers. -- Roberto -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafael.knuth at gmail.com Mon Sep 30 15:00:08 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 30 Sep 2013 15:00:08 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: Hej Dave, thank you for your response. > Your original program had some code that interacted with the user. So > when you went from that to a giant print statement, I, and proably many > others, thought you were just kidding. I noticed that, but I was serious about that. I mean, my giant print statement was really ridiculous to say the least but it did what I wanted the program to do - adding items to the To Do List and printing that list. However, I knew this was my very first iteration and I wanted to improve my program by making those incremental baby steps. > Are you using Python 3.3, under Windows? Python 3.0 under Windows. > So let me ask some questions about your level of understanding. Sure. > Do you know what an if statement is? How about a for or while > statement? Yes, I am familiar with both. > Can you write code in a function, have it take parameters and return > results? Do you know how to call such a function? Yes. > Do you know what a list is? Can you manipulate it at all? Can you > create it from a literal, using the [] syntax. Yes. > Do you know what a file is? Do you know the difference between text > file and binary file? Can you read a text file into a list? Can you > write a list of strings out to a text file? I worked with text files yet, I have to admit I haven't worked with binary files though - and I don't know yet what they are. But I will figure that out. > If you understand all these pieces, you're probably ready to try to > construct a todo list program. If not, I second the suggestion to > follow a tutorial, till it's covered at least all of these. Ok, cool. > (I may have missed quite a few items, but I think all of these are > necessary.) Ok, so I will rewrite that To Do list as you (and the others) suggested and I will get back to you in case I have any further questons. > For example, write a function that builds a list of strings by asking > the user, a line at a time, till the user enters a blank string. The > function should return the list. Ok, understood. > Once you think you have the function written, write a simple top-level > program that calls the function and prints the results. Then have it > print the results one line at a time. I don't understand yet what a top-level program is, but I will figure that out. Again, thank you all. I have a fairly good understanding of how I should proceed now. Rafael From wprins at gmail.com Mon Sep 30 15:08:11 2013 From: wprins at gmail.com (Walter Prins) Date: Mon, 30 Sep 2013 14:08:11 +0100 Subject: [Tutor] writing python on the web In-Reply-To: References: Message-ID: Hi, On 30 September 2013 13:49, roberto wrote: > Hi, my school is considering a massive shift to Chromebooks. I've to > carefully think about how could the students go on writing their python > programs on the web. > Do you know any online interpreter where programs might be written, saved > and modified. If sharing and collaborating were allowed, that would be a > big plus. > > These are some online and/or web based Python offerings I've run across: https://www.pythonanywhere.com/ http://pythonfiddle.com/ http://www.learnpython.org/ http://www.trypython.org/ http://shell.appspot.com/ http://www.pythontutor.com/ http://interactivepython.org/courselib/static/thinkcspy/index.html Regards, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From nik at naturalnet.de Mon Sep 30 15:29:40 2013 From: nik at naturalnet.de (Dominik George) Date: Mon, 30 Sep 2013 15:29:40 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: <20130930132939.GF17268@keks.naturalnet.de> Hi Rafael, > > Your original program had some code that interacted with the user. So > > when you went from that to a giant print statement, I, and proably many > > others, thought you were just kidding. > > I noticed that, but I was serious about that. I mean, my giant print > statement was really ridiculous to say the least but it did what I > wanted the program to do - adding items to the To Do List and printing > that list. However, I knew this was my very first iteration and I > wanted to improve my program by making those incremental baby steps. That still doesn't explain why you only have a print() statement print Python statements, rather than execute these Python statements. > > Are you using Python 3.3, under Windows? > > Python 3.0 under Windows. Why, exactly? > > Can you write code in a function, have it take parameters and return > > results? Do you know how to call such a function? > > Yes. Then do it, I'd suggest. > > Do you know what a file is? Do you know the difference between text > > file and binary file? Can you read a text file into a list? Can you > > write a list of strings out to a text file? > > I worked with text files yet, I have to admit I haven't worked with > binary files though - and I don't know yet what they are. But I will > figure that out. That's basically any file that contains, or is supposed to contain, non-printable characters, or where \n has another meaning than liebreaking. You normally read a plaintext file line by line and a binary file byte by byte. > > If you understand all these pieces, you're probably ready to try to > > construct a todo list program. If not, I second the suggestion to > > follow a tutorial, till it's covered at least all of these. > > Ok, cool. OTOH, *if* your claim that you understand the concepts mentioned by Dave isn't an ill-minded overestimation, I wonder why you don't go and use these skills. Doyou lack a concept of how to logically build up your code, or what's the main issue? > Ok, so I will rewrite that To Do list as you (and the others) > suggested and I will get back to you in case I have any further > questons. That's good ?! > > Once you think you have the function written, write a simple top-level > > program that calls the function and prints the results. Then have it > > print the results one line at a time. > > I don't understand yet what a top-level program is, but I will figure that out. The thing the python interpreter calls, that is not in a class:, def: or some other block. > Again, thank you all. > I have a fairly good understanding of how I should proceed now. You're welcome back with your results ?! -nik -- Ein Jabber-Account, sie alle zu finden; ins Dunkel zu treiben und ewig zu binden; im NaturalNet, wo die Schatten droh'n ;)! PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From rafael.knuth at gmail.com Mon Sep 30 17:10:05 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 30 Sep 2013 17:10:05 +0200 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: <20130930132939.GF17268@keks.naturalnet.de> References: <20130930132939.GF17268@keks.naturalnet.de> Message-ID: Dominik, > OTOH, *if* your claim that you understand the concepts mentioned by Dave > isn't an ill-minded overestimation, I wonder why you don't go and use > these skills. Doyou lack a concept of how to logically build up your > code, or what's the main issue? Exactly. I didn't know how to put those pieces I learned into a program I wanted to create, and I was not aware of which skills I still missed (which turned out to be writing to and reading from files). >> I don't understand yet what a top-level program is, but I will figure that out. > > The thing the python interpreter calls, that is not in a class:, def: or > some other block. Ok, go you. > You're welcome back with your results ?! Thank you! All the best, Rafael From davea at davea.name Mon Sep 30 21:14:39 2013 From: davea at davea.name (Dave Angel) Date: Mon, 30 Sep 2013 19:14:39 +0000 (UTC) Subject: [Tutor] Creating To Do List Program - Question References: Message-ID: On 30/9/2013 09:00, Rafael Knuth wrote: > Hej Dave, > > thank you for your response. > >> Your original program had some code that interacted with the user. So >> when you went from that to a giant print statement, I, and proably many >> others, thought you were just kidding. > > I noticed that, but I was serious about that. I mean, my giant print > statement was really ridiculous to say the least but it did what I > wanted the program to do - adding items to the To Do List and printing > that list But it didn't do any such thing. It just displayed some python code to the user, without running any of it. > However, I knew this was my very first iteration and I > wanted to improve my program by making those incremental baby steps. > >> Are you using Python 3.3, under Windows? > > Python 3.0 under Windows. Version 3.0 was probably the buggiest version in a decade. You really should upgrade to at least 3.3.2 > >> So let me ask some questions about your level of understanding. > > Sure. > >> Do you know what an if statement is? How about a for or while >> statement? > > Yes, I am familiar with both. > >> Can you write code in a function, have it take parameters and return >> results? Do you know how to call such a function? > > Yes. > >> Do you know what a list is? Can you manipulate it at all? Can you >> create it from a literal, using the [] syntax. > > Yes. > >> Do you know what a file is? Do you know the difference between text >> file and binary file? Can you read a text file into a list? Can you >> write a list of strings out to a text file? > > I worked with text files yet, I have to admit I haven't worked with > binary files though - and I don't know yet what they are. But I will > figure that out. I'm not as concerned that you know how to deal with them, as that you're aware that there are files that are not text, and the rules for manipulating them will be different. You won't need them for this program. > >> If you understand all these pieces, you're probably ready to try to >> construct a todo list program. If not, I second the suggestion to >> follow a tutorial, till it's covered at least all of these. > > Ok, cool. > >> (I may have missed quite a few items, but I think all of these are >> necessary.) > > Ok, so I will rewrite that To Do list as you (and the others) > suggested and I will get back to you in case I have any further > questons. > >> For example, write a function that builds a list of strings by asking >> the user, a line at a time, till the user enters a blank string. The >> function should return the list. > > Ok, understood. You can write such a function, and test it, without writing any other pieces of the to-do list. That's why I suggest you start there. Write it, test it, and then show it here for comment. Later, you can use that to take in one-day's worth of to-do items. > >> Once you think you have the function written, write a simple top-level >> program that calls the function and prints the results. Then have it >> print the results one line at a time. > > I don't understand yet what a top-level program is, but I will figure that out. Any code written at the left margin is top-level. Python runs only the top-level code in your script; it's up to that code to call the various functions and/or classes that you may also define. But many beginners put everything at top-level, which is very limiting. > > Again, thank you all. > I have a fairly good understanding of how I should proceed now. > > Rafael > _______________________________________________ -- DaveA From alan.gauld at btinternet.com Mon Sep 30 21:31:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Sep 2013 20:31:58 +0100 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: On 30/09/13 12:12, Rafael Knuth wrote: > @Alan @Joel: > I didn't know that pouring corn on newbies We weerenm't pouring corn, we were pointing out that the program you claimed to have working as a ToDo list did no such thing. It doesn't add anmy items it doesn't store it doesn;t retriebe. All it does is print another program to the screen. Hence it is identical to print('Hello World') except that instead of 'Hello World' it prints a long text string which happens to look like a python program. But not the one you are running. So when you say you got the ToDo list program running it was not with the code you posted. We can't help you add features to something that doesn't work in the first place. > Why don't you try writing a program instead? I write lots of programs and I sometimes even ask questions about them here. But that's not going to help you write programs. > I tried my best and that's what I came up with And what you have is a single print statement with a long string inside. > I do not understand why you don't consider what I wrote not a program > ("Hello World!" in a more elaborate form), Printing Hello world is a valid program, just not a ToDo list program. > as the user is actually able to a list, to write to and reads from > it (in a very primitive manner though). Not using the code that you posted they can't. Look below. Everything is inside a print statement so it does nothing but print. >> Now, if instead of just printing it you actually ran >> the code you print it might actually get you somewhere >> closer. This was the advice given. Did you try it? >>> print(""" >>> >>> Welcome World's Most Geeky To Do List Program >>> >>> G E E K L I S T 1 . 0 >>> >>> If you want to add items to the list, enter: >>> >>> text_file = open("ToDoList.txt", "w") >>> text_file.write("add your item here ") >>> text_file.write("add action item here ") >>> text_file.write("you get the point, right?") >>> text_file.close() >>> >>> If you want to print your to do list, enter: >>> >>> text_file = open("ToDoList.txt", "r") >>> print(text_file.read()) >>> text_file.close() >>> >>> We are constantly improving our program, watch out for version 2.0! >>> >>> """) Notice the """? That says treat everything inside as a single string and print it. You are not executing the "code" inside the string you are only printing it. Now if we critique the code inside the string as if it were executable we find that the first thing it does is opens a file in write mode ("w") which deletes any existing data and creates a new empty file. Next you write the prompts that presumably should go to your user in the file but don't display them to the user. You then close the file which sends it to disk. You then open the file you just created, read it and print it which displays the prompts and you then close it again. Next time you run the program you delete the prompts then recreate them. But the user has no ability to add or edit anything. So either way the program does not do what you claim it does. Now, reviewing the assistance you already received you were told you needed to do the following: read the data file (if it already exists). Populate your ToDo list in memory using that data Create a loop which Presents the user with a menu and process the commands by adding, deleting or modifying entries in the list When the user is done write the new modified ToDo list out to your file overwriting the old one. You do not appear to have done any of that yet. You can find a very similar program in my tutorial based on an address book. It is developed over several 'chapters' from a simple in memory list to a file based one and finally using a SQLite database. So if you had read my tutorial as suggested you would have found most of the code you need already there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 30 21:42:51 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Sep 2013 20:42:51 +0100 Subject: [Tutor] writing python on the web In-Reply-To: References: Message-ID: On 30/09/13 13:49, roberto wrote: > Hi, my school is considering a massive shift to Chromebooks. I've to > carefully think about how could the students go on writing their python > programs on the web. It's not just Python it's any kind of program. There are a few online interpreters around but if you are planning on teaching computing, a ChromeBook or any other cloud based tool is going to make it hard if not impossible to teach effectively. You maybe need to feed that back to your administration before they seriously damage their students prospects and their schools reputation. They may be slightly cheaper (and we are only talking about $50 each!) but they are very limited devices. If you are forced to go down that route consider finding an online terminal emulator and get the students to use it to access a server someplace where you can install Python and any other environment you need. That's still limiting things to text but better than an online interpreter IMHO. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From amitsaha.in at gmail.com Mon Sep 30 21:57:38 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Tue, 1 Oct 2013 05:57:38 +1000 Subject: [Tutor] writing python on the web In-Reply-To: References: Message-ID: On Tue, Oct 1, 2013 at 5:42 AM, Alan Gauld wrote: > On 30/09/13 13:49, roberto wrote: >> >> Hi, my school is considering a massive shift to Chromebooks. I've to >> carefully think about how could the students go on writing their python >> programs on the web. > > > It's not just Python it's any kind of program. > There are a few online interpreters around but if you are > planning on teaching computing, a ChromeBook or any other cloud > based tool is going to make it hard if not impossible to teach effectively. > > You maybe need to feed that back to your administration before they > seriously damage their students prospects and their schools reputation. > They may be slightly cheaper (and we are only talking about $50 each!) > but they are very limited devices. > > If you are forced to go down that route consider finding an online terminal > emulator and get the students to use it to access a server someplace where > you can install Python and any other environment you need. That's still > limiting things to text but better than an online interpreter IMHO. I am +1 in agreeing with Alan on all the above points. If your school really wants to teach programming, nothing other than a "real" computer should be the first preference. That said, considering Alan's last point, if you must, take a look at https://www.nitrous.io . I haven't used it much, but they give you terminal access, etc. May help. -Amit. -- http://echorand.me From gupta.leena at gmail.com Mon Sep 30 22:29:00 2013 From: gupta.leena at gmail.com (Leena Gupta) Date: Mon, 30 Sep 2013 13:29:00 -0700 Subject: [Tutor] Regex Question Message-ID: Hello, I have a TSV file that has the city,state,country information in this format: Name Display name Code San Jose SJC SJC - SJ (POP), CA (US) San Francisco SFO SFO - SF, CA (US) I need to extract the state and country for each city from this file. I'm trying to do this in python by using the following Regex: s=re.search(',(.*?)\(',text) if s: state=s.group(1).strip() c=re.search('\((.*?)\)',text) if c: country=c.group(1).strip() This works well for the state. But for country for San Jose, it brings the following: country = POP I think it maybe better to search from the end of the string,but I am unable to get the right syntax. Could you please share any pointers? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Sep 30 22:48:02 2013 From: davea at davea.name (Dave Angel) Date: Mon, 30 Sep 2013 20:48:02 +0000 (UTC) Subject: [Tutor] Regex Question References: Message-ID: On 30/9/2013 16:29, Leena Gupta wrote: > Hello, > > I have a TSV file that has the city,state,country information in this > format: > Name Display name Code > San Jose SJC SJC - SJ (POP), CA (US) > San Francisco SFO SFO - SF, CA (US) That's not a format, it's a infinitesimally tiny sample. But if we trust in this sample, you don't need a regex at all. The state and country are in the last 7 characters of the string: countr = text[-3:-1] state = text[-7:-5] I could be off by 1 or 2, but you get the idea. if this isn't good enough, then either supply or give a reference to a specification for how "code" is encoded. (If it does indeed need a regex, someone else will have to help) -- DaveA From breamoreboy at yahoo.co.uk Mon Sep 30 23:19:27 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 30 Sep 2013 22:19:27 +0100 Subject: [Tutor] Regex Question In-Reply-To: References: Message-ID: On 30/09/2013 21:29, Leena Gupta wrote: > Hello, > > I have a TSV file that has the city,state,country information in this > format: > Name Display name Code > San Jose SJC SJC - SJ (POP), CA (US) > San Francisco SFO SFO - SF, CA (US) > > I need to extract the state and country for each city from this file. > I'm trying to do this in python by using the following Regex: > > s=re.search(',(.*?)\(',text) > if s: > state=s.group(1).strip() > c=re.search('\((.*?)\)',text) > if c: > country=c.group(1).strip() > > > This works well for the state. But for country for San Jose, it brings > the following: > country = POP > > I think it maybe better to search from the end of the string,but I am > unable to get the right syntax. Could you please share any pointers? > > Thanks! > I'd be strongly inclined to use the CSV module from the standard library with an excel-tab dialect name, see http://docs.python.org/3/library/csv.html#module-csv Please try it and if you encounter any problems feel free to get back to us, we don't bite :) -- Cheers. Mark Lawrence From vitsen at gmx.com Mon Sep 30 11:15:40 2013 From: vitsen at gmx.com (vitsen at gmx.com) Date: Mon, 30 Sep 2013 11:15:40 +0200 Subject: [Tutor] Easiest framework for web development? Message-ID: <5249413C.3050100@gmx.com> Hi Which of the available Python frameworks is the EASIEST to learn for a NEWBIE who needs to do *basic* web development? (only the *most basic* web functionality will be needed) Could you please provide links to any relevant tutorials for learning such a Python-based web framework? (again, possibly the easiest tutorial) Thanks Vit