Re: beginner question-very basic

2019-08-11 Thread Wildman via Python-list
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


Re: Beginner Question

2016-06-02 Thread sohcahtoa82
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
>  wrote:
> > On Thursday 02 June 2016 14:21, Igor Korot wrote:
> >
> >> Hi, guys,
> >>
> >> On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp  wrote:
> >>> On Wed, Jun 1, 2016 at 7:55 PM, 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
> 
>  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

2016-06-02 Thread Igor Korot
Steven,

On Thu, Jun 2, 2016 at 1:20 AM, Steven D'Aprano
 wrote:
> On Thursday 02 June 2016 14:21, Igor Korot wrote:
>
>> Hi, guys,
>>
>> On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp  wrote:
>>> On Wed, Jun 1, 2016 at 7:55 PM, 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

 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

2016-06-02 Thread Marcin Rak
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

2016-06-01 Thread Steven D'Aprano
On Thursday 02 June 2016 14:21, Igor Korot wrote:

> Hi, guys,
> 
> On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp  wrote:
>> On Wed, Jun 1, 2016 at 7:55 PM, 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
>>>
>>> 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

2016-06-01 Thread Igor Korot
Hi, guys,

On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp  wrote:
> On Wed, Jun 1, 2016 at 7:55 PM, 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
>>
>> 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

2016-06-01 Thread Steven D'Aprano
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

2016-06-01 Thread boB Stepp
On Wed, Jun 1, 2016 at 7:55 PM, 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
>
> 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


Re: Beginner question - class definition error

2015-01-28 Thread Cousin Stanley

> 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 
> 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

2015-01-28 Thread David Aldrich
> 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 - class definition error

2015-01-28 Thread MRAB

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 
[INFO  ] [Factory ] 157 symbols loaded
[DEBUG  ] [Cache   ] register  with limit=None, 
timeout=Nones
[DEBUG  ] [Cache   ] register  with limit=None, 
timeout=60s
[DEBUG  ] [Cache   ] register  with limit=None, 
timeout=Nones
[INFO  ] [Image   ] Providers: img_tex, img_dds, img_pygame, 
img_gif (img_pil ignored)
[DEBUG  ] [Cache   ] register  with limit=1000, 
timeout=60s
[DEBUG  ] [Cache   ] register  with limit=1000, 
timeout=3600s
[INFO  ] [Text] Provider: pygame
  Traceback (most recent call last):
File "MinimalApplication.py", line 7, in 
  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


Re: beginner question (True False help)

2013-08-09 Thread Steven D'Aprano
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)

2013-08-09 Thread Joshua Landau
On 10 August 2013 00:34,   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)

2013-08-09 Thread eschneider92
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)

2013-08-09 Thread MRAB

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)

2013-08-09 Thread eschneider92
(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)

2013-08-09 Thread eschneider92
(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)

2013-08-09 Thread eschneider92
What does global mean?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner question (True False help)

2013-08-09 Thread Joshua Landau
On 10 August 2013 00:14,   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)

2013-08-09 Thread eschneider92
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)

2013-08-09 Thread eschneider92
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)

2013-08-09 Thread Joshua Landau
On 9 August 2013 23:27,   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)

2013-08-09 Thread eschneider92
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)

2013-08-09 Thread eschneider92
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)

2013-08-09 Thread wxjmfauth
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,   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
> 
> 
> 
>7 >>   19 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)
> 
> 
> 
>6 >>   19 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)

2013-08-08 Thread Terry Reedy

On 8/8/2013 7:41 AM, Chris Angelico wrote:

On Thu, Aug 8, 2013 at 7:20 AM,   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

  7 >>   19 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)

  6 >>   19 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


Re: beginner question (True False help)

2013-08-08 Thread Chris Angelico
On Thu, Aug 8, 2013 at 7:20 AM,   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)

2013-08-07 Thread wxjmfauth
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)

2013-08-07 Thread Larry Hudson

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


Re: beginner question (True False help)

2013-08-07 Thread Dave Angel
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)

2013-08-07 Thread eschneider92
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)

2013-08-07 Thread Joshua Landau
On 7 August 2013 09:17,   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

2013-08-06 Thread eschneider92
Thanks that helped a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question

2013-08-06 Thread Chris Down
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

2013-08-06 Thread Rhodri James

On Tue, 06 Aug 2013 22:35:44 +0100,  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

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 10:35 PM,   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

2013-08-06 Thread Dave Angel
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: 3D Models

2013-06-19 Thread andrewblundon
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


Re: Beginner Question: 3D Models

2013-06-19 Thread Rick Johnson
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

2013-06-19 Thread Fábio Santos
On Wed, Jun 19, 2013 at 2:57 PM, Oscar Benjamin
 wrote:
> On 19 June 2013 14:14,   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=17838&sid=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

2013-06-19 Thread Oscar Benjamin
On 19 June 2013 14:14,   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

2013-06-19 Thread andrewblundon
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

2013-06-19 Thread andrewblundon
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

2013-06-19 Thread Fábio Santos
On 19 Jun 2013 12:56, "Oscar Benjamin"  wrote:
>
> On 19 June 2013 12:13,   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

2013-06-19 Thread Oscar Benjamin
On 19 June 2013 12:13,   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

2013-06-19 Thread andrewblundon
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

2013-06-19 Thread andrewblundon
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

2013-06-18 Thread Christian Gollwitzer

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

2013-06-18 Thread Steven D'Aprano
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

2013-06-12 Thread Chris Angelico
On Tue, Jun 4, 2013 at 9:53 PM, Carlos Nepomuceno
 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

2013-06-06 Thread Steven D'Aprano
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


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

2013-06-05 Thread eschneider92
Thanks everyone!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question

2013-06-04 Thread Joshua Landau
On 4 June 2013 04:39,   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
 import " 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 i

Re: Beginner question

2013-06-04 Thread Mitya Sirenef

On 06/04/2013 07:53 AM, Carlos Nepomuceno wrote:

>On 4 Jun 2013 12:28,  "Carlos Nepomuceno"  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

2013-06-04 Thread Roy Smith
In article ,
 Larry Hudson  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: Beginner question

2013-06-04 Thread Carlos Nepomuceno


> 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

2013-06-04 Thread Fábio Santos
>
> 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

2013-06-04 Thread Steven D'Aprano
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

2013-06-04 Thread Carlos Nepomuceno


> 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

2013-06-04 Thread Steven D'Aprano
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

2013-06-04 Thread Fábio Santos
On 4 Jun 2013 12:57, "Carlos Nepomuceno" 
wrote:
>
> >On 4 Jun 2013 12:28, "Carlos Nepomuceno" 
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

2013-06-04 Thread Carlos Nepomuceno
>On 4 Jun 2013 12:28, "Carlos Nepomuceno"  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

2013-06-04 Thread Fábio Santos
On 4 Jun 2013 12:28, "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?

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

2013-06-04 Thread Carlos Nepomuceno
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

2013-06-04 Thread Peter Otten
Chris Angelico wrote:

> On Tue, Jun 4, 2013 at 5:57 PM, John Ladasky 
> 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

2013-06-04 Thread Larry Hudson

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

2013-06-04 Thread Chris Angelico
On Tue, Jun 4, 2013 at 5:57 PM, John Ladasky  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

2013-06-04 Thread Carlos Nepomuceno


> 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

2013-06-04 Thread John Ladasky
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

2013-06-04 Thread John Ladasky
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

2013-06-04 Thread Anssi Saari
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

2013-06-03 Thread Carlos Nepomuceno
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) ConfigParser nuances

2011-05-02 Thread Unknown Moss
On May 2, 3:25 pm, Chris Rebert  wrote:
> On Mon, May 2, 2011 at 3:04 PM, Unknown Moss  wrote:
> > Hi -Beginnerquestionhere. I'm working with ConfigParser. I'd like
> > to take a multiline variable and convert it directly to an array.
> > Seems like a common  problem, but I don't see how I can do it without
> > doing a little parsing in my own code. Here's what I'm doing ...
>
>  import ConfigParser
>  import io
>  sample = """
> > ... [Example]
> > ... fruit = apple
> > ...     orange
> > ...     pear
> > ... """
>  config = ConfigParser.RawConfigParser()
>  config.readfp(io.BytesIO(sample))
>  config.get("Example", "fruit")
> > 'apple\norange\npear'
>  temp = config.get("Example", "fruit")
>  temp.split()
> > ['apple', 'orange', 'pear']
>
> > I'm thinking there's a way to avoid this intermediate temp.split()
> > step. Is there not a way to move a multiline value straight into an
> > array using ConfigParser?
>
> Nope, there is not. I think some might instead use several numbered
> options to similar effect:
>
> # config file
> [Example]
> fruit1: apple
> fruit2: orange
> fruit3: pear
>
> # Python
> from itertools import count
> fruits = []
> names = ("fruit" + str(i) for i in count(1))
> for name in names:
>     if not config.has_option("Example", name):
>         break
>     fruits.append(config.get("Example", name))
>
> Cheers,
> Chris
> --http://rebertia.com

Ok, thanks Chris. Maybe I'm getting too lazy in my old age.  :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (beginner question) ConfigParser nuances

2011-05-02 Thread Chris Rebert
On Mon, May 2, 2011 at 3:04 PM, Unknown Moss  wrote:
> Hi - Beginner question here. I'm working with ConfigParser. I'd like
> to take a multiline variable and convert it directly to an array.
> Seems like a common  problem, but I don't see how I can do it without
> doing a little parsing in my own code. Here's what I'm doing ...
>
 import ConfigParser
 import io
 sample = """
> ... [Example]
> ... fruit = apple
> ...     orange
> ...     pear
> ... """
 config = ConfigParser.RawConfigParser()
 config.readfp(io.BytesIO(sample))
 config.get("Example", "fruit")
> 'apple\norange\npear'
 temp = config.get("Example", "fruit")
 temp.split()
> ['apple', 'orange', 'pear']
>
> I'm thinking there's a way to avoid this intermediate temp.split()
> step. Is there not a way to move a multiline value straight into an
> array using ConfigParser?

Nope, there is not. I think some might instead use several numbered
options to similar effect:

# config file
[Example]
fruit1: apple
fruit2: orange
fruit3: pear

# Python
from itertools import count
fruits = []
names = ("fruit" + str(i) for i in count(1))
for name in names:
if not config.has_option("Example", name):
break
fruits.append(config.get("Example", name))


Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Beginner question] Error when converting raster to ASCII

2010-11-15 Thread Benjamin Kaplan
On Monday, November 15, 2010, Becky Kern  wrote:
> Hi again users,
>
> This is in response to my post from 11/14/2010 (see below)
>
>> Hi users,
>> I'm using Python 2.5 (in concert with ArcGIS 9.3) to convert a raster to
>> an ASCII file. I used the code (listed below) several weeks ago to
>> successfully do the conversion, but when I tried to replicate it a few
>> days ago, I got an error message.
>> import arcgisscripting
>> gp = arcgisscripting.create(9.3)
>> InRaster = "C:/data/raster1"
>> OutAsciiFile = "C:/data/raster2ascii.asc"
>> gp.RasterToASCII_conversion(InRaster, OutAsciiFile)
>> The error message:
>> arcgisscripting.ExecuteError: Failed to execute. Parameters are not
>> valid. raster1 does not exist.
>> My file path has not changed so I don't understand why Python can no
>> longer recognize my raster file. Any ideas?
>>
>
> MRAB responded:
> Just to make sure, does os.path.isfile(InRaster) return True?
>
> When I tried os.path.isfile(InRaster), I received the following error message:
> "NameError: name 'os' is not defined"

you need to import os.path

>
> Does this shed any light on why my raster to ASCII conversion isn't working?
>
> Thanks again.
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Beginner question] Raster to ASCII

2010-11-14 Thread Tim Chase

On 11/14/2010 01:07 PM, Becky Kern wrote:

import arcgisscripting
gp = arcgisscripting.create(9.3)
InRaster = "C:/data/raster1"
OutAsciiFile = "C:/data/raster2ascii.asc"
gp.RasterToASCII_conversion(InRaster, OutAsciiFile)

The error message:

arcgisscripting.ExecuteError: Failed to execute. Parameters are not valid.
raster1 does not exist.


While I can't speak specifically to arcgisscripting, having no 
experience with it, the error _sounds_ like the InRaster file 
isn't found.  It's the only reference to "raster1" in your code 
and the error points directly at "raster1".  My suspicion is that 
you're missing an extension...something like


  InRaster = "C:/data/raster1.rst"

with whatever the corresponding extension is.  Alternatively, 
it's pointing at directory named "raster1" instead of a file.


-tkc





--
http://mail.python.org/mailman/listinfo/python-list


Re: [Beginner question] Raster to ASCII

2010-11-14 Thread MRAB

On 14/11/2010 19:07, Becky Kern wrote:

Hi users,
I'm using Python 2.5 (in concert with ArcGIS 9.3) to convert a raster to
an ASCII file. I used the code (listed below) several weeks ago to
successfully do the conversion, but when I tried to replicate it a few
days ago, I got an error message.
import arcgisscripting
gp = arcgisscripting.create(9.3)
InRaster = "C:/data/raster1"
OutAsciiFile = "C:/data/raster2ascii.asc"
gp.RasterToASCII_conversion(InRaster, OutAsciiFile)
The error message:
arcgisscripting.ExecuteError: Failed to execute. Parameters are not
valid. raster1 does not exist.
My file path has not changed so I don't understand why Python can no
longer recognize my raster file. Any ideas?


Just to make sure, does os.path.isfile(InRaster) return True?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question: binary data and socket.send

2009-12-21 Thread Stephen Hansen
On Mon, Dec 21, 2009 at 3:31 PM, Boris Epel  wrote:
> Hi! Please help with the problem:
> send over TCPIP data packet organized as 6 bytes of identifier,
> integer (LSB) and length of following binary data, binary data
> the clear part:  create socket, connect it, use send, close socket
> the unclear part:  create string with required data to use with send
> what I tried:

You probably want to take a look at the "struct" module to pack your
byte-strings with binary data.

HTH,

--S
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question

2009-01-19 Thread Terry Reedy

K-Dawg wrote:


I do no understand the underscore methods.


Names of the form __xyx__ are defined by the language definition and 
recognized and used by the interpreter.


See PythonLanguage / LexicalAnalysis / Identifiers / Reserved

Most refer to methods, a few to other attributes.  Modules may have 
several non-method attributes, such as '__builtins__', '__doc__', 
'__file__', '__name__', and '__package__'.


The top-level module created when the interpreter starts is given the 
name '__main__'.  If a module is imported, it __name__ is the import name.


>>> __name__
'__main__'
>>> import email
>>> email.__name__
'email'
>>> email.__file__
'C:\\Programs\\Python30\\lib\\email\\__init__.py'

If email were run directly, its name would be __main__ while the 
__file__ would be the same.


Most syntax operations have a corresponding special that implements the 
operation.  This allows user-defined objects to fully participate in 
syntax operations on an equal basis with built-in objects.


See PythonLanguage Manual / Data model / Special operations.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question

2009-01-19 Thread Benjamin Kaplan
On Mon, Jan 19, 2009 at 2:39 PM, K-Dawg  wrote:

> Please forgive my beginner question.  I have used python a little bit,
> mainly as a scripting language to perform specific administrative tasks.  I
> have trying to learn to use it to develop applications but there are a few
> things I do not understand.
>
> I come from more of a Java background.
>
> I do no understand the underscore methods.  __main__  - is this just the
> main method that is in the file that is actually executed?  I also see
> __init__ a lot.  What is that for?  Is it like a constructor in Java or
> totally different?]


Python doesn't have a main method. It's files are scripts and not programs.
It's just like a shell script- everything is run. Unlike Java where
everything has to be in a method in a class, you can have actions performed
at the module level in Python. What you'll find is a lot of "if __name__ ==
'__main__'" conditionals. The name of the script that is run is always
__main__, so you can use this to only run certain commands when the script
is run directly as opposed to be imported by another module.

__init__ is the equivalent of a Java constructor.

>
>
> Thanks for clearing it up.  I am undertaking my first application
> development effort in python and anticipate discussing this with all of you
> a lot.  :)  Thanks for your support.
>
> Kevin
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-14 Thread moogyd
On 13 Jul, 19:49, Terry Reedy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > What is this *lis operation called? I am having trouble finding any
> > reference to it in the python docs or the book learning python.
>
> One might call this argument unpacking, but
> Language Manual / Expressions / Primaries / Calls
> simply calls it *expression syntax.
> "If the syntax *expression appears in the function call, expression must
> evaluate to a sequence. Elements from this sequence are treated as if
> they were additional positional arguments; if there are positional
> arguments x1,...,*xN* , and expression evaluates to a sequence
> y1,...,*yM*, this is equivalent to a call with M+N positional arguments
> x1,...,*xN*,*y1*,...,*yM*."
>
> See Compound Statements / Function definitions for the mirror syntax in
> definitions.
>
> tjr

Thanks,

It's starting to make sense :-)

Steven
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-14 Thread cokofreedom
>
> zip(*vec_list) will zip together all entries in vec_list
> Do be aware that zip stops on the shortest iterable.  So if vec[1] is
> shorter than vec[0] and matches otherwise, your output line will be
> truncated.  Or if vec[1] is longer and vec[0] matches as far as it goes,
> there will be no signal either.
>

Do note that from Python 3.0 there is another form of zip that will
read until all lists are exhausted, with the other being filled up
with a settable default value. Very useful!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-13 Thread Terry Reedy

[EMAIL PROTECTED] wrote:


What is this *lis operation called? I am having trouble finding any
reference to it in the python docs or the book learning python.


One might call this argument unpacking, but
Language Manual / Expressions / Primaries / Calls
simply calls it *expression syntax.
"If the syntax *expression appears in the function call, expression must 
evaluate to a sequence. Elements from this sequence are treated as if 
they were additional positional arguments; if there are positional 
arguments x1,...,*xN* , and expression evaluates to a sequence 
y1,...,*yM*, this is equivalent to a call with M+N positional arguments 
x1,...,*xN*,*y1*,...,*yM*."


See Compound Statements / Function definitions for the mirror syntax in 
definitions.


tjr

--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-13 Thread moogyd
On 12 Jul, 21:50, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On 12 juil, 20:55, [EMAIL PROTECTED] wrote:
>
>
>
> zip is (mostly) ok. What you're missing is how to use it for any
> arbitrary number of sequences. Try this instead:
>
> >>> lists = [range(5), range(5,11), range(11, 16)]
> >>> lists
>
> [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]>>> for item in 
> zip(*lists):
>
> ... print item
> ...
> (0, 5, 11)
> (1, 6, 12)
> (2, 7, 13)
> (3, 8, 14)
> (4, 9, 15)

What is this *lis operation called? I am having trouble finding any
reference to it in the python docs or the book learning python.

> > Any other comments/suggestions appreciated.
>
> There's a difflib package in the standard lib. Did you give it a try ?

I'll check it out, but I am a newbie, so I am writing this as a
(useful) learning excercise.

Thanks for the help

Steven


--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-12 Thread Terry Reedy



[EMAIL PROTECTED] wrote:

Hi group,

I have a basic question on the zip built in function.

I am writing a simple text file comparison script, that compares line
by line and character by character. The output is the original file,
with an X in place of any characters that are different.

I have managed a solution for a fixed (3) number of files, but I want
a solution of any number of input files.

The outline of my solution:

for vec in zip(vec_list[0],vec_list[1],vec_list[2]):
res = ''
for entry in zip(vec[0],vec[1],vec[2]):
if len(set(entry)) > 1:
res = res+'X'
else:
res = res+entry[0]
outfile.write(res)

So vec is a tuple containing a line from each file, and then entry is
a tuple containg a character from each line.

2 questions
1) What is the general solution. Using zip in this way looks wrong. Is
there another function that does what I want


zip(*vec_list) will zip together all entries in vec_list
Do be aware that zip stops on the shortest iterable.  So if vec[1] is 
shorter than vec[0] and matches otherwise, your output line will be 
truncated.  Or if vec[1] is longer and vec[0] matches as far as it goes, 
there will be no signal either.


res=rex+whatever can be written as res+=whatever


2) I am using set to remove any repeated characters. Is there a
"better" way ?


I might have written a third loop to compare vec[0] to vec[1]..., but 
your set solution is easier and prettier.


If speed is an issue, don't rebuild the output line char by char.  Just 
change what is needed in a mutable copy.  I like this better anyway.


res = list(vec[0]) # if all ascii, in 3.0 use bytearray
for n, entry in enumerate(zip(vec[0],vec[1],vec[2])):
  if len(set(entry)) > 1:
  res[n] = 'X'
  outfile.write(''.join(res)) # in 3.0, write(res)

tjr




--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-12 Thread [EMAIL PROTECTED]
On 12 juil, 20:55, [EMAIL PROTECTED] wrote:
> Hi group,
>
> I have a basic question on the zip built in function.
>
> I am writing a simple text file comparison script, that compares line
> by line and character by character. The output is the original file,
> with an X in place of any characters that are different.
>
> I have managed a solution for a fixed (3) number of files, but I want
> a solution of any number of input files.
>
> The outline of my solution:
>
> for vec in zip(vec_list[0],vec_list[1],vec_list[2]):
> res = ''
> for entry in zip(vec[0],vec[1],vec[2]):
> if len(set(entry)) > 1:
> res = res+'X'
> else:
> res = res+entry[0]
> outfile.write(res)
>
> So vec is a tuple containing a line from each file, and then entry is
> a tuple containg a character from each line.
>
> 2 questions
> 1) What is the general solution. Using zip in this way looks wrong. Is
> there another function that does what I want

zip is (mostly) ok. What you're missing is how to use it for any
arbitrary number of sequences. Try this instead:

>>> lists = [range(5), range(5,11), range(11, 16)]
>>> lists
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> for item in zip(*lists):
... print item
...
(0, 5, 11)
(1, 6, 12)
(2, 7, 13)
(3, 8, 14)
(4, 9, 15)
>>> lists = [range(5), range(5,11), range(11, 16), range(16, 20)]
>>> for item in zip(*lists):
... print item
...
(0, 5, 11, 16)
(1, 6, 12, 17)
(2, 7, 13, 18)
(3, 8, 14, 19)
>>>

The only caveat with zip() is that it will only use as many items as
there are in your shorter sequence, ie:

>>> zip(range(3), range(10))
[(0, 0), (1, 1), (2, 2)]
>>> zip(range(30), range(10))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8,
8), (9, 9)]
>>>

So you'd better pad your sequences to make them as long as the longer
one. There are idioms for doing this using the itertools package's
chain and repeat iterators, but I'll leave concrete example as an
exercice to the reader !-)

> 2) I am using set to remove any repeated characters. Is there a
> "better" way ?

That's probably what I'd do too.

> Any other comments/suggestions appreciated.

There's a difflib package in the standard lib. Did you give it a try ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-12 Thread Larry Bates

[EMAIL PROTECTED] wrote:

Hi group,

I have a basic question on the zip built in function.

I am writing a simple text file comparison script, that compares line
by line and character by character. The output is the original file,
with an X in place of any characters that are different.

I have managed a solution for a fixed (3) number of files, but I want
a solution of any number of input files.

The outline of my solution:

for vec in zip(vec_list[0],vec_list[1],vec_list[2]):
res = ''
for entry in zip(vec[0],vec[1],vec[2]):
if len(set(entry)) > 1:
res = res+'X'
else:
res = res+entry[0]
outfile.write(res)

So vec is a tuple containing a line from each file, and then entry is
a tuple containg a character from each line.

2 questions
1) What is the general solution. Using zip in this way looks wrong. Is
there another function that does what I want
2) I am using set to remove any repeated characters. Is there a
"better" way ?

Any other comments/suggestions appreciated.

Thanks,

Steven






You should take a look at Python's difflib library.  I probably already does
what you are attempting to "re-invent".

-Larry
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question

2008-05-25 Thread Graham Dumpleton
On May 26, 4:13 am, howa <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Just want to try mod_python but it is more complicated then I
> expected...
>
> I just followed the tutorial 
> on:http://www.modpython.org/live/mod_python-2.7.8/doc-html/inst-testing
>
> E.g.
>
> URL =http://www.example.com/mptest.py
>
> It return
>
> ImportError: No module named mptest
>
> 1. If I removed addHandler mod_python .py and PythonHandler mptest, I
> can see the SOURCE CODE
>
> 2. The PythonHandler mod_python.testhandler seems return correct
> result, showing I am using python 2.4.3
>
> any idea?

Why are you using the documentation from version 2.7.8 of mod_python
when you are using a much newer version?

Also read:

  http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking

Graham



--
http://mail.python.org/mailman/listinfo/python-list


Re: beginner question, function returning object.

2008-02-07 Thread bambam
Thank you.

So example 2 was clearly wrong, and example 1 was not clear :~).

pipe is a serial port object: when I print pipe it shows first that it is
connected to port 5, then that it is connected to port 6.  I'll discard
the clearly wrong code, and concentrate on the unclear code: probably
by the time I have clarified the problem, the solution will also be clear.

Thanks again..



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner question, function returning object.

2008-02-07 Thread Steven D'Aprano
On Thu, 07 Feb 2008 19:14:54 +1100, bambam wrote:

> Second try (correction)
> 
> I started with ths:
>  --
> def open_pipe():
> pipe=PIPE()
> print pipe
> return pipe

What's PIPE() do?


> pipe=open_pipe()

(Extraneous space removed.)

> pipe.parent = self.parent

What's self? What's it do? What's self.parent and what does it do?

> print pipe
>  --
>  It didn't do what I wanted: when I printed the pipe the second time it
>  was not the same object as the first time.

How do you know? What makes you think they are different objects?


 
>  So I changed it to this:
> def open_pipe(pipe):
> pipe=PIPE()
> print pipe
> 
>  pipe = None

Again with the extraneous space.

> open_pipe(pipe)

This can't possibly work. What you are doing is this:

(1)  set the name 'pipe' to None
(2)  call the function open_pipe() with None as the argument
(3)  which reassigns the *inner* variable 'pipe' to the result of PIPE(),
but doesn't do anything to the *global* variable 'pipe'
(4)  open_pipe() now returns None, which doesn't get used

So as you can see, the global 'pipe' starts off as None, and then nothing 
happens to it, so it stays None.

> pipe.parent = self.parent
> print pipe
> 
>  It still doesn't do what I wanted: I can't assign the parent property
>  because pipe type is None.
>
>  I'm not sure enough of what I am doing to tell if I have another error
>  in my
>  code causing the problem. Is either of these examples supposed to work
>  as shown? Is it clear that either example is obviously wrong?


Your first attempt was almost certainly the correct way to try to do what 
you want. I suspect that your function PIPE() is broken.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner question, function returning object.

2008-02-07 Thread Marc 'BlackJack' Rintsch
On Thu, 07 Feb 2008 19:14:54 +1100, bambam wrote:

> I started with ths:
>  --
> def open_pipe():
> pipe=PIPE()
> print pipe
> return pipe
> 
>  pipe=open_pipe()
> pipe.parent = self.parent
> print pipe
>  --
>  It didn't do what I wanted: when I printed the pipe the second time it was
>  not the same object as the first time.

Please post actual minimal code that reproduces the problem and a better
description of what you get and what you expected instead.

What is `PIPE` and where does `self` come from?  What are the too
``print``\s printing that makes you think `pipe` isn't bound to the same
object?

>  So I changed it to this:
> def open_pipe(pipe):
> pipe=PIPE()
> print pipe
> 
>  pipe = None
> open_pipe(pipe)
> pipe.parent = self.parent
> print pipe
> 
>  It still doesn't do what I wanted: I can't assign the parent property
>  because pipe type is None.

Yes because in `open_pipe()` you bind a new object to the local name
`pipe` which of course has no effect on the binding of the name `pipe` in
the callers namespace.

> I'm not sure enough of what I am doing to tell if I have another error in 
> my code causing the problem. Is either of these examples supposed to work
> as shown? Is it clear that either example is obviously wrong?

The second is wrong.  The first should work if `self` and `PIPE` are bound
to appropriate objects.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner question, function returning object.

2008-02-07 Thread bambam
Second try (correction)

I started with ths:
 --
def open_pipe():
pipe=PIPE()
print pipe
return pipe

 pipe=open_pipe()
pipe.parent = self.parent
print pipe
 --
 It didn't do what I wanted: when I printed the pipe the second time it was
 not the same object as the first time.

 So I changed it to this:
def open_pipe(pipe):
pipe=PIPE()
print pipe

 pipe = None
open_pipe(pipe)
pipe.parent = self.parent
print pipe

 It still doesn't do what I wanted: I can't assign the parent property
 because pipe type is None.

 I'm not sure enough of what I am doing to tell if I have another error in 
my
 code causing the problem. Is either of these examples supposed to work as
 shown? Is it clear that either example is obviously wrong?





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread Bruno Desthuilliers
SMALLp a écrit :
(snip)
> One more question. How does my code looks like. I couldn't find any open 
> source program written in python

You must be jocking ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> On Dec 21, 9:11 am, SMALLp <[EMAIL PROTECTED]> wrote:
> 
(snip)
>>class insertData:
>>def insert(self, dataTable, data):
(snip)
> 
> I think you need to post the real traceback or the real code since
> your error message doesn't look like it has anything to do with the
> code above. At least, I do not see a method named "insert".

May I suggest a new pair of glasses ?-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread kyosohma
On Dec 21, 1:44 pm, SMALLp <[EMAIL PROTECTED]> wrote:
> Carsten Haese wrote:
> > On Fri, 2007-12-21 at 18:06 +0100, SMALLp wrote:
>  sql ="INSERT INTO "+dataTable+" (user_name, file_name, 
>  file_size,
>  file_path_local, file_path_FTP, curent_location, FTP_valid_time,
>  uploaded, last_modified, last_verified, file_type, file_category) VLAUES
>  "+data
>  cursor.execute(sql)
>
> >> Thanks! I solved the problem. And I thing i understand now.
>
> > You may have solved your initial problem, but the above snippet raises
> > two red flags:
>
> > 1) Why is the table name coming from a variable? This implies to me that
> > you a working with a collection of tables with different names that all
> > have the same column names. If that is the case, that smells of really
> > bad database design. If at all possible, those tables should be merged
> > into one table that has an additional column (or set of columns) for
> > distinguishing which "fragment" each row is in.
>
> > 2) Sticking literal values into an SQL query string is a bad idea. You
> > should learn about parametrized queries, e.g. here:
> >http://informixdb.blogspot.com/2007/07/filling-in-blanks.html
>
> > Hope this helps,
>
> Good question. I'm using only one tale and have no idea why i had table
> name from variable. But every new knowledge comes handy.
>
> One more question. How does my code looks like. I couldn't find any open
> source program written in python to learn from, so i read some tutorials
> and I'm not sure about how it looks.

You couldn't find any programs written in Python? What the!?

Here's a few:

http://cheeseshop.python.org/pypi/UliPad/3.6/
http://spambayes.sourceforge.net/
http://sourceforge.net/softwaremap/trove_list.php?form_cat=178

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread SMALLp
Carsten Haese wrote:
> On Fri, 2007-12-21 at 18:06 +0100, SMALLp wrote:
 sql ="INSERT INTO "+dataTable+" (user_name, file_name, 
 file_size,
 file_path_local, file_path_FTP, curent_location, FTP_valid_time,
 uploaded, last_modified, last_verified, file_type, file_category) VLAUES
 "+data
 cursor.execute(sql)
> 
>> Thanks! I solved the problem. And I thing i understand now.
> 
> You may have solved your initial problem, but the above snippet raises
> two red flags:
> 
> 1) Why is the table name coming from a variable? This implies to me that
> you a working with a collection of tables with different names that all
> have the same column names. If that is the case, that smells of really
> bad database design. If at all possible, those tables should be merged
> into one table that has an additional column (or set of columns) for
> distinguishing which "fragment" each row is in.
> 
> 2) Sticking literal values into an SQL query string is a bad idea. You
> should learn about parametrized queries, e.g. here:
> http://informixdb.blogspot.com/2007/07/filling-in-blanks.html
> 
> Hope this helps,
> 
Good question. I'm using only one tale and have no idea why i had table 
name from variable. But every new knowledge comes handy.

One more question. How does my code looks like. I couldn't find any open 
source program written in python to learn from, so i read some tutorials 
and I'm not sure about how it looks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread Carsten Haese
On Fri, 2007-12-21 at 18:06 +0100, SMALLp wrote:
> >> sql ="INSERT INTO "+dataTable+" (user_name, file_name, 
> >> file_size,
> >> file_path_local, file_path_FTP, curent_location, FTP_valid_time,
> >> uploaded, last_modified, last_verified, file_type, file_category) VLAUES
> >> "+data
> >> cursor.execute(sql)

> Thanks! I solved the problem. And I thing i understand now.

You may have solved your initial problem, but the above snippet raises
two red flags:

1) Why is the table name coming from a variable? This implies to me that
you a working with a collection of tables with different names that all
have the same column names. If that is the case, that smells of really
bad database design. If at all possible, those tables should be merged
into one table that has an additional column (or set of columns) for
distinguishing which "fragment" each row is in.

2) Sticking literal values into an SQL query string is a bad idea. You
should learn about parametrized queries, e.g. here:
http://informixdb.blogspot.com/2007/07/filling-in-blanks.html

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread SMALLp
[EMAIL PROTECTED] wrote:
>> Traceback (most recent call last):
>>File "/home/pofuk/MzMFIleShare/sharePanel.py", line 130, in share
>>  self.scanDirsAndFiles(dirPath)
>>File "/home/pofuk/MzMFIleShare/sharePanel.py", line 158, in
>> scanDirsAndFiles
>>  sql.insertData.insert("files", data)
>> TypeError: unbound method insert() must be called with insertData
>> instance as first argument (got str instance instead)
>>
>> share.py
> 
> 
> 
> 
> 
>> def scanDirsAndFiles(self, dirPath):
>> for item in os.listdir(dirPath):
>> if os.path.isdir(os.path.join(dirPath, item)):
>> scanDirsAndFiles(os.path.join(dirPath, item))
>> if os.path.isfile(os.path.join(dirPath, item)):
>> user_name = login.getUserName()
>> fileName = item
>> fileSize = 
>> os.path.getsize(os.path.join(dirPath, item))
>> filePathLocal = os.path.join(dirPath, item)
>> filePathFTP = ""
>> currentLocation = "Local"
>> FTP_valid_time = 7
>> uploaded = ""
>> lastModified = "NOW()"
>> lastVerified = "NOW()"
>> fileType = "file"
>> fileCategory = "Ostalo"
>>
>> data = [fileName, fileSize, filePathLocal, 
>> filePathFTP,
>> currentLocation, FTP_valid_time, uploaded, lastModified, lastVerified,
>> fileType, fileCategory]
>>
>> sql.insertData.insert("files", data)
>>
> 
> 
> 
> 
> 
>> class insertData:
>> def insert(self, dataTable, data):
>> conn = self.openConnection.openConnection()
>> cursor = conn.cursor()
>> sql ="INSERT INTO "+dataTable+" (user_name, file_name, 
>> file_size,
>> file_path_local, file_path_FTP, curent_location, FTP_valid_time,
>> uploaded, last_modified, last_verified, file_type, file_category) VLAUES
>> "+data
>> cursor.execute(sql)
>> conn.Close()
> 
> It doesn't look like you are instantiating the insertData class. You
> would need to do something like:
> 
> # untested
> foo = insertData()
> foo.insert("files", data)
> 
> 
> But I agree with Chris. You really do need to go through a tutorial on
> using classes and following Python naming conventions. Dive Into
> Python and some of the other online resources are very helpful.
> 
> This is something that I have trouble with myself since wxPython uses
> CamelCase for classes and methods/functions and and most
> recommendations for plain Python seem to only want CamelCase for
> classes and something like myFunct or myMethod for the other objects.
> 
> Mike
Thanks! I solved the problem. And I thing i understand now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread kyosohma

> Traceback (most recent call last):
>File "/home/pofuk/MzMFIleShare/sharePanel.py", line 130, in share
>  self.scanDirsAndFiles(dirPath)
>File "/home/pofuk/MzMFIleShare/sharePanel.py", line 158, in
> scanDirsAndFiles
>  sql.insertData.insert("files", data)
> TypeError: unbound method insert() must be called with insertData
> instance as first argument (got str instance instead)
>
> share.py





> def scanDirsAndFiles(self, dirPath):
> for item in os.listdir(dirPath):
> if os.path.isdir(os.path.join(dirPath, item)):
> scanDirsAndFiles(os.path.join(dirPath, item))
> if os.path.isfile(os.path.join(dirPath, item)):
> user_name = login.getUserName()
> fileName = item
> fileSize = 
> os.path.getsize(os.path.join(dirPath, item))
> filePathLocal = os.path.join(dirPath, item)
> filePathFTP = ""
> currentLocation = "Local"
> FTP_valid_time = 7
> uploaded = ""
> lastModified = "NOW()"
> lastVerified = "NOW()"
> fileType = "file"
> fileCategory = "Ostalo"
>
> data = [fileName, fileSize, filePathLocal, 
> filePathFTP,
> currentLocation, FTP_valid_time, uploaded, lastModified, lastVerified,
> fileType, fileCategory]
>
> sql.insertData.insert("files", data)
>





> class insertData:
> def insert(self, dataTable, data):
> conn = self.openConnection.openConnection()
> cursor = conn.cursor()
> sql ="INSERT INTO "+dataTable+" (user_name, file_name, 
> file_size,
> file_path_local, file_path_FTP, curent_location, FTP_valid_time,
> uploaded, last_modified, last_verified, file_type, file_category) VLAUES
> "+data
> cursor.execute(sql)
> conn.Close()

It doesn't look like you are instantiating the insertData class. You
would need to do something like:

# untested
foo = insertData()
foo.insert("files", data)


But I agree with Chris. You really do need to go through a tutorial on
using classes and following Python naming conventions. Dive Into
Python and some of the other online resources are very helpful.

This is something that I have trouble with myself since wxPython uses
CamelCase for classes and methods/functions and and most
recommendations for plain Python seem to only want CamelCase for
classes and something like myFunct or myMethod for the other objects.

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question!

2007-12-21 Thread Chris Mellon
On Dec 21, 2007 9:11 AM, SMALLp <[EMAIL PROTECTED]> wrote:
> Hy! I have error something like this
>
> TypeError: unbound method insert() must be called with insertData
> instance as first argument (got str instance instead)
>
> CODE:
>
> File1.py
> sql.insertData.insert("files", data)
>
> sql.py
>
> class insertData:
> def insert(self, dataTable, data):
> conn = self.openConnection.openConnection()
> cursor = conn.cursor()
> sql ="INSERT INTO "+dataTable+" (user_name, file_name, 
> file_size,
> file_path_local, file_path_FTP, curent_location, FTP_valid_time,
> uploaded, last_modified, last_verified, file_type, file_category) VLAUES
> "+data
> cursor.execute(sql)
> conn.Close()
>
>
> Help and advice neaded!
> --

You are unclear on the distinction between classes and instances of
those classes. Following Python convention and naming your classes in
CapsCase (InsertData not insertData) would help. I recommend taking 2
giant steps backward and working through the python tutorial and dive
into python, then coming back to this project.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >