Re: beginner question-very basic
On Sun, 11 Aug 2019 12:50:29 -0400, slefkowitz wrote: > Just getting started with Python. > > Downloaded 3.7.4 rom python.org > > I wrote program in Notepad, saved it with a ".py" extension. > > What do I do next? How do I execute a program? I am assuming you are using Windows since you posted with Outlook and that the python executable is in your path. Open a cmd window and enter: python \path\to\program.py -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
beginner question-very basic
Just getting started with Python. Downloaded 3.7.4 rom python.org I wrote program in Notepad, saved it with a ".py" extension. What do I do next? How do I execute a program? -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question
On Thursday, June 2, 2016 at 6:38:56 AM UTC-7, Igor Korot wrote: > Steven, > > On Thu, Jun 2, 2016 at 1:20 AM, Steven D'Aprano > <steve+comp.lang.pyt...@pearwood.info> wrote: > > On Thursday 02 June 2016 14:21, Igor Korot wrote: > > > >> Hi, guys, > >> > >> On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp <robertvst...@gmail.com> wrote: > >>> On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <m...@sightlineinnovation.com> > >>> wrote: > >>>> Hi to all > >>>> > >>>> I have a beginner question to which I have not found an answer I was able > >>>> to understand. Could someone explain why the following program: > >>>> > >>>> def f(a, L=[]): > >>>> L.append(a) > >>>> return L > >>>> > >>>> print(f(1)) > >>>> print(f(2)) > >>>> print(f(3)) > >>>> > >>>> gives us the following result: > >>>> > >>>> [1] > >>>> [1,2] > >>>> [1,2,3] > >>>> > >>>> How can this be, if we never catch the returned L when we call it, and we > >>>> never pass it on back to f??? > >> > >> I think the OP question here is: > >> > >> Why it is printing the array? > > > > Because he calls the function, then prints the return result. > > > > print(f(1)) > > > > calls f(1), which returns [1], then prints [1]. > > > > Then he calls: > > > > print(f(2)) > > > > which returns [1, 2] (but he expects [2]), then prints it. And so on. > > > > > >> There is no line like: > >> > >> t = f(1) > >> print t > > > > Correct. But there are lines: > > > > print(f(1)) > > print(f(2)) > > print(f(3)) > > I think you missed the point. > > Compare: > > def f(a, L=[]): > L.append(a) > return L > > print(f(1)) > print(f(2)) > print(f(3)) > > vs. > > def f(a, L=[]): > L.append(a) > return L > > t = f(1) > print t > t = f(2) > print t > t = f(3) > print t > > For people that comes from C/C++/Java, the first syntax is kind of weird: > you return a value from the function but the caller does not save it anywhere. > Especially since the return is not a basic type and most of them are > not familiar > with scalar vs list context (sorry for the Perl terminology here) > > Thank you. > > > > > > > > > > -- > > Steve > > > > -- > > https://mail.python.org/mailman/listinfo/python-list I came from C/C++/Java, and the first syntax makes perfect sense to me. You're just taking the result of a function and directly passing it as a parameter to another. There's nothing confusing about that. C/C++/Java let you do it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question
Steven, On Thu, Jun 2, 2016 at 1:20 AM, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > On Thursday 02 June 2016 14:21, Igor Korot wrote: > >> Hi, guys, >> >> On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp <robertvst...@gmail.com> wrote: >>> On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <m...@sightlineinnovation.com> >>> wrote: >>>> Hi to all >>>> >>>> I have a beginner question to which I have not found an answer I was able >>>> to understand. Could someone explain why the following program: >>>> >>>> def f(a, L=[]): >>>> L.append(a) >>>> return L >>>> >>>> print(f(1)) >>>> print(f(2)) >>>> print(f(3)) >>>> >>>> gives us the following result: >>>> >>>> [1] >>>> [1,2] >>>> [1,2,3] >>>> >>>> How can this be, if we never catch the returned L when we call it, and we >>>> never pass it on back to f??? >> >> I think the OP question here is: >> >> Why it is printing the array? > > Because he calls the function, then prints the return result. > > print(f(1)) > > calls f(1), which returns [1], then prints [1]. > > Then he calls: > > print(f(2)) > > which returns [1, 2] (but he expects [2]), then prints it. And so on. > > >> There is no line like: >> >> t = f(1) >> print t > > Correct. But there are lines: > > print(f(1)) > print(f(2)) > print(f(3)) I think you missed the point. Compare: def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3)) vs. def f(a, L=[]): L.append(a) return L t = f(1) print t t = f(2) print t t = f(3) print t For people that comes from C/C++/Java, the first syntax is kind of weird: you return a value from the function but the caller does not save it anywhere. Especially since the return is not a basic type and most of them are not familiar with scalar vs list context (sorry for the Perl terminology here) Thank you. > > > > -- > Steve > > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question
That linked help clear up my confusion...yes you really have to know how things work internally to understand why things happen the way they happen. Thanks again to all -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question
On Thursday 02 June 2016 14:21, Igor Korot wrote: > Hi, guys, > > On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp <robertvst...@gmail.com> wrote: >> On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <m...@sightlineinnovation.com> >> wrote: >>> Hi to all >>> >>> I have a beginner question to which I have not found an answer I was able >>> to understand. Could someone explain why the following program: >>> >>> def f(a, L=[]): >>> L.append(a) >>> return L >>> >>> print(f(1)) >>> print(f(2)) >>> print(f(3)) >>> >>> gives us the following result: >>> >>> [1] >>> [1,2] >>> [1,2,3] >>> >>> How can this be, if we never catch the returned L when we call it, and we >>> never pass it on back to f??? > > I think the OP question here is: > > Why it is printing the array? Because he calls the function, then prints the return result. print(f(1)) calls f(1), which returns [1], then prints [1]. Then he calls: print(f(2)) which returns [1, 2] (but he expects [2]), then prints it. And so on. > There is no line like: > > t = f(1) > print t Correct. But there are lines: print(f(1)) print(f(2)) print(f(3)) -- Steve -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question
Hi, guys, On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp <robertvst...@gmail.com> wrote: > On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <m...@sightlineinnovation.com> > wrote: >> Hi to all >> >> I have a beginner question to which I have not found an answer I was able to >> understand. Could someone explain why the following program: >> >> def f(a, L=[]): >> L.append(a) >> return L >> >> print(f(1)) >> print(f(2)) >> print(f(3)) >> >> gives us the following result: >> >> [1] >> [1,2] >> [1,2,3] >> >> How can this be, if we never catch the returned L when we call it, and we >> never pass it on back to f??? I think the OP question here is: Why it is printing the array? There is no line like: t = f(1) print t So, why the first print does print the list? The return value should be thrown away... Thank you. > > This comes up rather frequently. In fact, if you just copy your > function (Which is used in the official Python tutuorial.) and paste > it into Google you will get some relevant hits. One such is: > > https://pythonconquerstheuniverse.wordpress.com/category/python-gotchas/ > > As the link will explain the behavior you observe is a consequence of > two things: When Python assigns the default argument for the empty > list and that lists are *mutable*. > > Enjoy! > > > -- > boB > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question
On Thursday 02 June 2016 10:55, Marcin Rak wrote: > Hi to all > > I have a beginner question to which I have not found an answer I was able to > understand. Could someone explain why the following program: > > def f(a, L=[]): > L.append(a) > return L The default value is set once, and once only, so you get the same list each time, not a new empty list. Default values in Python are sort of like this: HIDDEN_DEFAULT_VALUE = [] # initialised once def f(a, L): if L is not defined: L = HIDDEN_DEFAULT_VALUE L.append(a) return L except that HIDDEN_DEFAULT_VALUE is not actually a global variable. Every function gets its own storage for defaults. The technical term for this is "early binding of default values". If you want to get a new, fresh list each time ("late binding of default values") you should use a sentinel value: def f(a, L=None): if L is None: L = [] # new, fresh list each time L.append(a) return L -- Steve -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question
On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <m...@sightlineinnovation.com> wrote: > Hi to all > > I have a beginner question to which I have not found an answer I was able to > understand. Could someone explain why the following program: > > def f(a, L=[]): > L.append(a) > return L > > print(f(1)) > print(f(2)) > print(f(3)) > > gives us the following result: > > [1] > [1,2] > [1,2,3] > > How can this be, if we never catch the returned L when we call it, and we > never pass it on back to f??? This comes up rather frequently. In fact, if you just copy your function (Which is used in the official Python tutuorial.) and paste it into Google you will get some relevant hits. One such is: https://pythonconquerstheuniverse.wordpress.com/category/python-gotchas/ As the link will explain the behavior you observe is a consequence of two things: When Python assigns the default argument for the empty list and that lists are *mutable*. Enjoy! -- boB -- https://mail.python.org/mailman/listinfo/python-list
Beginner Question
Hi to all I have a beginner question to which I have not found an answer I was able to understand. Could someone explain why the following program: def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3)) gives us the following result: [1] [1,2] [1,2,3] How can this be, if we never catch the returned L when we call it, and we never pass it on back to f??? Any help is appreciated. Marcin -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner question - class definition error
from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): return Label(text='Hello World') if __name__ == '__main__': MyApp().run() I get this error when I run it: Traceback (most recent call last): File MinimalApplication.py, line 7, in module class MyApp(App): File MinimalApplication.py, line 12, in MyApp MyApp().run() NameError: name 'MyApp' is not defined How can I fix this please? Try removing beginning indentation from if __name__ == '__main__': if __name__ == '__main__': -- Stanley C. Kitching Human Being Phoenix, Arizona -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginner question - class definition error
On 2015-01-28 11:10, David Aldrich wrote: Hi I am just getting started with Python 3.3.3 and Kivy 1.8. I am using the Kivy development environment on Windows (open a command prompt and call kivy.bat). With this minimal code: import kivy kivy.require('1.8.0') from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): return Label(text='Hello World') if __name__ == '__main__': MyApp().run() I get this error when I run it: C:\python MinimalApplication.py [INFO ] Kivy v1.8.0 [INFO ] [Logger ] Record log in snip [INFO ] [Factory ] 157 symbols loaded [DEBUG ] [Cache ] register kv.lang with limit=None, timeout=Nones [DEBUG ] [Cache ] register kv.image with limit=None, timeout=60s [DEBUG ] [Cache ] register kv.atlas with limit=None, timeout=Nones [INFO ] [Image ] Providers: img_tex, img_dds, img_pygame, img_gif (img_pil ignored) [DEBUG ] [Cache ] register kv.texture with limit=1000, timeout=60s [DEBUG ] [Cache ] register kv.shader with limit=1000, timeout=3600s [INFO ] [Text] Provider: pygame Traceback (most recent call last): File MinimalApplication.py, line 7, in module class MyApp(App): File MinimalApplication.py, line 12, in MyApp MyApp().run() NameError: name 'MyApp' is not defined How can I fix this please? Unindent the 'if' statement. Currently, it's indented inside the class definition, so MyApp isn't defined yet. -- https://mail.python.org/mailman/listinfo/python-list
Beginner question - class definition error
Hi I am just getting started with Python 3.3.3 and Kivy 1.8. I am using the Kivy development environment on Windows (open a command prompt and call kivy.bat). With this minimal code: import kivy kivy.require('1.8.0') from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): return Label(text='Hello World') if __name__ == '__main__': MyApp().run() I get this error when I run it: C:\python MinimalApplication.py [INFO ] Kivy v1.8.0 [INFO ] [Logger ] Record log in snip [INFO ] [Factory ] 157 symbols loaded [DEBUG ] [Cache ] register kv.lang with limit=None, timeout=Nones [DEBUG ] [Cache ] register kv.image with limit=None, timeout=60s [DEBUG ] [Cache ] register kv.atlas with limit=None, timeout=Nones [INFO ] [Image ] Providers: img_tex, img_dds, img_pygame, img_gif (img_pil ignored) [DEBUG ] [Cache ] register kv.texture with limit=1000, timeout=60s [DEBUG ] [Cache ] register kv.shader with limit=1000, timeout=3600s [INFO ] [Text] Provider: pygame Traceback (most recent call last): File MinimalApplication.py, line 7, in module class MyApp(App): File MinimalApplication.py, line 12, in MyApp MyApp().run() NameError: name 'MyApp' is not defined How can I fix this please? Best regards David -- https://mail.python.org/mailman/listinfo/python-list
RE: Beginner question - class definition error
Unindent the 'if' statement. Currently, it's indented inside the class definition, so MyApp isn't defined yet. Thanks very much. That fixed it. Best regards David -- https://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
Le jeudi 8 août 2013 22:29:00 UTC+2, Terry Reedy a écrit : On 8/8/2013 7:41 AM, Chris Angelico wrote: On Thu, Aug 8, 2013 at 7:20 AM, wxjmfa...@gmail.com wrote: def z2(): ... letters = 'abc' ... while True: ... c = input('letter: ') ... if c not in letters: ... print('end, fin, Schluss') ... break ... else: ... print('do stuff') Minor quibble: I don't like having a hard exit followed by an else. Whereas I tend to prefer to have the two alternatives cleanly marked as alternatives by both being indented the same. Many alternatives are not so trivial as the above. I remember reading one snippet in the CPython codebase where the 'else' was omitted and the if clause subdivided into about three paths. It took at least a minute to determine that all paths terminated in such a way that there really was an inplied else. How much easier it would have been to read the code if the author had explicitly types the 'else'. If the if branch will unconditionally quit the loop (with a break, here, but could also be a return, a thrown exception, etc etc), I would prefer to see the else removed and its code unindented one level. Maybe this is just personal preference, though, learned from assembly language programming where a block if looks something like this: ; if x == y: CMP x,y JNZ .else ; Code for x == y JMP .endif .else: ; Code for else .endif Putting an unconditional departure in the x == y branch makes the JMP .endif redundant. Python is not assembly ;-). 3.3 effectively ignores the extraneous 'else:'. Either way, if the condition is false, control jumps to the second print. For what little it matters, the bytecode is the same length. def f(): while True: if a: b = 1 break else: b = 2 dis(f) 2 0 SETUP_LOOP 25 (to 28) 3 3 LOAD_GLOBAL 0 (a) 6 POP_JUMP_IF_FALSE 19 4 9 LOAD_CONST 1 (1) 12 STORE_FAST 0 (b) 5 15 BREAK_LOOP 16 JUMP_ABSOLUTE3 719 LOAD_CONST 2 (2) 22 STORE_FAST 0 (b) 25 JUMP_ABSOLUTE3 28 LOAD_CONST 0 (None) 31 RETURN_VALUE def f(): while True: if a: b = 1 break b = 2 dis(f) 2 0 SETUP_LOOP 25 (to 28) 3 3 LOAD_GLOBAL 0 (a) 6 POP_JUMP_IF_FALSE 19 4 9 LOAD_CONST 1 (1) 12 STORE_FAST 0 (b) 5 15 BREAK_LOOP 16 JUMP_FORWARD 0 (to 19) 619 LOAD_CONST 2 (2) 22 STORE_FAST 0 (b) 25 JUMP_ABSOLUTE3 28 LOAD_CONST 0 (None) 31 RETURN_VALUE -- Terry Jan Reedy - The problem of this guy is not at this level. His problem is more simply, he most probably does not understand how to build a correct, proper loop. What I wanted to happen is when the user typed something ... ... would cause the program to stop ... jmf -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
This is what I ended up with btw. Does this insult anyone's more well attuned Python sensibilities? letters='abcdefghijkl' def repeat(): print('wanna go again?') batman=input() if batman in ('y','yes'): main() else: return def main(): print('guess a letter') batman=input() if batman in letters: print('ok that letter was in letters') repeat() else: print('asdasdasd') repeat() main() print('how ya doin') -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
This is what I ended up with btw. Does this insult anyone's more well-attuned Pythonic sensibilities? letters='abcdefghijkl' def repeat(): print('wanna go again?') batman=input() if batman in ('y','yes'): main() else: return def main(): print('guess a letter') batman=input() if batman in letters: print('ok that letter was in letters') repeat() else: print('asdasdasd') repeat() main() print('how ya doin') -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On 9 August 2013 23:27, eschneide...@comcast.net wrote: This is what I ended up with btw. Does this insult anyone's more well attuned Python sensibilities? ... Yes. You didn't listen to any of the advice we've been giving you. You've had *much* better answers given than this. Start from the top. We need letters, so define that: letters = abcdefghijkl We then want to loop, possibly forever. A good choice is a while loop. # True is always True, so will loop forever while True: We then want to ask for a letter. We want to use input. Write help(input) in the Python Shell and you get help(input) Help on built-in function input in module builtins: input(...) input([prompt]) - string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. So our line should be: letter = input(Type a letter from 'a' to 'n' in the alphabet: ) Then we want to test if it's on of our letters: if letter in letters: And if so we want to say something positive: print(That's right.) If not we want to say something negative: else: print(That's wrong.) And then we want to ask if we should go again: go_again = input(Do you want to do this again? ) If the response is y or yes, we want to continue looping. The while loop will do that automatically, so we can do nothing in this circumstance. If the response in *not* y or yes, we want to stop: if go_again not in (y, yes): break That's it. No need to complicate things. Just take it one step at a time. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
I don't understand any of the advice any of you have given. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
Thanks, though me not utilizing any of the other advice wasn't from lack of trying; I couldn't understand any of it. I get it now that I have a corrrect example code in front of me. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On 10 August 2013 00:14, eschneide...@comcast.net wrote: I don't understand any of the advice any of you have given. What about it don't you understand? Pick a sentence you don't understand and throw it back at us. If you understand all the sentences but not how they come together, say so. If there's a leap that you don't understand, say that you don't get it. We've tried rephrasing things a few ways but without any interaction we can't really help. --- You have said I figured that ... the batman==False part of the repeat() function would cause the 'while batman==True' part to become False and end. We have said this is untrue. The batman = False inside the function does not affect batman outside of the function. You need to put global batman in the function for it to change batman on a global scope. You've not once explained what part of this explanation confuses you. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
What does global mean? -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
(I forgot to post this with my last post.) Also, I don't understand any part of the following example, so there's no specific line that's confusing me. Thanks for the help btw. var = 42 def myfunc(): var = 90 print before:, var myfunc() print after:, var def myfunc(): global var var = 90 -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
(I forgot to post this with my last post.) Also, I don't understand any part of the following example, so there's no specific line that's confusing me. Thanks for the help btw. var = 42 def myfunc(): var = 90 print before:, var myfunc() print after:, var def myfunc(): global var var = 90 -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On 10/08/2013 00:40, eschneide...@comcast.net wrote: (I forgot to post this with my last post.) Also, I don't understand any part of the following example, so there's no specific line that's confusing me. Thanks for the help btw. You don't understand _any_ of it? var = 42 Here you're assigning to 'var'. You're not in a function, so 'var' is a global variable. def myfunc(): var = 90 Here you're assigning to 'var'. If you assign to a variable anywhere in a function, and you don't say that that variable is global, then it's treated as being local to that function, and completely unrelated to any other variable outside that function. print before:, var myfunc() print after:, var def myfunc(): global var var = 90 Here you're assigning to 'var', but this time you've declared that it's global, so you're assigning to the global variable called 'var'. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
I'm sorry, but I still don't understand how it applies to my problem. Thanks for everyone's patience. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On 10 August 2013 00:34, eschneide...@comcast.net wrote: What does global mean? Python has scopes for its variables. Most programming languages do. A scope is a restriction on where variables exist -- they exist only within the scope. This can be seen in this example: def function(): # A new scope is made when you enter a function variable = 100 function() print(variable) # Error, as variable doesn't exist outside of function's scope There are lots of different scopes in code. Every function has one, and there are some more too. One of the scopes is the global scope. This is the scope *outside* of all the functions and other scopes. Everything in the file is within this sope: # Make in global scope variable = 100 def function(): # Works because we're inside the global scope print(variable) # Prints 100 function() So a = b inside the function applies to the function's scope, but when accessing variables (such as print(variable)) it will look in all of the outer scopes too. If you want to write a = b inside the function and change the global scope, you need to say that a refers to the a in the global scope. You do that like this: def function(): # variable is in the global scope, not the functions' global variable variable = 100 function() # Prints 100 print(variable) Does that help you understand what global means? -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On Fri, 09 Aug 2013 16:34:48 -0700, eschneider92 wrote: What does global mean? Hi eschneider92, A few bits of advice: - You may like to actually sign your emails with a real name, or at least an alias that you want to be called, otherwise we'll just call you by your email address, and apart from sounding silly, many people don't like that. - You might also find that the tutor mailing list is a better match for your status as a complete beginner to Python. You can subscribe to it here: http://mail.python.org/mailman/listinfo/tutor - If you do, please take my advice and use individual emails, not daily digests. It is MUCH easier to carry on a back-and-forth conversation with individual emails. - Please try to quote enough of the message you are replying to to establish context, but without filling the email with page after page of irrelevant history. (Notice the line at the top of this message, starting with ? That's what you previously wrote.) If you need help configuring your email program to quote the previous message, just ask. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
Le mercredi 7 août 2013 10:17:21 UTC+2, eschne...@comcast.net a écrit : I'm trying to create an option for the program to repeat if the user types 'y' or 'yes', using true and false values, or otherwise end the program. If anyone could explain to me how to get this code working, I'd appreciate it. letters='abcdefghijklmn' batman=True def thingy(): print('type letter from a to n') typedletter=input() if typedletter in letters: print('yes') else: print('no') def repeat(): print('go again?') goagain=input() if goagain in ('y', 'yes'): print('ok') else: print('goodbye') batman=False while batman==True: thingy() repeat() print('this is the end') --- Your loop is not very well organized. It should be at the same time the loop and the condition tester. Compare your code with this and note the missing and unnecessary batman: def z(): ... letters = 'abc' ... c = input('letter: ') ... while c in letters: ... print('do stuff') ... c = input('letter: ') ... print('end, fin, Schluss') ... z() letter: a do stuff letter: b do stuff letter: b do stuff letter: c do stuff letter: n end, fin, Schluss z() letter: q end, fin, Schluss Variant It is common to use a infinite loop and to break it in order to end the job. def z2(): ... letters = 'abc' ... while True: ... c = input('letter: ') ... if c not in letters: ... print('end, fin, Schluss') ... break ... else: ... print('do stuff') ... z2() letter: a do stuff letter: b do stuff letter: a do stuff letter: q end, fin, Schluss jmf -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On Thu, Aug 8, 2013 at 7:20 AM, wxjmfa...@gmail.com wrote: def z2(): ... letters = 'abc' ... while True: ... c = input('letter: ') ... if c not in letters: ... print('end, fin, Schluss') ... break ... else: ... print('do stuff') Minor quibble: I don't like having a hard exit followed by an else. If the if branch will unconditionally quit the loop (with a break, here, but could also be a return, a thrown exception, etc etc), I would prefer to see the else removed and its code unindented one level. Maybe this is just personal preference, though, learned from assembly language programming where a block if looks something like this: ; if x == y: CMP x,y JNZ .else ; Code for x == y JMP .endif .else: ; Code for else .endif Putting an unconditional departure in the x == y branch makes the JMP .endif redundant. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On 8/8/2013 7:41 AM, Chris Angelico wrote: On Thu, Aug 8, 2013 at 7:20 AM, wxjmfa...@gmail.com wrote: def z2(): ... letters = 'abc' ... while True: ... c = input('letter: ') ... if c not in letters: ... print('end, fin, Schluss') ... break ... else: ... print('do stuff') Minor quibble: I don't like having a hard exit followed by an else. Whereas I tend to prefer to have the two alternatives cleanly marked as alternatives by both being indented the same. Many alternatives are not so trivial as the above. I remember reading one snippet in the CPython codebase where the 'else' was omitted and the if clause subdivided into about three paths. It took at least a minute to determine that all paths terminated in such a way that there really was an inplied else. How much easier it would have been to read the code if the author had explicitly types the 'else'. If the if branch will unconditionally quit the loop (with a break, here, but could also be a return, a thrown exception, etc etc), I would prefer to see the else removed and its code unindented one level. Maybe this is just personal preference, though, learned from assembly language programming where a block if looks something like this: ; if x == y: CMP x,y JNZ .else ; Code for x == y JMP .endif .else: ; Code for else .endif Putting an unconditional departure in the x == y branch makes the JMP .endif redundant. Python is not assembly ;-). 3.3 effectively ignores the extraneous 'else:'. Either way, if the condition is false, control jumps to the second print. For what little it matters, the bytecode is the same length. def f(): while True: if a: b = 1 break else: b = 2 dis(f) 2 0 SETUP_LOOP 25 (to 28) 3 3 LOAD_GLOBAL 0 (a) 6 POP_JUMP_IF_FALSE 19 4 9 LOAD_CONST 1 (1) 12 STORE_FAST 0 (b) 5 15 BREAK_LOOP 16 JUMP_ABSOLUTE3 719 LOAD_CONST 2 (2) 22 STORE_FAST 0 (b) 25 JUMP_ABSOLUTE3 28 LOAD_CONST 0 (None) 31 RETURN_VALUE def f(): while True: if a: b = 1 break b = 2 dis(f) 2 0 SETUP_LOOP 25 (to 28) 3 3 LOAD_GLOBAL 0 (a) 6 POP_JUMP_IF_FALSE 19 4 9 LOAD_CONST 1 (1) 12 STORE_FAST 0 (b) 5 15 BREAK_LOOP 16 JUMP_FORWARD 0 (to 19) 619 LOAD_CONST 2 (2) 22 STORE_FAST 0 (b) 25 JUMP_ABSOLUTE3 28 LOAD_CONST 0 (None) 31 RETURN_VALUE -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
beginner question (True False help)
I'm trying to create an option for the program to repeat if the user types 'y' or 'yes', using true and false values, or otherwise end the program. If anyone could explain to me how to get this code working, I'd appreciate it. letters='abcdefghijklmn' batman=True def thingy(): print('type letter from a to n') typedletter=input() if typedletter in letters: print('yes') else: print('no') def repeat(): print('go again?') goagain=input() if goagain in ('y', 'yes'): print('ok') else: print('goodbye') batman=False while batman==True: thingy() repeat() print('this is the end') -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On 7 August 2013 09:17, eschneide...@comcast.net wrote: I'm trying to create an option for the program to repeat if the user types 'y' or 'yes', using true and false values, or otherwise end the program. If anyone could explain to me how to get this code working, I'd appreciate it. Always tell people what in particular you don't understand (*ducks*) because it wasn't obvious what part of the problem you were unable to fulfil. letters='abcdefghijklmn' batman=True def thingy(): print('type letter from a to n') typedletter=input() if typedletter in letters: print('yes') else: print('no') def repeat(): print('go again?') goagain=input() if goagain in ('y', 'yes'): print('ok') else: print('goodbye') batman=False This doesn't do what you want it to. x = old thing def change_x(): x = new thing change_x() print(x) # Not changed! The solution is to put global x at the start of the function. while batman==True: thingy() repeat() print('this is the end') Note that this isn't actually a good way to do it. Imagine you had several hundred function -- would you really want to have an equivalent number of names floating around that you have to look after? The solution is to make the functions simply return values: x = old thing def return_thing(): x = new thing return new thing # You can do this in one line x = return_thing() # Get the value from the function and change x with it Does this make sense? -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
What I wanted to happen is when the user typed something other than 'y' or 'yes' after being asked 'go again?', the batman==False line would cause the program to stop asking anything and say 'this is the end'. Instead, what is happening is that the program just keeps going. I figured that after defining the function (thingy(), repeat()), that the while statement would repeat until the 'go again' user input was something other than 'y' or 'yes', and the batman==False part of the repeat() function would cause the 'while batman==True' part to become False and end. You probably answered my question and I'm too dumb to see it, but that's a slight elaboration on my problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
eschneide...@comcast.net wrote: What I wanted to happen is when the user typed something other than 'y' or 'yes' after being asked 'go again?', the batman==False line would cause the program to stop asking anything and say 'this is the end'. Instead, what is happening is that the program just keeps going. I figured that after defining the function (thingy(), repeat()), that the while statement would repeat until the 'go again' user input was something other than 'y' or 'yes', and the batman==False part of the repeat() function would cause the 'while batman==True' part to become False and end. You probably answered my question and I'm too dumb to see it, but that's a slight elaboration on my problem. When you assign a variable inside a function, it has no effect on a global variable with similar name. In order to make it change the global, you'd have needed the global declaration. Try this: var = 42 def myfunc(): var = 90 print before:, var myfunc() print after:, var Now, change the function, by adding a declaration: def myfunc(): global var var = 90 and the result will change. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question (True False help)
On 08/07/2013 01:17 AM, eschneide...@comcast.net wrote: I'm trying to create an option for the program to repeat if the user types 'y' or 'yes', using true and false values, or otherwise end the program. If anyone could explain to me how to get this code working, I'd appreciate it. letters='abcdefghijklmn' batman=True def thingy(): print('type letter from a to n') typedletter=input() if typedletter in letters: print('yes') else: print('no') def repeat(): print('go again?') goagain=input() if goagain in ('y', 'yes'): print('ok') else: print('goodbye') batman=False while batman==True: thingy() repeat() print('this is the end') You've already received answers to this, primarily pointing out that batman needs to be declared as global in your repeat() function. Global variables can be read from inside a function without declaring them as such, but if you need to change them, they MUST be declared as globals, otherwise it will merely create an independant local variable with the same name. A second possibility is to do away with batman in the repeat() function, and instead return True in the 'yes' clause and False in the else clause. Then in your while loop, change the repeat() line to: batman = repeat() A third version (which I would prefer) is to do away with batman altogether (maybe the Penguin got 'im??) ;-) Use the True/False version of repeat() and change the while loop to: while True: thingy() if not repeat(): break And finally unindent your final print() line. The way you have it will print 'The end' every time in your loop. Not what you want, I'm sure. -=- Larry -=- -- http://mail.python.org/mailman/listinfo/python-list
Beginner question
Why won't the 'goodbye' part of this code work right? it prints 'ok' no matter what is typed. Much thanks. def thing(): print('go again?') goagain=input() if goagain=='y' or 'yes': print('ok') elif goagain!='y' or 'yes': print('goodbye') sys.exit() thing() -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
eschneide...@comcast.net wrote: Why won't the 'goodbye' part of this code work right? it prints 'ok' no matter what is typed. Much thanks. def thing(): print('go again?') goagain=input() if goagain=='y' or 'yes': This expression doesn't do what you think. The comparison binds more tightly, so it first evaluates (goagain==y). The results of that are either True or False. Then it or's that logical value with 'yes'. The result is either True or it's 'yes'. 'yes' is considered truthy, so the if will always succeed. What you meant to use was: if goagain == y or goagain == yes: Alternatively, you could use if goagain in (y, yes): print('ok') elif goagain!='y' or 'yes': Same here. print('goodbye') sys.exit() thing() -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tue, Aug 6, 2013 at 10:35 PM, eschneide...@comcast.net wrote: Why won't the 'goodbye' part of this code work right? it prints 'ok' no matter what is typed. Much thanks. def thing(): print('go again?') goagain=input() if goagain=='y' or 'yes': print('ok') elif goagain!='y' or 'yes': print('goodbye') sys.exit() thing() When you use 'or' in this way, it's not doing what you think it does. It actually first computes goagain=='y' which is either True or False, and then evaluates the next part: True or 'yes' False or 'yes' Try out those two in interactive Python and see what they do. You probably want to compare in both halves of the test, or possibly use the 'in' operator: if goagain in ('y', 'yes'): Also, you don't need an 'elif' there; just use a plain else. Repeating the condition just introduces the chance of bugs - for instance, would you notice the error in this? if goagain=='y' or goagain=='yes': print('ok') elif goagain!='y' or goagain!='yes': print('goodbye') Using a plain 'else' guarantees that exactly one of the branches will be executed, rather than having the possibility that neither will, which isn't the intention here. Hope that helps! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tue, 06 Aug 2013 22:35:44 +0100, eschneide...@comcast.net wrote: Why won't the 'goodbye' part of this code work right? it prints 'ok' no matter what is typed. Much thanks. def thing(): print('go again?') goagain=input() if goagain=='y' or 'yes': This line doesn't do what you think it does :-) Typing that condition at an interactive prompt reveals something interesting: goagain = n goagain==y False goagain==y or yes 'yes' Oho. What's actually happening is that you've mistaken the operator precedence. == has a higher precedence than or, so your condition is equivalent to '(goagain==y) or yes'. Since it's left-hand argument is False, or returns its right-hand argument, which has the value 'yes', which in a boolean context is True. What you seem to want to do is to have your condition be true if goagain is either y or yes. Probably the easiest way of doing this and learning something new at the same time is to ask if goagain appears in a list (or rather a tuple) of strings: if goagain in ('y', 'yes'): print('ok') elif goagain not in ('y', 'yes'): print('goodbye') sys.exit() or better, if goagain in ('y', 'yes', 'ohdeargodyes', 'you get the idea'): print('ok') else: print('goodbye') sys.exit() -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On 2013-08-06 14:35, eschneide...@comcast.net wrote: Why won't the 'goodbye' part of this code work right? it prints 'ok' no matter what is typed. Much thanks. if statements do not fall through, because the first statement was matched, no other ones in the same chain will be evaluted. elif means else if, where else means if nothing previous matched. pgpmktmYIQJiC.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
Thanks that helped a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
Am 19.06.13 04:47, schrieb andrewblun...@gmail.com: However, for one part of the program I'd like to be able to create a 3D model based on the user input. The model would be very basic consisting of a number of lines and objects. We have 3D models of each component within our CAD system so it would be great if we could utilize those models. Have a look at vtk http://www.vtk.org/ Using VTK you can import CAD models and visualize them, combine to scenes and export. VTK has Python bindings. It is a real big library, but focused on polygonal models, i.e. it will happily import STL and OBJ, but not IGES and the like ith real curves. Then the question is how you'd want to export your model. VTK can export to VRML and X3D, but if you want to CREATE a real model by CSG of the exisiting parts, you would need a true CAD system. There is not much useful free stuff out there, you could try BRL-CAD or OpenCascade. The latter also has python bindings. http://www.pythonocc.org/ Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On Wednesday, June 19, 2013 12:50:52 AM UTC-2:30, Steven D'Aprano wrote: On Tue, 18 Jun 2013 19:47:34 -0700, andrewblundon wrote: However, for one part of the program I'd like to be able to create a 3D model based on the user input. The model would be very basic consisting of a number of lines and objects. We have 3D models of each component within our CAD system so it would be great if we could utilize those models. [...] Is this possible? Is Python the right language? Is Blender the sort of thing you are looking for? https://duckduckgo.com/html/?q=blender%20python -- Steven I've seen some information on Blender. Is it possible to have the entire program contained within a single exe (or exe and some other files) so that it can be passed around and used by others without having to install blender? -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On Wednesday, June 19, 2013 3:30:41 AM UTC-2:30, Christian Gollwitzer wrote: Am 19.06.13 04:47, schrieb andrewblun...@gmail.com: However, for one part of the program I'd like to be able to create a 3D model based on the user input. The model would be very basic consisting of a number of lines and objects. We have 3D models of each component within our CAD system so it would be great if we could utilize those models. Have a look at vtk http://www.vtk.org/ Using VTK you can import CAD models and visualize them, combine to scenes and export. VTK has Python bindings. It is a real big library, but focused on polygonal models, i.e. it will happily import STL and OBJ, but not IGES and the like ith real curves. Then the question is how you'd want to export your model. VTK can export to VRML and X3D, but if you want to CREATE a real model by CSG of the exisiting parts, you would need a true CAD system. There is not much useful free stuff out there, you could try BRL-CAD or OpenCascade. The latter also has python bindings. http://www.pythonocc.org/ Christian I don't need to create and export the model. I just want to be able to view it within the application I'm creating (without any other programs). -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On 19 June 2013 12:13, andrewblun...@gmail.com wrote: I've seen some information on Blender. Is it possible to have the entire program contained within a single exe (or exe and some other files) so that it can be passed around and used by others without having to install blender? I don't know if Blender would cause problems for that but it's not hard to install Blender generally; apparently there is a portable version that can be simply unzipped on the target computer. More generally, though, there are some legal issues relating to packaging standard MSVC-compiled Python with all of its dependencies in a single .exe file for Windows. The particular problem is the Microsoft C runtime library. py2exe has some information about this here: http://www.py2exe.org/index.cgi/Tutorial Generally Python is not designed with the intention that applications would be packaged into a standalone executable file although a number of projects exist to make that possible. Is it so hard for your users to install Python and Blender if you tell them which files to download and install? Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On 19 Jun 2013 12:56, Oscar Benjamin oscar.j.benja...@gmail.com wrote: On 19 June 2013 12:13, andrewblun...@gmail.com wrote: I've seen some information on Blender. Is it possible to have the entire program contained within a single exe (or exe and some other files) so that it can be passed around and used by others without having to install blender? I don't know if Blender would cause problems for that but it's not hard to install Blender generally; apparently there is a portable version that can be simply unzipped on the target computer. More generally, though, there are some legal issues relating to packaging standard MSVC-compiled Python with all of its dependencies in a single .exe file for Windows. The particular problem is the Microsoft C runtime library. py2exe has some information about this here: http://www.py2exe.org/index.cgi/Tutorial Generally Python is not designed with the intention that applications would be packaged into a standalone executable file although a number of projects exist to make that possible. Is it so hard for your users to install Python and Blender if you tell them which files to download and install? Oscar I don't know about the legality of it, but I've used blender in the past to make executable (exe) files with small games and distributed them without problems. The exe files were standalone (except for a few DLLs which I would place in the same folder) and it worked rather well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
As I've said, I'm a fairly novice. I've compiled simple VB programs previously into exe files for use but nothing with pyton and nothing of this complexity. This application could potentially be distributed to hundreds of people throughout the world as our company is worldwide. Asking these people to install other software is really not realistic. I'd like to have it all contained in one project. I stated one exe but it could be a number of files packaged into one distribution if that it's the right term. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
This sounds similar to what I might want. So you know of any online tutorials for this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On 19 June 2013 14:14, andrewblun...@gmail.com wrote: This sounds similar to what I might want. So you know of any online tutorials for this? It's hard to tell what you're referring to since you haven't included any quoted context in your message (like I have above). I'll assume you're referring to what Fábio said. I've already posted the link to the py2exe tutorial (I assume Fábio used py2exe since nothing else was specified). The legal issue I mentioned is precisely about the .dll files that Fábio referred to. The reason that py2exe (and similar projects) do not bundle these into the .exe is because it normally isn't legal to distribute these files. From the tutorial: ''' you need to check redist.txt within your Visual Studio installation to see whether you have the legal right to redistribute this DLL. If you do have these rights, then you have the option to bundle the C runtime DLL with you application. ''' Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On Wed, Jun 19, 2013 at 2:57 PM, Oscar Benjamin oscar.j.benja...@gmail.com wrote: On 19 June 2013 14:14, andrewblun...@gmail.com wrote: This sounds similar to what I might want. So you know of any online tutorials for this? It's hard to tell what you're referring to since you haven't included any quoted context in your message (like I have above). I'll assume you're referring to what Fábio said. I've already posted the link to the py2exe tutorial (I assume Fábio used py2exe since nothing else was specified). It's a blender game engine thing. (it may very well internally use py2exe). Here's a resource on how you do it: http://www.blender.org/forum/viewtopic.php?t=17838sid=5fa212f30833199dab4950e70d311490 Blender's game engine can probably be used to create a 3D model viewer, since the game engine is not specifically oriented towards games. It's more of a rudimentary interactive 3D framework, offering simple visual programming capabilities, and an awesome 3D editor, which is Blender itself. The greatest advantage to it is that it is couped with a 3D program. So you can create your physics bodies, entities, lights, etc., place them wherever you want and run the simulation. You can very likely import your CAD models into Blender using the many importers it has. It can import .3DS, .OBJ, etc. files with ease, provided you find (or write!) the plugins for them. -- Fábio Santos -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On Tuesday, June 18, 2013 9:47:34 PM UTC-5, andrew...@gmail.com wrote: I'm looking at developing a program for work that can be distributed to others (i.e. and exe file). The application would open various dialogue boxes and ask the user for input and eventually perform mathematical calculations on the input. Tkinter sucks for GUI (at least as it stands today) however it IS part of the stdlib and you can get going fairly quickly with it -- although Tkinter does not supply a native 3dcanvas widget so you'll have to use togl, which is very old and poorly written, but it works! ;-) Alternatively, WxPython is a full featured GUI library which has a glCanvas waiting for you. But like anything there is a trade-off -- will take a bit more time to understand Wx than Tkinter. From what I've read Python would have no trouble with this. However, for one part of the program I'd like to be able to create a 3D model based on the user input. The model would be very basic consisting of a number of lines and objects. [...] Are there any capabilities to import existing CAD geometry, arrange the components in particular 3D coordinates in space and then view the results in some sort of 3D viewer? Ideally the user would then be able to zoom in and orbit around looking at the model. Is this possible? Is Python the right language? Sounds like OpenGL is what you need. Others have mentioned Blender, however i would say that is a bad idea. Sure, all the zoom and orbit code is written for you but then your users are going to be overwhelmed by the Blender interface. Blender is overkill for what you want! Suggesting Blender for this problem is like suggesting you rent a semi-truck to ship a toaster one block. Adding lines and faces (or even geometric primitives) in OpenGL is so easy you'd have to be a complete moron not to understand it. There's a little bit of complication when handling concave faces (or faces containing holes), but nothing impossible about it. Importing data from outside programs is pure Python (easy stuff). PS: Be aware that you'll most likely want to use the latest version of Python 2.x if you go the OpenGL route. You need the following. Python2.x + (Tkinter Togl or WxPython) + OpenGL -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On Wednesday, June 19, 2013 11:47:36 AM UTC-2:30, Rick Johnson wrote: On Tuesday, June 18, 2013 9:47:34 PM UTC-5, andrew...@gmail.com wrote: I'm looking at developing a program for work that can be distributed to others (i.e. and exe file). The application would open various dialogue boxes and ask the user for input and eventually perform mathematical calculations on the input. Tkinter sucks for GUI (at least as it stands today) however it IS part of the stdlib and you can get going fairly quickly with it -- although Tkinter does not supply a native 3dcanvas widget so you'll have to use togl, which is very old and poorly written, but it works! ;-) Alternatively, WxPython is a full featured GUI library which has a glCanvas waiting for you. But like anything there is a trade-off -- will take a bit more time to understand Wx than Tkinter. From what I've read Python would have no trouble with this. However, for one part of the program I'd like to be able to create a 3D model based on the user input. The model would be very basic consisting of a number of lines and objects. [...] Are there any capabilities to import existing CAD geometry, arrange the components in particular 3D coordinates in space and then view the results in some sort of 3D viewer? Ideally the user would then be able to zoom in and orbit around looking at the model. Is this possible? Is Python the right language? Sounds like OpenGL is what you need. Others have mentioned Blender, however i would say that is a bad idea. Sure, all the zoom and orbit code is written for you but then your users are going to be overwhelmed by the Blender interface. Blender is overkill for what you want! Suggesting Blender for this problem is like suggesting you rent a semi-truck to ship a toaster one block. Adding lines and faces (or even geometric primitives) in OpenGL is so easy you'd have to be a complete moron not to understand it. There's a little bit of complication when handling concave faces (or faces containing holes), but nothing impossible about it. Importing data from outside programs is pure Python (easy stuff). PS: Be aware that you'll most likely want to use the latest version of Python 2.x if you go the OpenGL route. You need the following. Python2.x + (Tkinter Togl or WxPython) + OpenGL Excellent.. Thank you for your response. I'll start looking at OpenGL. I've looked into Blender previously for simply animations and having an average user use that for any sort of interface would indeed be overwhelming. I simply need a viewer that you could zoom and orbit. It would also be nice if you could import an existing 3D CAD geometry for viewing. I think I need to start downloading Python with a few of the libraries and start playing around. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Beginner Question: 3D Models
Hi there, Sorry for the complete beginner question but I thought the readers here might be able to provide me with some guidance. I've done some programming with Visual Basic and VBA plus a little PHP, CSS and HTML. I'm looking at developing a program for work that can be distributed to others (i.e. and exe file). The application would open various dialogue boxes and ask the user for input and eventually perform mathematical calculations on the input. From what I've read Python would have no trouble with this. However, for one part of the program I'd like to be able to create a 3D model based on the user input. The model would be very basic consisting of a number of lines and objects. We have 3D models of each component within our CAD system so it would be great if we could utilize those models. Most of the 3D graphic capabilities I've seen seem to center around either gaming or mathematical plotting. Are there any capabilities to import existing CAD geometry, arrange the components in particular 3D coordinates in space and then view the results in some sort of 3D viewer? Ideally the user would then be able to zoom in and orbit around looking at the model. Is this possible? Is Python the right language? Thanks AB -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On Tue, 18 Jun 2013 19:47:34 -0700, andrewblundon wrote: However, for one part of the program I'd like to be able to create a 3D model based on the user input. The model would be very basic consisting of a number of lines and objects. We have 3D models of each component within our CAD system so it would be great if we could utilize those models. [...] Is this possible? Is Python the right language? Is Blender the sort of thing you are looking for? https://duckduckgo.com/html/?q=blender%20python -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tue, Jun 4, 2013 at 9:53 PM, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Are there any benefits from using dict() instead of {}? Not for what you're doing, but you can use dict() with an iterable. Most of the time, use the literal. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
Sorry for the delay in replying. On Tue, 04 Jun 2013 15:51:38 +0300, Carlos Nepomuceno wrote: [1] Technically it's a type, not a function, but the difference makes no difference here. Can you explain me the difference of the type and function you've just mentioned? We were talking about dict(). In Python, type is another name for class. There is a built-in class called dict: py dict class 'dict' The way we create a new instance of a class is to call it, as if it were a function: py dict() {} just like you might call some other function: py len([]) 0 so sometimes it is convenient to be lazy and just refer to the type/class as a function. The general term for things which can be called in Python is callable, which includes functions, methods, and types. (Back in the ancient days of Python 1.x, dict *actually was a function*, just like len() or ord(), and the type/class system was radically different. But that's ancient history now.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
Thanks everyone! -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
That doesn't even works because input() is the same as eval(raw_input()). So you'll get a NameError exception. I think you know that. Perhaps you mean raw_input() instead of input(). In that case the answer is yes, it can be more 'efficient' because the if-then-else clause always breaks the while loop. I think you are looking for is a switch statement, which Python don't have. You can use the following structure to emulate a switch statement: def function1(): if raw_input() in option1: print('he tumbles over you') else: print('he stabs you') def function2(): if raw_input() in option2: print('you trip him up') else: print('he stabs you') def default(): print 'DEFAULT' switch = { option1: function1, option2: function2 } switch.get(randomizer, default)() Note that switch is a dictionary and you can use it without creating a variable, for example: { option1: function1, option2: function2 }.get(randomizer, default)() Date: Mon, 3 Jun 2013 20:39:28 -0700 Subject: Beginner question From: eschneide...@comcast.net To: python-list@python.org Is there a more efficient way of doing this? Any help is gratly appreciated. import random def partdeux(): print('''A man lunges at you with a knife! Do you DUCK or PARRY?''') option1=('duck') option2=('parry') optionsindex=[option1, option2] randomizer=random.choice(optionsindex) while randomizer==option1: if input() in option1: print('he tumbles over you') break else: print('he stabs you') break while randomizer==option2: if input() in option2: print('you trip him up') break else: print('he stabs you') break partdeux() -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
eschneide...@comcast.net writes: Is there a more efficient way of doing this? Any help is gratly appreciated. Efficiency in a short program isn't a big thing. You have some pretty weird things in there, there's no need make single element tuples out of your strings and then putting those in a list. Just put the strings in a tuple and go. Likewise there's really no point in having while loops where you exit on the first round now is there? Just use an if. BTW, did I get the logic correctly, the end result is random? If true then the logic can be simplified greatly, you can just discard the user input and print a random choice of your three result strings... -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Monday, June 3, 2013 11:46:03 PM UTC-7, Carlos Nepomuceno wrote: That doesn't even works because input() is the same as eval(raw_input()). So you'll get a NameError exception. I think you know that. Perhaps you mean raw_input() instead of input(). But the OP's code shows print() functions... which is not the habit of Python 2 programmers, even though it's legal code. And the OP says s/he's a beginning programmer... so why start learning Python 2 in 2013? Let me ask the OP, are you programming in Python 2 or Python 3? If the answer is indeed Python 3: raw_input() has been banished from Python 3, in favor of plain-old input(). -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tuesday, June 4, 2013 12:45:38 AM UTC-7, Anssi Saari wrote: BTW, did I get the logic correctly, the end result is random? You're right! I'm guessing that's not what the OP wants? -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
Date: Tue, 4 Jun 2013 00:53:04 -0700 Subject: Re: Beginner question From: john_lada...@sbcglobal.net To: python-list@python.org On Monday, June 3, 2013 11:46:03 PM UTC-7, Carlos Nepomuceno wrote: That doesn't even works because input() is the same as eval(raw_input()). So you'll get a NameError exception. I think you know that. Perhaps you mean raw_input() instead of input(). But the OP's code shows print() functions... which is not the habit of Python 2 programmers, even though it's legal code. And the OP says s/he's a beginning programmer... so why start learning Python 2 in 2013? Let me ask the OP, are you programming in Python 2 or Python 3? If the answer is indeed Python 3: raw_input() has been banished from Python 3, in favor of plain-old input(). Didn't know that. Thanks! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tue, Jun 4, 2013 at 5:57 PM, John Ladasky john_lada...@sbcglobal.net wrote: On Tuesday, June 4, 2013 12:45:38 AM UTC-7, Anssi Saari wrote: BTW, did I get the logic correctly, the end result is random? You're right! I'm guessing that's not what the OP wants? I'm guessing that's exactly what the OP wants. This is a fairly classic programming puzzle; on the surface it appears that you have some influence on the outcome, but ultimately you're playing rock-paper-scissors with the Random Number God. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On 06/03/2013 08:39 PM, eschneide...@comcast.net wrote: Is there a more efficient way of doing this? Any help is gratly appreciated. import random def partdeux(): print('''A man lunges at you with a knife! Do you DUCK or PARRY?''') option1=('duck') option2=('parry') optionsindex=[option1, option2] randomizer=random.choice(optionsindex) while randomizer==option1: if input() in option1: print('he tumbles over you') break else: print('he stabs you') break while randomizer==option2: if input() in option2: print('you trip him up') break else: print('he stabs you') break partdeux() Yes, you are making this much more complicated than necessary. It seems that what you are trying to do is input the option, then randomly print a success or failure message for that option. I suspect you didn't plan it, but it also prints the stab message for invalid entries. Like any program, it can be approached in many different ways. Here is one possibility. (Just the function def, add the import and function call as well. Also I am not adding any comments. See if you can follow the logic here yourself.) -- def partdeux(): print('A man lunges at you with a knife!') option = input('Do you DUCK or PARRY? ').lower() success = random.randint(0, 1) if success: if option == 'duck': print('He tumbles over you') return if option == 'parry': print('You trip him up') return print('He stabs you') BTW, ignore the response from Carlos. I can see from the print() functions in your original that you're using Python 3. His answer is only valid for Python 2. -=- Larry -=- -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
Chris Angelico wrote: On Tue, Jun 4, 2013 at 5:57 PM, John Ladasky john_lada...@sbcglobal.net wrote: On Tuesday, June 4, 2013 12:45:38 AM UTC-7, Anssi Saari wrote: BTW, did I get the logic correctly, the end result is random? You're right! I'm guessing that's not what the OP wants? I'm guessing that's exactly what the OP wants. This is a fairly classic programming puzzle; on the surface it appears that you have some influence on the outcome, but ultimately you're playing rock-paper-scissors with the Random Number God. As it is written, don't you always win if you hit enter? It may be the approved cheat code, though... OP: (some string) is not a tuple, it is the same as just some string therefore option1 = some string if input() in option1: print(yes) prints 'yes' if the user types in a substring of option1, and the shortest substring of any string is . For a single-item tuple the trailing comma is mandatory: (some string) # string 'some string' some string, # tuple ('some string',) (some string,) # tuple, parens added for clarity ('some string',) In general a tuple is consituted by the comma(s), not the parentheses: one, two ('one', 'two') -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
Started answering... now I'm asking! lol I've tried to use dict() to create a dictionary to use like the switch statement providing variable names instead of literals, such as: a='A' b='B' {a:0,b:1}#here the variables are resolved {'A': 0, 'B': 1} That's ok! But if I use dict() declaration: dict(a=0,b=1) {'a': 0, 'b': 1}#here variable names are taken as literals What's going on? Is there a way to make dict() to resolve the variables? -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
On 4 Jun 2013 12:28, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Started answering... now I'm asking! lol I've tried to use dict() to create a dictionary to use like the switch statement providing variable names instead of literals, such as: a='A' b='B' {a:0,b:1}#here the variables are resolved {'A': 0, 'B': 1} That's ok! But if I use dict() declaration: dict(a=0,b=1) {'a': 0, 'b': 1}#here variable names are taken as literals What's going on? Is there a way to make dict() to resolve the variables? Well yes. dict(**{a:0,b:1}) The dict() constructor makes a dictionary from keyword arguments. So you just have to feed it keyword arguments using **. And if you're in a bad day, dict(**locals()) -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
On 4 Jun 2013 12:28, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: [...] What's going on? Is there a way to make dict() to resolve the variables? Well yes. dict(**{a:0,b:1}) The dict() constructor makes a dictionary from keyword arguments. So you just have to feed it keyword arguments using **. And if you're in a bad day, dict(**locals()) That's exactly the same! dict(**{a:0,b:1})=={a:0,b:1} True Are there any benefits from using dict() instead of {}? -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
On 4 Jun 2013 12:57, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: On 4 Jun 2013 12:28, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: [...] What's going on? Is there a way to make dict() to resolve the variables? Well yes. dict(**{a:0,b:1}) The dict() constructor makes a dictionary from keyword arguments. So you just have to feed it keyword arguments using **. And if you're in a bad day, dict(**locals()) That's exactly the same! dict(**{a:0,b:1})=={a:0,b:1} True Are there any benefits from using dict() instead of {}? Other than being able to create a dict from a list of tuples, and copying a dict using dict(anotherdict.items()), not that I know of. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tue, 04 Jun 2013 14:53:29 +0300, Carlos Nepomuceno wrote: That's exactly the same! dict(**{a:0,b:1})=={a:0,b:1} True Of course it is. Isn't that what you wanted? It's also a waste of time, because you create a dict literal using {}, then unpack it into keyword arguments, then call dict() to create a new dict with the same content. Rather like doing this: n = int(str(42)) only even more expensive. Are there any benefits from using dict() instead of {}? Of course there are. {} can be used for creating dict literals, which means you are limited to key/values that you explicitly include. dict(), on the other hand, has a rich set of constructor APIs: py help(dict) Help on class dict in module builtins: class dict(object) | dict() - new empty dictionary | dict(mapping) - new dictionary initialized from a mapping object's | (key, value) pairs | dict(iterable) - new dictionary initialized as if via: | d = {} | for k, v in iterable: | d[k] = v | dict(**kwargs) - new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2) py dict(zip('abcd', range(4)), x=23, y=42, z=999) {'a': 0, 'c': 2, 'b': 1, 'd': 3, 'y': 42, 'x': 23, 'z': 999} Try doing that with {} alone! -- Steven -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
From: steve+comp.lang.pyt...@pearwood.info Subject: Re: Beginner question Date: Tue, 4 Jun 2013 12:25:27 + To: python-list@python.org On Tue, 04 Jun 2013 14:53:29 +0300, Carlos Nepomuceno wrote: That's exactly the same! dict(**{a:0,b:1})=={a:0,b:1} True Of course it is. Isn't that what you wanted? Indeed! But that form isn't economically viable as you noted. It's also a waste of time, because you create a dict literal using {}, then unpack it into keyword arguments, then call dict() to create a new dict with the same content. Rather like doing this: n = int(str(42)) only even more expensive. Are there any benefits from using dict() instead of {}? Of course there are. {} can be used for creating dict literals, which means you are limited to key/values that you explicitly include. dict(), on the other hand, has a rich set of constructor APIs: py help(dict) Help on class dict in module builtins: class dict(object) | dict() - new empty dictionary | dict(mapping) - new dictionary initialized from a mapping object's | (key, value) pairs | dict(iterable) - new dictionary initialized as if via: | d = {} | for k, v in iterable: | d[k] = v | dict(**kwargs) - new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2) py dict(zip('abcd', range(4)), x=23, y=42, z=999) {'a': 0, 'c': 2, 'b': 1, 'd': 3, 'y': 42, 'x': 23, 'z': 999} Awesome! Now I can do it just like that: dict([(chr(ord('a')+x),x) for x in range(2)]) {'a': 0, 'b': 1} Thanks a lot! ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tue, 04 Jun 2013 14:23:39 +0300, Carlos Nepomuceno wrote: Started answering... now I'm asking! lol I've tried to use dict() to create a dictionary to use like the switch statement providing variable names instead of literals, such as: a='A' b='B' {a:0,b:1}#here the variables are resolved {'A': 0, 'B': 1} That's ok! But if I use dict() declaration: dict(a=0,b=1) {'a': 0, 'b': 1}#here variable names are taken as literals What's going on? Is there a way to make dict() to resolve the variables? This is by design. You're calling a function, dict(), and like all functions, code like: func(name=value) provides a *keyword argument*, where the argument is called name and the argument's value is as given. dict is no different from any other function, it has no superpowers, keyword arguments are still keyword arguments. In this case, there is no simple way to use the dict() function[1] the way you want. You could build up a string and then call eval(): s = dict(%s=0, %s=1) % (a, b) d = eval(s) but that's slow and inconvenient and dangerous if your data is untrusted. So in this specific case, you should stick to the {} method. [1] Technically it's a type, not a function, but the difference makes no difference here. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
Awesome! Now I can do it just like that: dict([(chr(ord('a')+x),x) for x in range(2)]) {'a': 0, 'b': 1} Thanks a lot! ;) Or dict((c, i) for (i, c) in enumerate('ab')) But at this point you could just use a dict comprehension. {c: i for i, c in enumerate('ab')} -- http://mail.python.org/mailman/listinfo/python-list
RE: Beginner question
From: steve+comp.lang.pyt...@pearwood.info Subject: Re: Beginner question Date: Tue, 4 Jun 2013 12:35:59 + To: python-list@python.org On Tue, 04 Jun 2013 14:23:39 +0300, Carlos Nepomuceno wrote: Started answering... now I'm asking! lol I've tried to use dict() to create a dictionary to use like the switch statement providing variable names instead of literals, such as: a='A' b='B' {a:0,b:1}#here the variables are resolved {'A': 0, 'B': 1} That's ok! But if I use dict() declaration: dict(a=0,b=1) {'a': 0, 'b': 1}#here variable names are taken as literals What's going on? Is there a way to make dict() to resolve the variables? This is by design. You're calling a function, dict(), and like all functions, code like: func(name=value) provides a *keyword argument*, where the argument is called name and the argument's value is as given. dict is no different from any other function, it has no superpowers, keyword arguments are still keyword arguments. In this case, there is no simple way to use the dict() function[1] the way you want. You could build up a string and then call eval(): s = dict(%s=0, %s=1) % (a, b) d = eval(s) but that's slow and inconvenient and dangerous if your data is untrusted. So in this specific case, you should stick to the {} method. [1] Technically it's a type, not a function, but the difference makes no difference here. -- Steven It's superclear now! You're an excelent teacher! Can you explain me the difference of the type and function you've just mentioned? -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
In article ikkdnevcx7wymjdmnz2dnuvz_ssdn...@giganews.com, Larry Hudson org...@yahoo.com wrote: def partdeux(): print('A man lunges at you with a knife!') option = input('Do you DUCK or PARRY? ').lower() success = random.randint(0, 1) if success: if option == 'duck': print('He tumbles over you') return if option == 'parry': print('You trip him up') return print('He stabs you') I'm going to suggest another possible way to organize this. I'm not claiming it's necessarily better, but as this is a learning exercise, it's worth exploring. Get rid of all the conditional logic and make this purely table-driven: responses = {(0, 'duck'): He tumbles over you, (0, 'parry'): You trip him up, (1, 'duck'): He stabs you, (1, 'parry'): He stabs you, } and then def partdeux(): print('A man lunges at you with a knife!') option = input('Do you DUCK or PARRY? ').lower() success = random.randint(0, 1) print responses[(success, option)] Consider what happens when the game evolves to the point where you have four options (DUCK, PARRY, RETREAT, FEINT), multiple levels of success, and modifiers for which hand you and/or your opponent are holding your weapons in? Trying to cover all that with nested logic will quickly drive you insane. -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On Tuesday, June 4, 2013 11:21:53 AM UTC-4, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me with '1' But, if the header is: h02: ('contig-100_1') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max -- http://mail.python.org/mailman/listinfo/python-list
lstrip problem - beginner question
Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On Tuesday, June 4, 2013 11:21:53 AM UTC-4, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max edit: h02: ('contig-100_1') -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On Tuesday, June 4, 2013 11:21:53 AM UTC-4, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max edit: h02= ('contig-100_1') -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On Tuesday, June 4, 2013 11:21:53 AM UTC-4, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max edit: h02= ('contig-100_1') -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On 4 Jun 2013 16:34, mstagliamonte madmax...@yahoo.it wrote: On Tuesday, June 4, 2013 11:21:53 AM UTC-4, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max edit: h02: ('contig-100_1') You don't have to use ('..') to declare a string. Just 'your string' will do. You can use str.split to split your string by a character. (Not tested) string_on_left, numbers = 'contig-100_01'.split('-') left_number, right_number = numbers.split('_') left_number, right_number = int(left_number), int(right_number) Of course, you will want to replace the variable names. If you have more advanced parsing needs, you will want to look at regular expressions or blobs. -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On 04/06/2013 16:21, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? The methods 'lstrip', 'rstrip' and 'strip' don't strip a string, they strip characters. You should think of the argument as a set of characters to be removed. This code: h01.lstrip('scaffold_') will return the result of stripping the characters '', '_', 'a', 'c', 'd', 'f', 'l', 'o' and 's' from the left-hand end of h01. A simpler example: 'xyyxyabc'.lstrip('xy') 'abc' It strips the characters 'x' and 'y' from the string, not the string 'xy' as such. They are that way because they have been in Python for a long time, long before sets and such like were added to the language. -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On Tuesday, June 4, 2013 11:41:43 AM UTC-4, Fábio Santos wrote: On 4 Jun 2013 16:34, mstagliamonte madm...@yahoo.it wrote: On Tuesday, June 4, 2013 11:21:53 AM UTC-4, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max edit: h02: ('contig-100_1') You don't have to use ('..') to declare a string. Just 'your string' will do. You can use str.split to split your string by a character. (Not tested) string_on_left, numbers = 'contig-100_01'.split('-') left_number, right_number = numbers.split('_') left_number, right_number = int(left_number), int(right_number) Of course, you will want to replace the variable names. If you have more advanced parsing needs, you will want to look at regular expressions or blobs. Thanks, I will try it straight away. Still, I don't understand why the original command is returning me with nothing !? Have you got any idea? I am trying to understand a bit the 'nuts and bolts' of what I am doing and this result does not make any sense to me Regards Max -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? abba.lstrip(ab) does not remove the prefix ab from the string abba. Instead it removes chars from the beginning until it encounters one that is not in ab. So t = s.lstrip(chars_to_be_removed) is roughly equivalent to t = s while len(t) 0 and t[0] in chars_to_be_removed: t = t[1:] If you want to remove a prefix use s = abba prefix = ab if s.startswith(prefix): s = s[len(prefix):] -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On Tuesday, June 4, 2013 11:48:55 AM UTC-4, MRAB wrote: On 04/06/2013 16:21, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? The methods 'lstrip', 'rstrip' and 'strip' don't strip a string, they strip characters. You should think of the argument as a set of characters to be removed. This code: h01.lstrip('scaffold_') will return the result of stripping the characters '', '_', 'a', 'c', 'd', 'f', 'l', 'o' and 's' from the left-hand end of h01. A simpler example: 'xyyxyabc'.lstrip('xy') 'abc' It strips the characters 'x' and 'y' from the string, not the string 'xy' as such. They are that way because they have been in Python for a long time, long before sets and such like were added to the language. Hey, Great! Now I understand! So, basically, it is also stripping the numbers after the '_' !! Thank you, I know a bit more now! Have a nice day everyone :) Max -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
In 1829efca-935d-4049-ba61-7138015a2...@googlegroups.com mstagliamonte madmax...@yahoo.it writes: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? It's happening because the argument you pass to lstrip() isn't an exact string to be removed; it's a set of individual characters, all of which will be stripped out. So, when you make this call: h02.lstrip('contig-100_') You're telling python to remove all of the characters in 'contig-100_' from the base string, which leaves nothing remaining. The reason it worked on your first example was that the character '1' didn't occur in your sample header string 'scaffold_'. If the underscore character is always the separating point in your headers, a better way might be to use the split() method instead of lstrip(). -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On 04/06/2013 16:49, mstagliamonte wrote: [strip the double line spaced nonsense] Can you please check your email settings. It's bad enough being plagued with double line spaced mail from google, having it come from yahoo is just adding insult to injury, thanks :) -- Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green. Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
Thanks to everyone! I didn't expect so many replies in such a short time! Regards, Max -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On 06/04/2013 07:53 AM, Carlos Nepomuceno wrote: On 4 Jun 2013 12:28, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: [...] What's going on? Is there a way to make dict() to resolve the variables? Well yes. dict(**{a:0,b:1}) The dict() constructor makes a dictionary from keyword arguments. So you just have to feed it keyword arguments using **. And if you're in a bad day, dict(**locals()) That's exactly the same! dict(**{a:0,b:1})=={a:0,b:1} True Are there any benefits from using dict() instead of {}? Other than what Steven already mentioned, a big advantage is that it's easier to make a dict if you have a lot of keys that are valid identifiers, and it's more readable, to boot: dict(red=1, blue=2, orange=3, violet=4, crimson=5, ...) VS. {'red':1, 'blue':2, 'orange':3, 'violet':4, 'crimson':5, ...} -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Although the most acute judges of the witches and even the witches themselves, were convinced of the guilt of witchery, the guilt nevertheless was non-existent. It is thus with all guilt. Friedrich Nietzsche -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On 4 June 2013 04:39, eschneide...@comcast.net wrote: Is there a more efficient way of doing this? Any help is gratly appreciated. import random def partdeux(): print('''A man lunges at you with a knife! Do you DUCK or PARRY?''') option1=('duck') option2=('parry') optionsindex=[option1, option2] randomizer=random.choice(optionsindex) while randomizer==option1: if input() in option1: print('he tumbles over you') break else: print('he stabs you') break while randomizer==option2: if input() in option2: print('you trip him up') break else: print('he stabs you') break partdeux() I'm going to look directly at the code for my comment, here, and explain what's up. I imagine you were given this code to fix up, I'll lead you through the steps. import random You only use random.choice, never anything else, so in this case I'd be tempted to do: from random import choice This is *entirely optional*: I tend to do quite a lot of from module import object but others prefer to be more explicit about where things come from; your choice. def partdeux(): Other than the atrocious name this is as simple as it gets to define a function - you should like that it's a function, though. print('''A man lunges at you with a knife! Do you DUCK or PARRY?''') This is iffy! Triple-quotes? Personally this is a really bad time to use them - they break indentation and whatnot. I'd write: print('A man lunges at you with a knife!') print('Do you DUCK or PARRY?') This, in my opinion, is much nicer. But we haven't simplified much yet. option1=('duck') option2=('parry') optionsindex=[option1, option2] There are two things off about this. Firstly, no-one should be so addicted to brackets to use them here, and you should space variables. option1 = 'duck' option2 = 'parry' BUT this is not needed anyway. The next line puts both of these in a variable. You can add them straight in: optionsindex = ['duck', 'parry'] There are some things wrong though: 1) *Never* lie. This is not an index of any sort, unless you're referring to one of these: [http://shop.pageprotectors.com/images/Index-Ring-Binder-2-Rings-Recipe-3x5-Card.jpg] This should be named options or, better, valid_responses. 2) You write Do you DUCK or PARRY?. None of this suggests uppercase. We shall deal with this later. Thus: valid_responses = ['duck', 'parry'] randomizer=random.choice(optionsindex) while randomizer==option1: ... while randomizer==option2: This is odd! What do you think this does? This says that you choose an option, duck or parry. If it is duck, then do A. If it is parry, then do B. But why would a computer choose options like that? Surely it's better to do: (I'm properly spacing it as I go along, by the way) randomizer = random.choice([True, False]) while randomizer: ... while not randomizer: Oh, that's odd! As randomizer never changes after you set it, you can be sure that the while randomizer is equivalent to while True or while False. This means it will loop forever without a break. Looking at the breaks it is clear that *all paths lead to a break*. A while *LOOP* should only ever be used to *LOOP*. This makes the looping redundant. Thus remove the breaks and use: randomizer = random.choice([True, False]) if randomizer: ... if not randomizer: which can be better written: if random.choice([True, False]): ... else: (BUT you may have to write if choice([True, False]): if you've followed all of my advice) if input() in option1: option1 no longer exists, so this is now written: if input() in valid_responses[0]: BUT why in? You want to check whether that *equals* the response, not whether that is *in* the response: if input() == valid_responses[0]: else: print('he stabs you') Why else? This means that if you wrote Seppuku *he'd* stab you. You want to check that you actually wrote the right thing! elif input() == valid_responses[1]: print('he stabs you') This does not work, but we'll fix it later. if input() in option2: For the same reason, change this to: if input() == valid_responses[1]: else: print('he stabs you') and this to: elif input() == valid_responses[0]: print('he stabs you') The rest is better. That leaves you with a much nicer looking function: ### START CODE ### from random import choice def partdeux(): print(A man lunges at you with a knife!) print(Do you DUCK or PARRY?) valid_responses = [duck, parry] if choice([True, False]): if input() == valid_responses[0]: print('he tumbles over you') elif input() == valid_responses[0]: print('he stabs you') else:
Re: lstrip problem - beginner question
On 06/04/2013 12:01 PM, Mark Lawrence wrote: On 04/06/2013 16:49, mstagliamonte wrote: [strip the double line spaced nonsense] Can you please check your email settings. It's bad enough being plagued with double line spaced mail from google, having it come from yahoo is just adding insult to injury, thanks :) Mark: The OP is posting from googlegroups, just using a yahoo return address. So you just have one buggy provider to hate, not two. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: madmax...@yahoo.it: If you must use googlegroups, at least fix the double-posting and double-spacing bugs it has. Start by reading: http://wiki.python.org/moin/GoogleGroupsPython -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
On 06/04/2013 08:21 AM, mstagliamonte wrote: Hi everyone, I am a beginner in python and trying to find my way through... :) I am writing a script to get numbers from the headers of a text file. If the header is something like: h01 = ('scaffold_1') I just use: h01.lstrip('scaffold_') and this returns me '1' But, if the header is: h02: ('contig-100_0') if I use: h02.lstrip('contig-100_') this returns me with: '' ...basically nothing. What surprises me is that if I do in this other way: h02b = h02.lstrip('contig-100') I get h02b = ('_1') and subsequently: h02b.lstrip('_') returns me with: '1' which is what I wanted! Why is this happening? What am I missing? Thanks for your help and attention Max The lstrip() function is the wrong one to use here. The command help(str.lstrip) gives: lstrip(...) S.lstrip([chars]) - str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. IOW, it does NOT strip the given string, but all the characters in the given string. So in your second example it (correctly) removes everything and gives you an empty string as the result. One possible alternative is to use slicing: h02 = 'contig-100_0' h03 = 'contig-100_' result = h02[len(h03):] Or some similar variation, possibly adding a startswith() function for some simple error checking. Of course, other approaches are possible as well, -=- Larry -=- -- http://mail.python.org/mailman/listinfo/python-list
Beginner question
Is there a more efficient way of doing this? Any help is gratly appreciated. import random def partdeux(): print('''A man lunges at you with a knife! Do you DUCK or PARRY?''') option1=('duck') option2=('parry') optionsindex=[option1, option2] randomizer=random.choice(optionsindex) while randomizer==option1: if input() in option1: print('he tumbles over you') break else: print('he stabs you') break while randomizer==option2: if input() in option2: print('you trip him up') break else: print('he stabs you') break partdeux() -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning new APIs/classes (beginner question)
On Apr 7, 1:52 am, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: Sounds like this library is documented the same way most third party libraries are: as an afterthought, by somebody who is so familiar with the software that he cannot imagine why anyone might actually need documentation. I feel your pain. Thanks Steven, I suspected this might be the case, but wasn't sure if I was missing something obvious. Maybe I'll start on a different project using better-documented or just the build-in libraries. Many thanks, Martin. -- http://mail.python.org/mailman/listinfo/python-list
Learning new APIs/classes (beginner question)
In a nutshell: My question is: how do experienced coders learn about external/third-party classes/APIs? I'm teaching myself Python through a combination of Hetland's 'Beginning Python', various online tutorials and some past experience coding ASP/VBScript. To start to learn Python I've set myself the task of coding a viewer/editor for Google Contacts and Google Calendar, mainly because I've been experiencing some synchronisation anomalies lately. This has so far entailed getting into Google's Contacts API. Although they give some examples, my searches haven't been able to pull up anything approaching comprehensive documentation on each class/method. Can anyone experienced advise on how they would usually go about learning to use third party APIs/classes like these? With thanks, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning new APIs/classes (beginner question)
On 4/6/2012 1:41 PM Martin Jones said... In a nutshell: My question is: how do experienced coders learn about external/third-party classes/APIs? I'm teaching myself Python through a combination of Hetland's 'Beginning Python', various online tutorials and some past experience coding ASP/VBScript. One resource for learning at least the bulk of python's interal library is http://effbot/librarybook -- of course, not much help for third party libraries... Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning new APIs/classes (beginner question)
On Fri, 06 Apr 2012 13:41:23 -0700, Martin Jones wrote: In a nutshell: My question is: how do experienced coders learn about external/third-party classes/APIs? Does it have a tutorial? Do it. Does it have a manual, a wiki, FAQs, or other documentation? Read them. If all else fails, what does help(external_library) say? Are there examples you can follow? Do so. Does it have a mailing list to ask for help? Subscribe to it. Google for examples and sample code. If all else fails, read the source code if it is available. Otherwise find another library. If you can't do that, then you're stuck with learning by trial and error. Which is to say, mostly by error, which is a trial. I'm teaching myself Python through a combination of Hetland's 'Beginning Python', various online tutorials and some past experience coding ASP/VBScript. To start to learn Python I've set myself the task of coding a viewer/editor for Google Contacts and Google Calendar, mainly because I've been experiencing some synchronisation anomalies lately. This has so far entailed getting into Google's Contacts API. Although they give some examples, my searches haven't been able to pull up anything approaching comprehensive documentation on each class/method. Sounds like this library is documented the same way most third party libraries are: as an afterthought, by somebody who is so familiar with the software that he cannot imagine why anyone might actually need documentation. I feel your pain. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: redis beginner question
Why do you want to stop redis after your program terminates? Generally, you just start redis up when the system boots and leave it running. Hi, OK, so it's more like MySQL or PostgeSQL, i.e. leave the server running in the background. I wanted to use it like SQLite, i.e. let it run only when I need it. Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: redis beginner question
In article mailman.2766.1321449007.27778.python-l...@python.org, Jabba Laci jabba.l...@gmail.com wrote: Why do you want to stop redis after your program terminates? Generally, you just start redis up when the system boots and leave it running. Hi, OK, so it's more like MySQL or PostgeSQL, i.e. leave the server running in the background. That's how I would treat it. -- http://mail.python.org/mailman/listinfo/python-list