Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-12 Thread mad scientist jr
Thanks for your reply!

On Saturday, June 11, 2016 at 2:41:39 PM UTC-4, MRAB wrote:
> Drop the next 3 comment lines. They add visual clutter, and no useful info.
> > ###
> > # REFERENCE MODULES
> > ###

I'm not going to argue minor points at length, because others have said the 
same thing here, but I will push back a little and explain that what you guys 
consider visual clutter, I find helps me to visually break up and quickly 
identify sections in my code, which is why I like those separators.

> There's an easier to make the repeated string: "+" * 79
> > 
> > print("+++")

Thanks, that's a good tip. In this case I might prefer showing the full line of 
+s because that way, wysiwyg, it's just easier to visualize the output.

Thanks again for the input. . . I will further digest what you all said and 
study some more (including the docstrings)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-11 Thread MRAB

On 2016-06-11 18:59, mad scientist jr wrote:

Thanks to everyone for your replies.  I see my script was as horrific as I 
feared, but I read all the responses and made a few changes.  I'm not 100% sold 
on not checking types, but took it out, because it made sense that other 
programmers might want to use some custom type with my functions for their own 
nefarious purposes.

One question I have is, can someone point me to a full listing of all the error 
types I can trap for?  It seems like a Pandora's box, trying to think of all 
the things that could go wrong, which is why I originally just printed the 
error #. Is it better to not trap errors, and let the stack trace tell what 
went wrong?  Does it give all the information on the error type etc.?


Catch those exceptions that you can do something about.

If, say, it complains that it can't create a folder, you'll need to 
decide what you should do about it. You might decide that the best way 
to handle it is to report it to the user and then continue, or report it 
to the user and then stop. Do whatever makes most sense.


If it complains about something unexpected, it's probably best to report 
it and then just stop, i.e. let unknown exceptions propagate.


As Python is an extensible language, there'll never be a complete list 
of exceptions; just catch what you're prepared to handle.



Anyway, for those charitable (or masochistic, or both) enough to critique my 
code again, here is the updated version:

# For Python 3.x

# This script creates multiple numbered empty folders
# in the desired location. To change the folder names
# or location, edit function get_default_options.


Drop the next 3 comment lines. They add visual clutter, and no useful info.


###
# REFERENCE MODULES
###
import datetime
import os
import errno
import sys

###
# SUPPORT FUNCTIONS
###

# returns: dictionary containing options for this script
def get_default_options():
dict = {
"s_for_python_version": "3",
"s_folder_path_template": "C:/temp/test/MP3 Disk {count:03}",
"i_from_count": 3,
"i_to_count": 7,
}
return dict

# returns: string containing exact version #, eg "3.5.1"
# TODO: update to use
#   sys.version_info[:3] by itself gives a three-element tuple.
#   Probably easier to use than thestring version.
#   A couple alternatives:
#   sys.version[:5] or perhaps a bit safer -- sys.version.split()[0] both 
directly give you the
#  string version.  (Note this uses version not version_info.)
def get_exact_python_version():
s_version = ".".join(map(str, sys.version_info[:3]))


The string produced by the preceding line won't start or end with any 
whitespace, so the next line is pointless.



s_version = s_version.strip()
return s_version

# returns: string containing general version #, eg "3"
# TODO: return to the left of first "."
def get_general_python_version():


It's called the "major" version. You're going the long way round! The 
simplest way to get it is directly from sys.version_info.



s_version = get_exact_python_version()
return s_version[0]

# checks python version
# if it's wrong then gracefully exit before it blows up
# (damn, python 2.x still complains with syntax errors!!)
#
# receives:
#   s_right_version (string) = python version # to check against
#
# TODO: more granular check, eg if version >= 3.5.0
def exit_if_wrong_python_version(s_right_version):
s_current_version = get_general_python_version()


The conditions of 'if' statements don't need to be wrapped in (...).


if (s_current_version != s_right_version):
print(
"Wrong Python version ({}), "
"this script should be run using "
"Python {}.x,  Exiting..."
"".format(s_current_version, s_right_version))
sys.exit() # SAME AS os._exit(0)

# assists in script readability
# returns: string containing name of the current script
def get_script_filename():
return sys.argv[0]

# returns: string containing the current date/time in the format eg 2016-05-22 
13:01:55
def get_timestamp():
> return datetime.datetime.strftime(datetime.datetime.now(), 
'%Y-%m-%d %H:%M:%S')


datetime instances have a .strftime method, so you can shorten that to:

return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')



# creates a folder at the specified path
# receives:
#   s_path (string) = full path of folder to create
def create_folder(s_path):
try:
os.makedirs(s_path, exist_ok=True)
except (FileExistsError, IsADirectoryError) as e:


There's little point in catching an exception, printing a message, and 
then re-raising the exception. The exception's traceback 

Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-11 Thread Marc Brooks
Look into docstrings. They will make your code much more readable to a
Python reader.
On Sat, Jun 11, 2016 at 2:16 PM mad scientist jr 
wrote:

> For those who don't want to have to wade through comments, here is a
> version without so many comments:
>
> # For Python 3.x
> # This script creates multiple numbered empty folders
> # in the desired location. To change the folder names
> # or location, edit function get_default_options.
>
> import datetime
> import os
> import errno
> import sys
>
>
> ###
> # EDIT VALUES HERE TO CUSTOMIZE THE OUTPUT
> def get_default_options():
> dict = {
> "s_for_python_version": "3",
> "s_folder_path_template": "C:/temp/test/MP3 Disk {count:03}",
> "i_from_count": 3,
> "i_to_count": 7,
> }
> return dict
>
> ###
>
> def get_exact_python_version():
> s_version = ".".join(map(str, sys.version_info[:3]))
> s_version = s_version.strip()
> return s_version
>
> def get_general_python_version():
> s_version = get_exact_python_version()
> return s_version[0]
>
> def exit_if_wrong_python_version(s_right_version):
> s_current_version = get_general_python_version()
> if (s_current_version != s_right_version):
> print(
> "Wrong Python version ({}), "
> "this script should be run using "
> "Python {}.x,  Exiting..."
> "".format(s_current_version, s_right_version))
> sys.exit()
>
> def get_script_filename():
> return sys.argv[0]
>
> def get_timestamp():
> return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d
> %H:%M:%S')
>
> def create_folder(s_path):
> try:
> os.makedirs(s_path, exist_ok=True)
> except (FileExistsError, IsADirectoryError) as e:
> print("FileExistsError IN makedirs")
> raise
> return False
> except OSError as exception:
> print("ERROR #" + str(exception.errno) + "IN makedirs")
> raise
> return False
> print("" + get_timestamp() + " " + "Created folder: " + s_path + "")
>
> def create_folders(
> s_folder_path_template:str="",
> i_from_count:int=1,
> i_to_count:int=0
> ):
> i_count=0
> for i_loop in range(i_from_count, i_to_count + 1):
> create_folder(s_folder_path_template.format(count=i_loop))
> i_count += 1
>
> return i_count
>
> def main():
> options_dict = get_default_options()
> exit_if_wrong_python_version(options_dict["s_for_python_version"])
>
>
> print("+++")
> print("" + get_timestamp() + " " + get_script_filename() + " started.")
>
> i_total_created = create_folders(
> options_dict["s_folder_path_template"],
> options_dict["i_from_count"],
> options_dict["i_to_count"])
>
> print("" + get_timestamp() + " " + str(i_total_created) + " folders
> created.")
> print("" + get_timestamp() + " " + get_script_filename() + "
> finished.")
>
> if __name__ == '__main__':
> main()
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-11 Thread mad scientist jr
For those who don't want to have to wade through comments, here is a version 
without so many comments:

# For Python 3.x
# This script creates multiple numbered empty folders
# in the desired location. To change the folder names
# or location, edit function get_default_options.

import datetime
import os
import errno
import sys

###
# EDIT VALUES HERE TO CUSTOMIZE THE OUTPUT
def get_default_options():
dict = {
"s_for_python_version": "3",
"s_folder_path_template": "C:/temp/test/MP3 Disk {count:03}", 
"i_from_count": 3,
"i_to_count": 7,
}
return dict
###

def get_exact_python_version():
s_version = ".".join(map(str, sys.version_info[:3]))
s_version = s_version.strip()
return s_version

def get_general_python_version():
s_version = get_exact_python_version()
return s_version[0]

def exit_if_wrong_python_version(s_right_version):
s_current_version = get_general_python_version()
if (s_current_version != s_right_version):
print(
"Wrong Python version ({}), "
"this script should be run using " 
"Python {}.x,  Exiting..."
"".format(s_current_version, s_right_version))
sys.exit()

def get_script_filename():
return sys.argv[0]

def get_timestamp():
return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d 
%H:%M:%S')

def create_folder(s_path):
try:
os.makedirs(s_path, exist_ok=True)
except (FileExistsError, IsADirectoryError) as e:
print("FileExistsError IN makedirs")
raise
return False
except OSError as exception:
print("ERROR #" + str(exception.errno) + "IN makedirs")
raise
return False
print("" + get_timestamp() + " " + "Created folder: " + s_path + "")

def create_folders(
s_folder_path_template:str="",
i_from_count:int=1,
i_to_count:int=0
):
i_count=0
for i_loop in range(i_from_count, i_to_count + 1): 
create_folder(s_folder_path_template.format(count=i_loop))
i_count += 1

return i_count

def main():
options_dict = get_default_options()
exit_if_wrong_python_version(options_dict["s_for_python_version"])


print("+++")
print("" + get_timestamp() + " " + get_script_filename() + " started.")

i_total_created = create_folders(
options_dict["s_folder_path_template"],
options_dict["i_from_count"],
options_dict["i_to_count"])

print("" + get_timestamp() + " " + str(i_total_created) + " folders 
created.")
print("" + get_timestamp() + " " + get_script_filename() + " finished.")

if __name__ == '__main__': 
main()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-11 Thread mad scientist jr
Thanks to everyone for your replies.  I see my script was as horrific as I 
feared, but I read all the responses and made a few changes.  I'm not 100% sold 
on not checking types, but took it out, because it made sense that other 
programmers might want to use some custom type with my functions for their own 
nefarious purposes.  

One question I have is, can someone point me to a full listing of all the error 
types I can trap for?  It seems like a Pandora's box, trying to think of all 
the things that could go wrong, which is why I originally just printed the 
error #. Is it better to not trap errors, and let the stack trace tell what 
went wrong?  Does it give all the information on the error type etc.?

Anyway, for those charitable (or masochistic, or both) enough to critique my 
code again, here is the updated version:

# For Python 3.x

# This script creates multiple numbered empty folders
# in the desired location. To change the folder names
# or location, edit function get_default_options.

###
# REFERENCE MODULES
###
import datetime
import os
import errno
import sys

###
# SUPPORT FUNCTIONS
###

# returns: dictionary containing options for this script
def get_default_options():
dict = {
"s_for_python_version": "3",
"s_folder_path_template": "C:/temp/test/MP3 Disk {count:03}", 
"i_from_count": 3,
"i_to_count": 7,
}
return dict

# returns: string containing exact version #, eg "3.5.1"
# TODO: update to use
#   sys.version_info[:3] by itself gives a three-element tuple.
#   Probably easier to use than thestring version. 
#   A couple alternatives: 
#   sys.version[:5] or perhaps a bit safer -- sys.version.split()[0] both 
directly give you the 
#  string version.  (Note this uses version not version_info.)
def get_exact_python_version():
s_version = ".".join(map(str, sys.version_info[:3]))
s_version = s_version.strip()
return s_version

# returns: string containing general version #, eg "3"
# TODO: return to the left of first "."
def get_general_python_version():
s_version = get_exact_python_version()
return s_version[0]

# checks python version
# if it's wrong then gracefully exit before it blows up
# (damn, python 2.x still complains with syntax errors!!)
#
# receives:
#   s_right_version (string) = python version # to check against
# 
# TODO: more granular check, eg if version >= 3.5.0
def exit_if_wrong_python_version(s_right_version):
s_current_version = get_general_python_version()
if (s_current_version != s_right_version):
print(
"Wrong Python version ({}), "
"this script should be run using " 
"Python {}.x,  Exiting..."
"".format(s_current_version, s_right_version))
sys.exit() # SAME AS os._exit(0)

# assists in script readability
# returns: string containing name of the current script
def get_script_filename():
return sys.argv[0]

# returns: string containing the current date/time in the format eg 2016-05-22 
13:01:55
def get_timestamp():
return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d 
%H:%M:%S')

# creates a folder at the specified path
# receives:
#   s_path (string) = full path of folder to create
def create_folder(s_path):
try:
os.makedirs(s_path, exist_ok=True)
except (FileExistsError, IsADirectoryError) as e:
print("FileExistsError IN makedirs")
raise
return False
except OSError as exception:
print("ERROR #" + str(exception.errno) + "IN makedirs")
raise
return False
print("" + get_timestamp() + " " + "Created folder: " + s_path + "")

# creates multiple numbered folders named per template
# receives:
#   s_folder_path_template (string) = template containing full path of folder 
to create,
# where "{count:n}" is replaced by the 
folder count (n digits)
#   i_from_count (int) = number to begin counting at
#   i_to_count (int) = number to stop counting after
#
# returns: count of folders created, 0 if error or none
def create_folders(
s_folder_path_template:str="",
i_from_count:int=1,
i_to_count:int=0
):
i_count=0
for i_loop in range(i_from_count, i_to_count + 1): 
create_folder(s_folder_path_template.format(count=i_loop))
i_count += 1

return i_count

###
# MAIN LOGIC
###

def main():
options_dict = get_default_options()
exit_if_wrong_python_version(options_dict["s_for_python_version"])
   

Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread Matt Wheeler
First of all welcome :)

The other suggestions you've received so far are good so I won't repeat
them... (note that in particular I've reused the names you've chosen in
your program where I've given code examples, but that's purely for clarity
and I agree with the others who've said you should use a more pythonic
naming convention)

On Fri, 10 Jun 2016, 23:52 mad scientist jr, 
wrote:

> Is this group appropriate for that kind of thing?
> (If not sorry for posting this here.)
>
> So I wanted to start learning Python, and there is s much information
> online, which is a little overwhelming. I really learn best from doing,
> especially if it's something actually useful. I needed to create a bunch of
> empty folders, so I figured it was a good exercise to start learning Python.
> Now that it's done, I am wondering what kind of things I could do better.
> Here is the code:
>
> # WELCOME TO MY FIRST PYTHON SCRIPT!
> # FIRST OF ALL, IT ***WORKS***!!! YAY!
> # I AM A VBA AND JAVASCRIPT PROGRAMMER,
> # SO IT IS PROBABLY NOT VERY "PYTHONIC",
> # SO PLEASE FEEL FREE TO TEAR THE SCRIPT A NEW ONE
> # AFTER YOU ARE SHOCKED BY THIS BAD CODE,
> # ALL I ASK IS THAT IF YOU THINK SOMETHING IS BAD,
> # PLEASE POST AN EXAMPLE OF THE "CORRECT" WAY OF DOING IT
> # COMING FROM VBA, I KNOW A LITTLE OOP,
> # BUT NOT C++ C# JAVA STUFF LIKE "INTERFACES" AND "ABSTRACT BASE CLASSES"
> # SO IF YOU GET INTO SUCH TERMINOLOGY MY EYES MIGHT START TO GLAZE OVER
> # UNLESS YOU CARE TO EXPLAIN THAT TOO
>
Don't worry, Python doesn't have "interfaces" like Java (though it does
have multiple inheritance instead, which is more powerful), and it's not
necessary to learn about advanced things like abstract classes until you're
comfortable :)

>
>
> 
> # GLOBAL VALUES
> sForPythonVersion="3"
> #sFolderPathTemplate = "c:\\myscripts\\MP3 Disc "
> sFolderPathTemplate = "c:\\temp\\MP3 Disc "
>
It's possible in Python to use forward slashes in paths, even on Windows,
which would allow you to avoid the double slashes above (and can make your
code more easily ported to other OSes, which pretty universally use a '/'
in paths.
I would also suggest you use python's string formatting capabilities
instead here (see below where I use this FOLDER_TEMPLATE string):

FOLDER_TEMPLATE = 'C:/temp/MP3 Disk {count:03}'

iFromCount = 1
> iToCount = 250
> iCountWidth = 3
>
>
> 
> # SUPPORT FUNCTIONS
>
> #
> //
> def is_string(myVar): # is_string IS MORE READABLE THAN isinstance (PLAIN
> ENGLISH!)
> #PYTHON 3 IS NOT LIKING THIS: return ( isinstance(myVar, str) or
> isinstance(myVar, unicode) )
> #PYTHON 3 IS NOT LIKING THIS: return isinstance(myVar, basestr)
> return isinstance(myVar, str)
>

I know this one's been asked already but I think it deserves expanding on.
In general in Python it's recommended that you don't try too hard (if at
all) to check types of things. Think about what purpose this serves.
Pythonic programs follow what's known as "duck typing". i.e. if it quacks
like a duck then we can treat it like it's a duck.
This lets you write code which expects, for example something like a
string, or a dict or list, but isn't strictly bound to those types. That
allows other programmers to create their own classes, perhaps a subclass of
dict or list, or some unconnected class which just happens to be list-like
enough, and it can just work with your code.

Of course there are places where you do need to check the type of
something, but if you think you need to it's always worth really asking
yourself why you think that.
(I think this is particularly true when it comes to `str`. Most classes can
be represented one way or another as a string, so why not let people pass
you anything if you're going to read it as a string anyway? Refusing to
accept a non-string is more work for you and more work for them for little
benefit)

#
> //
> # THIS IS SOME SAMPLE FUNCTION FROM A BOOK I AM READING "PYTHON IN EASY
> STEPS"
> def strip_one_space(s):
> if s.endswith(" "): s = s[:-1]
> if s.startswith(" "): s = s[1:]
> return s
>
> #
> //
> def get_exact_python_version():
> import sys
>

Imports belong at the top of the file unless there's a good reason you

Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread Larry Hudson via Python-list

On 06/10/2016 03:52 PM, mad scientist jr wrote:

Is this group appropriate for that kind of thing?
(If not sorry for posting this here.)

So I wanted to start learning Python, and there is s much information 
online, which is a little overwhelming. I really learn best from doing, 
especially if it's something actually useful. I needed to create a bunch of 
empty folders, so I figured it was a good exercise to start learning Python.
Now that it's done, I am wondering what kind of things I could do better.
Here is the code:


It is FAR too complicated -- it's BASIC written Python.  Python is MUCH easier.

First a couple of general comments...

Drop the Hungarian notation!!  Python uses dynamic typing.  Variables do NOT have a type, the 
data they hold have types, but not the variable itself.  ANY variable can hod ANY data type at 
ANY time.  And Python uses duck typing -- get used to it.


Generally you should put all the imports at the beginning of the program, NOT in each function. 
 A possible exception could be if an import is only used in one function.




# GLOBAL VALUES
sForPythonVersion="3"
#sFolderPathTemplate = "c:\\myscripts\\MP3 Disc "
sFolderPathTemplate = "c:\\temp\\MP3 Disc "
iFromCount = 1
iToCount = 250
iCountWidth = 3


Drop the  from the template string.  (More on this below.)



# SUPPORT FUNCTIONS

# 
//
def is_string(myVar): # is_string IS MORE READABLE THAN isinstance (PLAIN 
ENGLISH!)
 #PYTHON 3 IS NOT LIKING THIS: return ( isinstance(myVar, str) or 
isinstance(myVar, unicode) )
 #PYTHON 3 IS NOT LIKING THIS: return isinstance(myVar, basestr)
 return isinstance(myVar, str)


Not necessary.


# 
//
# THIS IS SOME SAMPLE FUNCTION FROM A BOOK I AM READING "PYTHON IN EASY STEPS"
def strip_one_space(s):
 if s.endswith(" "): s = s[:-1]
 if s.startswith(" "): s = s[1:]
 return s


???  Is this used anyplace?  Delete it.


# 
//
def get_exact_python_version():
 import sys
 sVersion = ".".join(map(str, sys.version_info[:3]))
 sVersion = sVersion.strip()
 return sVersion

sys.version_info[:3] by itself gives a three-element tuple.  Probably easier to use than the 
string version.


A couple alternatives:
sys.version[:5] or perhaps a bit safer -- sys.version.split()[0] both directly give you the 
string version.  (Note this uses version not version_info.)



# 
//
# TO DO: RETURN TO THE LEFT OF FIRST "."
def get_python_version():
 sVersion = get_exact_python_version()
 return sVersion[0:1]


Probably unnecessary as a function.  A simple sVersion[0] in-line might be 
easier.


# 
//
# CHECK PYTHON VERSION, IF IT'S WRONG THEN GRACEFULLY EXIT BEFORE IT BLOWS UP
# (DAMN, PYTHON 2.x STILL COMPLAINS WITH SYNTAX ERRORS!!)
# MAYBE THIS COULD STILL BE USEFUL FOR CHECKING THE SUB-VERSION, IN THAT CASE
# TO DO: MORE GRANULAR CHECK, EG IF VERSION >= 3.5.0
def exit_if_wrong_python_version(sRightVersion):
 import os
 sCurrentVersion = get_python_version()
 if (sCurrentVersion != sRightVersion):
 print("" +
   "Wrong Python version (" +
   sCurrentVersion +
   "), this script should be run using Python " +
   sRightVersion +
   ".x. Exiting..."
   )
 os._exit(0)


Get used to Python string formatting...
print("Wrong Python version ({}), this script should be run using "
"Python {}.x,  Exiting...".format(sCurrentVersion, sRightVersion))

Notice how I split the long single-line string into two shorter strings on two lines relying on 
the automatic string concatenation in Python.  "string1 " "string2" becomes "string1 string2". 
Any whitespace (spaces, tabs, newlines) are ignored and the two strings are stuck together.


Also the common use is sys.exit() instead of os._exit().


# 

Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread Joel Goldstick
On Fri, Jun 10, 2016 at 6:52 PM, mad scientist jr
 wrote:
> Is this group appropriate for that kind of thing?
> (If not sorry for posting this here.)
>
> So I wanted to start learning Python, and there is s much information 
> online, which is a little overwhelming. I really learn best from doing, 
> especially if it's something actually useful. I needed to create a bunch of 
> empty folders, so I figured it was a good exercise to start learning Python.
> Now that it's done, I am wondering what kind of things I could do better.
> Here is the code:
>
> # WELCOME TO MY FIRST PYTHON SCRIPT!
> # FIRST OF ALL, IT ***WORKS***!!! YAY!
> # I AM A VBA AND JAVASCRIPT PROGRAMMER,
> # SO IT IS PROBABLY NOT VERY "PYTHONIC",
> # SO PLEASE FEEL FREE TO TEAR THE SCRIPT A NEW ONE
> # AFTER YOU ARE SHOCKED BY THIS BAD CODE,
> # ALL I ASK IS THAT IF YOU THINK SOMETHING IS BAD,
> # PLEASE POST AN EXAMPLE OF THE "CORRECT" WAY OF DOING IT
> # COMING FROM VBA, I KNOW A LITTLE OOP,
> # BUT NOT C++ C# JAVA STUFF LIKE "INTERFACES" AND "ABSTRACT BASE CLASSES"
> # SO IF YOU GET INTO SUCH TERMINOLOGY MY EYES MIGHT START TO GLAZE OVER
> # UNLESS YOU CARE TO EXPLAIN THAT TOO
>
>
Ditch the uppercase comments.
 

> # GLOBAL VALUES
> sForPythonVersion="3"
> #sFolderPathTemplate = "c:\\myscripts\\MP3 Disc "
> sFolderPathTemplate = "c:\\temp\\MP3 Disc "
> iFromCount = 1
> iToCount = 250
> iCountWidth = 3
>
Python has guidelines for naming things.  Don't use camel case.  Use
lower case and put underscores between words.  Globals are a bad idea.
If you don't know why, they are even a worse idea
> 
> # SUPPORT FUNCTIONS
>
> # 
> //
> def is_string(myVar): # is_string IS MORE READABLE THAN isinstance (PLAIN 
> ENGLISH!)
> #PYTHON 3 IS NOT LIKING THIS: return ( isinstance(myVar, str) or 
> isinstance(myVar, unicode) )
> #PYTHON 3 IS NOT LIKING THIS: return isinstance(myVar, basestr)
> return isinstance(myVar, str)

I'm not sure why you want to test for type.
>
> # 
> //
> # THIS IS SOME SAMPLE FUNCTION FROM A BOOK I AM READING "PYTHON IN EASY STEPS"
> def strip_one_space(s):
> if s.endswith(" "): s = s[:-1]
> if s.startswith(" "): s = s[1:]
> return s

This may be from some book, but it could be done:
s.strip()


>
> # 
> //
> def get_exact_python_version():
> import sys
> sVersion = ".".join(map(str, sys.version_info[:3]))
> sVersion = sVersion.strip()
> return sVersion
>
> # 
> //
> # TO DO: RETURN TO THE LEFT OF FIRST "."
> def get_python_version():
> sVersion = get_exact_python_version()
> return sVersion[0:1]
>
> # 
> //
> # CHECK PYTHON VERSION, IF IT'S WRONG THEN GRACEFULLY EXIT BEFORE IT BLOWS UP
> # (DAMN, PYTHON 2.x STILL COMPLAINS WITH SYNTAX ERRORS!!)
> # MAYBE THIS COULD STILL BE USEFUL FOR CHECKING THE SUB-VERSION, IN THAT CASE
> # TO DO: MORE GRANULAR CHECK, EG IF VERSION >= 3.5.0
> def exit_if_wrong_python_version(sRightVersion):
> import os
> sCurrentVersion = get_python_version()
> if (sCurrentVersion != sRightVersion):
> print("" +
>   "Wrong Python version (" +
>   sCurrentVersion +
>   "), this script should be run using Python " +
>   sRightVersion +
>   ".x. Exiting..."
>   )
> os._exit(0)
>
> # 
> //
> def get_script_filename():
> import os
> return os.path.basename(__file__)
>
> # 
> //
> def get_timestamp():
> import datetime
> return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d 
> %H:%M:%S')
>
> # 
> 

Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread Marc Brooks
The structure of your program is really not that Pythonic.  I'd recommend
you take a look at PEP 8.

https://www.python.org/dev/peps/pep-0008/

It's not perfect, but it's a good start to get a feel for how to structure
your Python work.

Marc

On Fri, Jun 10, 2016 at 7:05 PM, Christopher Reimer <
christopher_rei...@icloud.com> wrote:

>
>
> Sent from my iPhone
>
> > On Jun 10, 2016, at 3:52 PM, mad scientist jr <
> mad.scientist...@gmail.com> wrote:
> > .
> > Now that it's done, I am wondering what kind of things I could do better.
>
> This is Python, not BASIC. Lay off on the CAP LOCK key and delete all the
> comments and separation blocks. No one is going to find your code in all
> that noise.
>
> Chris R.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread Christopher Reimer


Sent from my iPhone

> On Jun 10, 2016, at 3:52 PM, mad scientist jr  
> wrote:
> . 
> Now that it's done, I am wondering what kind of things I could do better.

This is Python, not BASIC. Lay off on the CAP LOCK key and delete all the 
comments and separation blocks. No one is going to find your code in all that 
noise.

Chris R.
-- 
https://mail.python.org/mailman/listinfo/python-list


i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread mad scientist jr
Is this group appropriate for that kind of thing? 
(If not sorry for posting this here.)

So I wanted to start learning Python, and there is s much information 
online, which is a little overwhelming. I really learn best from doing, 
especially if it's something actually useful. I needed to create a bunch of 
empty folders, so I figured it was a good exercise to start learning Python. 
Now that it's done, I am wondering what kind of things I could do better. 
Here is the code: 

# WELCOME TO MY FIRST PYTHON SCRIPT!
# FIRST OF ALL, IT ***WORKS***!!! YAY!
# I AM A VBA AND JAVASCRIPT PROGRAMMER, 
# SO IT IS PROBABLY NOT VERY "PYTHONIC", 
# SO PLEASE FEEL FREE TO TEAR THE SCRIPT A NEW ONE
# AFTER YOU ARE SHOCKED BY THIS BAD CODE, 
# ALL I ASK IS THAT IF YOU THINK SOMETHING IS BAD, 
# PLEASE POST AN EXAMPLE OF THE "CORRECT" WAY OF DOING IT
# COMING FROM VBA, I KNOW A LITTLE OOP,
# BUT NOT C++ C# JAVA STUFF LIKE "INTERFACES" AND "ABSTRACT BASE CLASSES"
# SO IF YOU GET INTO SUCH TERMINOLOGY MY EYES MIGHT START TO GLAZE OVER
# UNLESS YOU CARE TO EXPLAIN THAT TOO


# GLOBAL VALUES
sForPythonVersion="3"
#sFolderPathTemplate = "c:\\myscripts\\MP3 Disc "
sFolderPathTemplate = "c:\\temp\\MP3 Disc "
iFromCount = 1
iToCount = 250
iCountWidth = 3


# SUPPORT FUNCTIONS

# 
//
def is_string(myVar): # is_string IS MORE READABLE THAN isinstance (PLAIN 
ENGLISH!)
#PYTHON 3 IS NOT LIKING THIS: return ( isinstance(myVar, str) or 
isinstance(myVar, unicode) )
#PYTHON 3 IS NOT LIKING THIS: return isinstance(myVar, basestr)
return isinstance(myVar, str)

# 
//
# THIS IS SOME SAMPLE FUNCTION FROM A BOOK I AM READING "PYTHON IN EASY STEPS"
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s

# 
//
def get_exact_python_version():
import sys
sVersion = ".".join(map(str, sys.version_info[:3]))
sVersion = sVersion.strip()
return sVersion

# 
//
# TO DO: RETURN TO THE LEFT OF FIRST "."
def get_python_version():
sVersion = get_exact_python_version()
return sVersion[0:1]

# 
//
# CHECK PYTHON VERSION, IF IT'S WRONG THEN GRACEFULLY EXIT BEFORE IT BLOWS UP
# (DAMN, PYTHON 2.x STILL COMPLAINS WITH SYNTAX ERRORS!!)
# MAYBE THIS COULD STILL BE USEFUL FOR CHECKING THE SUB-VERSION, IN THAT CASE
# TO DO: MORE GRANULAR CHECK, EG IF VERSION >= 3.5.0
def exit_if_wrong_python_version(sRightVersion):
import os
sCurrentVersion = get_python_version()
if (sCurrentVersion != sRightVersion):
print("" +
  "Wrong Python version (" +
  sCurrentVersion +
  "), this script should be run using Python " +
  sRightVersion +
  ".x. Exiting..."
  )
os._exit(0)

# 
//
def get_script_filename():
import os
return os.path.basename(__file__)

# 
//
def get_timestamp():
import datetime
return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d 
%H:%M:%S')

# 
//

def create_folder(sPath):
import os
import errno
#if not os.path.exists(directory):
#os.makedirs(directory)
try:
os.makedirs(sPath, exist_ok=True)
except OSError as exception:
#if exception.errno != errno.EEXIST:
print("ERROR #" + str(exception.errno) + "IN makedirs")
raise

# 

Re: Python newbie here! No module named settings

2015-04-12 Thread rdavis7408
On Thursday, June 2, 2011 at 10:29:48 AM UTC-5, Neeraj Agarwal wrote:
 Hello all,
 
 I'm a newbie to Python and its my 2nd day exploring it.
 
 I was trying to use Python wrapper for Google Charts API and was
 tweaking the examples.
 https://github.com/gak/pygooglechart/raw/master/examples/pie.py
 
 This is the script which I was trying.
 
 And the python interpreter gives the following error:
 import settings
 ImportError: No module named settings
 
 I installed Django as well before this (if its causing the problem,
 dunno)
 
 Please help me.
 
 Thanks,
 Neeraj

Thanks, your answer was a big help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive sorting of strings (Python newbie)

2015-01-23 Thread Peter Otten
John Sampson wrote:

 I notice that the string method 'lower' seems to convert some strings
 (input from a text file) to Unicode but not others.
 This messes up sorting if it is used on arguments of 'sorted' since
 Unicode strings come before ordinary ones.
 
 Is there a better way of case-insensitive sorting of strings in a list?
 Is it necessary to convert strings read from a plaintext file
 to Unicode? If so, how? This is Python 2.7.8.

The standard recommendation is to convert bytes to unicode as early as 
possible and only manipulate unicode. This is more likely to give correct 
results when slicing or converting a string.

$ cat tmp.txt
ähnlich
üblich
nötig
möglich
Maß
Maße
Masse
ÄHNLICH
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type help, copyright, credits or license for more information.
 for line in open(tmp.txt):
... line = line.strip()
... print line, line.lower()
... 
ähnlich ähnlich
üblich üblich
nötig nötig
möglich möglich
Maß maß
Maße maße
Masse masse
ÄHNLICH Ähnlich

Now the same with unicode. To read text with a specific encoding use either 
codecs.open() or io.open() instead of the built-in (replace utf-8 with your 
actual encoding):

 import io
 for line in io.open(tmp.txt, encoding=utf-8): 
... line = line.strip()
... print line, line.lower()
... 
ähnlich ähnlich
üblich üblich
nötig nötig
möglich möglich
Maß maß
Maße maße
Masse masse
ÄHNLICH ähnlich

Unfortunately this will not give the order that you (or a german speaker in 
the example below) will probably expect:

 print .join(sorted(io.open(tmp.txt), key=unicode.lower))
Masse
Maß
Maße
möglich
nötig
ähnlich
ÄHNLICH
üblich

For case-insensitive sorting you get better results with locale.strxfrm() -- 
but this doesn't accept unicode:

 import locale
 locale.setlocale(locale.LC_ALL, )
'de_DE.UTF-8'
 print .join(sorted(io.open(tmp.txt), key=locale.strxfrm))
Traceback (most recent call last):
  File stdin, line 1, in module
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 
0: ordinal not in range(128)

As a workaround you can sort first:

 print .join(sorted(open(tmp.txt), key=locale.strxfrm))
ähnlich
ÄHNLICH
Maß
Masse
Maße
möglich
nötig
üblich

You should still convert the result to unicode if you want to do further 
processing in Python.

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


Re: Case-insensitive sorting of strings (Python newbie)

2015-01-23 Thread Steven D'Aprano
John Sampson wrote:

 I notice that the string method 'lower' seems to convert some strings
 (input from a text file) to Unicode but not others.

I don't think so. You're going to have to show an example.

I *think* what you might be running into is an artifact of printing to a
terminal, which may (or may not) interpret some byte sequences as UTF-8
characters, but I can't replicate it. So I'll have to see an example.
Please state what OS you are running on, and what encoding your terminal is
set to. Also, are you opening the file in text mode or binary mode?


 This messes up sorting if it is used on arguments of 'sorted' since
 Unicode strings come before ordinary ones.
 
 Is there a better way of case-insensitive sorting of strings in a list?
 Is it necessary to convert strings read from a plaintext file
 to Unicode? If so, how? This is Python 2.7.8.

Best practice is to always convert to Unicode, even if you know your text is
pure ASCII. You *may* be able to get away with not doing so if you know you
have ASCII, but that's still the lazy way. And of course you need to know
what encoding has been used.

There is some overhead with decoding to Unicode, so if performance really is
critical, *and* your needs are quite low, you may be able to get away with
just treating the strings as ASCII byte strings:

with open(my file.txt) as f:
for line in f:
print line.lower()


will correctly lowercase ASCII strings. It won't lowercase non-ASCII
letters, and there's a good chance that they may display as raw bytes in
some encoding. Otherwise, I think the best way to approach this may be:


import io
with io.open(my file.txt, encoding='utf-8') as f:
for line in f:
print line.lower()


Assuming the file actually is encoded with UTF-8, that ought to work
perfectly.

But to really know what is going on we will need more information.


-- 
Steven

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


Case-insensitive sorting of strings (Python newbie)

2015-01-23 Thread John Sampson
I notice that the string method 'lower' seems to convert some strings 
(input from a text file) to Unicode but not others.
This messes up sorting if it is used on arguments of 'sorted' since 
Unicode strings come before ordinary ones.


Is there a better way of case-insensitive sorting of strings in a list? 
Is it necessary to convert strings read from a plaintext file

to Unicode? If so, how? This is Python 2.7.8.

Regards

John Sampson
--
https://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive sorting of strings (Python newbie)

2015-01-23 Thread Michael Ströder
John Sampson wrote:
 I notice that the string method 'lower' seems to convert some strings (input
 from a text file) to Unicode but not others.
 This messes up sorting if it is used on arguments of 'sorted' since Unicode
 strings come before ordinary ones.

I doubt that. Can you provide a short example?

 Is there a better way of case-insensitive sorting of strings in a list? Is it
 necessary to convert strings read from a plaintext file
 to Unicode? If so, how? This is Python 2.7.8.

Well, if you have non-ASCII chars for many Unicode characters str.lower()
won't give reasonable results. So binary strings containing an encoding of
Unicode character entities should be decoded to Unicode strings first.

Ciao, Michael.

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


Re: Case-insensitive sorting of strings (Python newbie)

2015-01-23 Thread Chris Angelico
On Sat, Jan 24, 2015 at 4:53 AM, Peter Otten __pete...@web.de wrote:
 Now the same with unicode. To read text with a specific encoding use either
 codecs.open() or io.open() instead of the built-in (replace utf-8 with your
 actual encoding):

 import io
 for line in io.open(tmp.txt, encoding=utf-8):
 ... line = line.strip()
 ... print line, line.lower()

In Python 3, the built-in open() function sports a fancy encoding=
parameter like that.

for line in open(tmp.txt, encoding=utf-8):

If you can, I would recommend using Python 3 for all this kind of
thing. The difference may not be huge, but there are all sorts of
little differences here and there that mean that Unicode support is
generally better; most of it stems from the fact that the default
quoted string literal is a Unicode string rather than a byte string,
which means that basically every function ever written for Py3 has
been written to be Unicode-compatible.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive sorting of strings (Python newbie)

2015-01-23 Thread Chris Angelico
On Sat, Jan 24, 2015 at 6:14 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 Well, if Python can't, then who can? Probably nobody in the world, not
 generically, anyway.

 Example:

  print(re\u0301sume\u0301)
 résumé
  print(r\u00e9sum\u00e9)
 résumé
  print(re\u0301sume\u0301 == r\u00e9sum\u00e9)
 False
  print(\ufb01nd)
 find
  print(find)
 find
  print(\ufb01nd == find)
 False

 If equality can't be determined, words really can't be sorted.

Ah, that's a bit easier to deal with. Just use Unicode normalization.

 print(unicodedata.normalize(NFC,re\u0301sume\u0301) == 
 unicodedata.normalize(NFC,r\u00e9sum\u00e9))
True

It's a bit verbose, but if you're doing a lot of comparisons, you
probably want to make a key-function that folds together everything
that you want to be treated the same way, for instance:

def key(s):
Normalize a Unicode string for comparison purposes.

Composes, case-folds, and trims excess spaces.

return unicodedata.normalize(NFC,s).strip().casefold()

Then it's much tidier:

 print(key(re\u0301sume\u0301) == key(r\u00e9sum\u00e9))
True
 print(key(\ufb01nd) == key(find))
True

You may want to go further, too; for search comparisons, you'll want
to use NFKC normalization, and probably translate all strings of
Unicode whitespace into single U+0020s, or completely strip out
zero-width non-breaking spaces (and maybe zero-width breaking spaces,
too), etc, etc. It all depends on what you mean by equality. But
certainly a basic NFC or NFD normalization is safe for general work.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive sorting of strings (Python newbie)

2015-01-23 Thread Marko Rauhamaa
Peter Otten __pete...@web.de:

 The standard recommendation is to convert bytes to unicode as early as
 possible and only manipulate unicode.

Unicode doesn't get you off the hook (as you explain later in your
post). Upper/lowercase as well as collation order is ambiguous. Python
even with decent locale support can't be expected to do it all for you.

Well, if Python can't, then who can? Probably nobody in the world, not
generically, anyway.

Example:

 print(re\u0301sume\u0301)
résumé
 print(r\u00e9sum\u00e9)
résumé
 print(re\u0301sume\u0301 == r\u00e9sum\u00e9)
False
 print(\ufb01nd)
find
 print(find)
find
 print(\ufb01nd == find)
False

If equality can't be determined, words really can't be sorted.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


python newbie

2014-06-18 Thread Maura E Monville
My supervisor has palmed me off with a python code, written by a collaborator, 
which implements an algorithm aimed at denoising the dose distribution (energy 
per unit mass) output from a radiation transport Monte Carlo code.
My task is to translate the python code into a MatLab code.
A colleague of mine and I stared at the python code for a while without 
understanding the logic. 
To me that code looks like Chinese or Arabian.
I don't have clear ideas about the syntax and python variables. For instance, 
in MatLab there is the cell array storage type to host data of different type. 
I have no idea how a 3D matrix can be loaded through python.
Does a debugger exist for python code ?
Is there an easy concise user's manual ?

Thank you in advance for any help.
Regards,
maura

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


Re: python newbie

2014-06-18 Thread Steven D'Aprano
On Wed, 18 Jun 2014 05:10:03 -0700, Maura E Monville wrote:

 My supervisor has palmed me off with a python code, written by a
 collaborator, which implements an algorithm aimed at denoising the dose
 distribution (energy per unit mass) output from a radiation transport
 Monte Carlo code. My task is to translate the python code into a MatLab
 code. A colleague of mine and I stared at the python code for a while
 without understanding the logic. To me that code looks like Chinese or
 Arabian. I don't have clear ideas about the syntax and python variables.
 For instance, in MatLab there is the cell array storage type to host
 data of different type. I have no idea how a 3D matrix can be loaded
 through python. Does a debugger exist for python code ? Is there an easy
 concise user's manual ?


If you don't understand how to even read Python code, using a debugger 
isn't going to help you.

Start by spending an hour or two to go through the tutorial, to get up to 
speed with the basic principles of the syntax:

https://docs.python.org/2/tutorial/

If you're using Python 3, you should use this instead:

https://docs.python.org/3/tutorial/


Although there aren't very many differences between the versions, when 
you're learning something for the first time, those differences can be 
perplexing.

Once you've done that, you'll be better able to ask sensible questions 
about your code. Feel free to show us your code (especially snippets) if 
there is anything unclear.



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


Re: python newbie

2014-06-18 Thread Maura E Monville
On Wednesday, June 18, 2014 1:50:54 PM UTC+1, Steven D'Aprano wrote:
 On Wed, 18 Jun 2014 05:10:03 -0700, Maura E Monville wrote:
 
 
 
  My supervisor has palmed me off with a python code, written by a
 
  collaborator, which implements an algorithm aimed at denoising the dose
 
  distribution (energy per unit mass) output from a radiation transport
 
  Monte Carlo code. My task is to translate the python code into a MatLab
 
  code. A colleague of mine and I stared at the python code for a while
 
  without understanding the logic. To me that code looks like Chinese or
 
  Arabian. I don't have clear ideas about the syntax and python variables.
 
  For instance, in MatLab there is the cell array storage type to host
 
  data of different type. I have no idea how a 3D matrix can be loaded
 
  through python. Does a debugger exist for python code ? Is there an easy
 
  concise user's manual ?
 
 
 
 
 
 If you don't understand how to even read Python code, using a debugger 
 
 isn't going to help you.
 
 
 
 Start by spending an hour or two to go through the tutorial, to get up to 
 
 speed with the basic principles of the syntax:
 
 
 
 https://docs.python.org/2/tutorial/
 
 
 
 If you're using Python 3, you should use this instead:
 
 
 
 https://docs.python.org/3/tutorial/
 
 
 
 
 
 Although there aren't very many differences between the versions, when 
 
 you're learning something for the first time, those differences can be 
 
 perplexing.
 
 
 
 Once you've done that, you'll be better able to ask sensible questions 
 
 about your code. Feel free to show us your code (especially snippets) if 
 
 there is anything unclear.
 
 
 
 
 
 
 
 -- 
 
 Steven

Thank you so much.
I am pretty sure you'll have to put up with my naive questions for a while. The 
python code though is not long.
Best regards,
Maura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python newbie

2014-06-18 Thread Jim Gibson
In article fa433710-0953-4b4a-96f6-2f7d1b9af...@googlegroups.com,
Maura E Monville maura.monvi...@gmail.com wrote:

 My supervisor has palmed me off with a python code, written by a
 collaborator, which implements an algorithm aimed at denoising the dose
 distribution (energy per unit mass) output from a radiation transport Monte
 Carlo code.
 My task is to translate the python code into a MatLab code.

Interestingly, I was recently given the task of translating a Matlab
program into Python. Just the opposite of your problem. And I knew
neither!

 A colleague of mine and I stared at the python code for a while without
 understanding the logic. 
 To me that code looks like Chinese or Arabian.
 I don't have clear ideas about the syntax and python variables. For instance,
 in MatLab there is the cell array storage type to host data of different
 type. I have no idea how a 3D matrix can be loaded through python.

Does the Python program use scipy and numpy modules? Those, in my short
experience, provide the closest equivalent to Matlab matrices and
functions. They allowed me to do almost a line-by-line translation of
Matlab code into Python. The h5py module allows you to read and write
Matlab save files in Python, too.

Some of the differences between Matlab and Python:

1. Matlab array indexing starts at 1; Python starts at 0.
2. Matlab uses parentheses () for sequence indexing; Python uses
brackets [].
3. Matlab arrays are column-major order; Numpy arrays are row-major
order,

Post Python code here or provide a link to code posted elsewhere for
additional help.

Good luck.

-- 
Jim Gibson
-- 
https://mail.python.org/mailman/listinfo/python-list


Total Python Newbie needs geting started info.

2013-11-20 Thread Ev J
I am learning Python and wish to develop GUI applications to run on Windows.
I have installed the Visual Studio integrated shell (Ver. 12.0.21005.1 REL) IDE 
and the Python 3.3 interpreter. I have gone through some of the 3.3 tutorial 
available at http://docs.python.org/3.3/tutorial/.

The tutorial is all about using the interactive interrupter and writing little 
console programs to learn the language.

Before I go too far down this road, I need to know if I can/should use this 
environment to develop GUI applications.  Is there graphical support for this - 
for example I can I just insert/move/set properties of buttons, combo boxes, 
etc. using an interface like the one in VBA?

If not, what is the best free IDE for me to use?
What is the best tutorial for the IDE?

I am a bit overwhelmed as to how to get started.

Thanks for any help.

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


Re: Total Python Newbie needs geting started info.

2013-11-20 Thread Chris Angelico
On Thu, Nov 21, 2013 at 3:03 AM, Ev J shorepoin...@gmail.com wrote:
 Before I go too far down this road, I need to know if I can/should use this 
 environment to develop GUI applications.  Is there graphical support for this 
 - for example I can I just insert/move/set properties of buttons, combo 
 boxes, etc. using an interface like the one in VBA?

Yes, you most certainly can. In the Microsoft world, you get a
language and its one GUI toolkit as a package deal; but in most of the
rest of the world, they're quite separate. Python can be used with
GTK, wx, TK, and a variety of other GUI toolkits; I happen to quite
like GTK, which I also use with Pike, a quite different language, and
can also be used with C and various other languages. So you can get to
know Python, and then later on choose one of several GUI toolkits, and
figure out how you want to lay out your window from there. The
tutorial sticks with the console because it's simple and easy to work
with; adding a GUI adds extra complexity, which can be left for later.

I don't know how much of an interface like VBA you'll get, but there
are graphical window builders. Personally, I don't use them; but if
you want them, they do exist.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Total Python Newbie needs geting started info.

2013-11-20 Thread Alister
On Thu, 21 Nov 2013 03:14:44 +1100, Chris Angelico wrote:

 On Thu, Nov 21, 2013 at 3:03 AM, Ev J shorepoin...@gmail.com wrote:
 Before I go too far down this road, I need to know if I can/should use
 this environment to develop GUI applications.  Is there graphical
 support for this - for example I can I just insert/move/set properties
 of buttons, combo boxes, etc. using an interface like the one in VBA?
 
 Yes, you most certainly can. In the Microsoft world, you get a language
 and its one GUI toolkit as a package deal; but in most of the rest of
 the world, they're quite separate. Python can be used with GTK, wx, TK,
 and a variety of other GUI toolkits; I happen to quite like GTK, which I
 also use with Pike, a quite different language, and can also be used
 with C and various other languages. So you can get to know Python, and
 then later on choose one of several GUI toolkits, and figure out how you
 want to lay out your window from there. The tutorial sticks with the
 console because it's simple and easy to work with; adding a GUI adds
 extra complexity, which can be left for later.
 
 I don't know how much of an interface like VBA you'll get, but there
 are graphical window builders. Personally, I don't use them; but if you
 want them, they do exist.
 
 ChrisA

Glade works quite well for GTK
I believe there is a WX version as well although i have never used it
i am not sure about gt or tk




-- 
Consensus Terrorism:
The process that decides in-office attitudes and behavior.
-- Douglas Coupland, Generation X: Tales for an 
Accelerated
   Culture
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Total Python Newbie needs geting started info.

2013-11-20 Thread Rod Person

On 11/20/2013 11:03 AM, Ev J wrote:

I am learning Python and wish to develop GUI applications to run on Windows.
I have installed the Visual Studio integrated shell (Ver. 12.0.21005.1 REL) IDE 
and the Python 3.3 interpreter. I have gone through some of the 3.3 tutorial 
available at http://docs.python.org/3.3/tutorial/.

The tutorial is all about using the interactive interrupter and writing little 
console programs to learn the language.

Before I go too far down this road, I need to know if I can/should use this 
environment to develop GUI applications.  Is there graphical support for this - 
for example I can I just insert/move/set properties of buttons, combo boxes, 
etc. using an interface like the one in VBA?

If not, what is the best free IDE for me to use?
What is the best tutorial for the IDE?

I am a bit overwhelmed as to how to get started.

Thanks for any help.


The integrated shell for Visual Studio does not give you the drag and drop GUI 
builder like is available for VB or C#.

I would say for a newbie you at Eric IDE:
 http://eric-ide.python-projects.org/

It uses the QT widget set and intergrated with QTBuilder to allow you to design 
GUI via dragging and dropping components.

There are other GUI builders like GLADE for gtk, but QtBuilder is probably the 
closes to what you would be familiar with from using Visual Studio.


--
Rod

So little pains do the vulgar take in the investigation of truth, accepting 
readily the first story that comes to hand.
  -Thucydides
  History of The Peloponnesian War, 432BC

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


Re: Total Python Newbie needs geting started info.

2013-11-20 Thread Christopher Welborn

On 11/20/2013 10:03 AM, Ev J wrote:

I am learning Python and wish to develop GUI applications to run on Windows.
I have installed the Visual Studio integrated shell (Ver. 12.0.21005.1 REL) IDE 
and the Python 3.3 interpreter. I have gone through some of the 3.3 tutorial 
available at http://docs.python.org/3.3/tutorial/.

The tutorial is all about using the interactive interrupter and writing little 
console programs to learn the language.

Before I go too far down this road, I need to know if I can/should use this 
environment to develop GUI applications.  Is there graphical support for this - 
for example I can I just insert/move/set properties of buttons, combo boxes, 
etc. using an interface like the one in VBA?

If not, what is the best free IDE for me to use?
What is the best tutorial for the IDE?

I am a bit overwhelmed as to how to get started.

Thanks for any help.





+1 for GTK. It takes a minute to get used to coming from a VB background 
(VB spoils people with its easy GUI builder). You write your own signal 
handlers with GTK (and other GUI libs also), instead of having it 
'auto-created' along with the button when its dropped. You also learn a 
lot more. Qt and Wx look good, I just don't have any experience with 
them. Glade for GTK is a very good GUI builder, but again, coming from 
VB it's not what you think. It only generates a glade file (XML-like 
file containing the layout for the GUI), but it's up to you to fill in 
the actual code. The process is something like this:


Build a gui with glade and save it.

Load .glade file in your python code. (builder.add_from_file(myfile))
(where builder is a Gtk.Builder())

Grab objects from it. (self.button1 = builder.get_object('Button1'))
(where Button1 is the name of a GtkButton in the glade file.)

Write signal handlers. (def button1_clicked_cb(self, btn):)
(signal names can be defined in glade)

Connect signals (builder.connect_signals(self))
(where self is a class containing the signal handlers)


I'm no expert at it, but I really like using it. There are different 
approaches and styles for using Gtk, so don't think my 'process' is set 
in stone. Someone else here may have a different view. The great thing 
about Gtk is the amount of control you have over everything. Large 
projects may require a different style than small ones.

--

- Christopher Welborn cjwelb...@live.com
  http://welbornprod.com

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


Re: Python newbie trying to embed in C++

2013-02-28 Thread Marwan Badawi

On 27/02/2013 10:26, Ian Kelly wrote:

On Wed, Feb 27, 2013 at 1:51 AM, Marwan lar...@free.fr wrote:

When I run the generated exe, I get errors about the functions not
existing...

TestPython.exe test Hello
AttributeError: 'module' object has no attribute 'Hello'
Cannot find function Hello


test is the name of a module in the standard library.  My guess
would be that for some reason it's importing that module rather than
your test.py.  Make sure that test.py can be found on your sys.path,
and perhaps change the name of your module to reduce confusion.

I just noticed that my reply went to the message sender and not to the 
newsgroup, so I'm posting again: thanks, that was it. Just renaming my 
test.py file solved the problem.


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


Re: Python newbie trying to embed in C++

2013-02-28 Thread Marwan Badawi

On 27/02/2013 16:17, Christian Gollwitzer wrote:

Am 27.02.13 09:51, schrieb Marwan:

And I'd appreciate it if you could give me pointers to how to easily
call Python from C++.


Maybe you can use boost::python?

http://www.boost.org/doc/libs/1_53_0/libs/python/doc/

Cave: I haven't used it and don't know if it is up-to-date.

 Christian

I just noticed that my reply went to the message sender and not to the 
newsgroup, so I'm posting again: thanks, I'll look into that.


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


Re: Python newbie trying to embed in C++

2013-02-28 Thread Gisle Vanem

Marwan Badawi marwan.bad...@inria.fr wrote:

I just noticed that my reply went to the message sender and not to the 
newsgroup, so I'm posting again: thanks, I'll look into that.


Yes, I often do that too; i.e. I'm subscribed to python-list@python.org
and get all messages from comp.lang.python mirrored to the ML a bit later.
I prefer the mailing-list over comp.lang.python since my NNTP server
(eternal-september.org) is rather slow and my ISP has deprecated NNTP 
long time ago. 


I saw you uses Thunderbird on Windows. I'm not sure how it by default handles
a reply-to when there is no Reply-to field in the header. To the address in 
From / Sender or what? 


I wish the NNTP-mailing list gateway could add a Reply-to: 
python-list@python.org.
Since I'm getting the messages via the ML, I think it would be logical that the replies 
should by default go to the ML too.


--gv



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


Re: Python newbie trying to embed in C++

2013-02-28 Thread Michael Torrie
On 02/28/2013 03:47 AM, Gisle Vanem wrote:
 I saw you uses Thunderbird on Windows. I'm not sure how it by default handles
 a reply-to when there is no Reply-to field in the header. To the address in 
 From / Sender or what? 

Thunderbird has a handy, reply to list button that works every time no
matter what the rely-to field is set to.

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


Python newbie trying to embed in C++

2013-02-27 Thread Marwan

Hello all,

I'm new to Python and just starting to learn it. For he needs of my 
project, I need to call some specific methods in Python scripts from C++.


For now, I just compiled the example in the Python documentation about 
Pure Embedding to try it out ( 
http://docs.python.org/2/extending/embedding.html#pure-embedding ).


I'm trying to test it on an extremely simple script called test.py which 
contains the following:


def testPY( value ):
   print('You input ', value )

 def Hello():
print('Hello')


When I run the generated exe, I get errors about the functions not 
existing...


TestPython.exe test Hello
AttributeError: 'module' object has no attribute 'Hello'
Cannot find function Hello


My Python version is 2.7.3 because that's the version used in the module 
we need to access. And I'm using VS2010 SP1 for compiling my C++ because 
that's the version used to generate our DLLs and EXEs.


Could anyone tell me why this is happening?

And I'd appreciate it if you could give me pointers to how to easily 
call Python from C++.


Thanks in advance for your help,

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


Re: Python newbie trying to embed in C++

2013-02-27 Thread Ian Kelly
On Wed, Feb 27, 2013 at 1:51 AM, Marwan lar...@free.fr wrote:
 When I run the generated exe, I get errors about the functions not
 existing...

 TestPython.exe test Hello
 AttributeError: 'module' object has no attribute 'Hello'
 Cannot find function Hello

test is the name of a module in the standard library.  My guess
would be that for some reason it's importing that module rather than
your test.py.  Make sure that test.py can be found on your sys.path,
and perhaps change the name of your module to reduce confusion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie trying to embed in C++

2013-02-27 Thread Christian Gollwitzer

Am 27.02.13 09:51, schrieb Marwan:

And I'd appreciate it if you could give me pointers to how to easily
call Python from C++.


Maybe you can use boost::python?

http://www.boost.org/doc/libs/1_53_0/libs/python/doc/

Cave: I haven't used it and don't know if it is up-to-date.

Christian

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


Re: Python newbie trying to embed in C++

2013-02-27 Thread Terry Reedy

On 2/27/2013 3:51 AM, Marwan wrote:

Hello all,

I'm new to Python and just starting to learn it. For he needs of my
project, I need to call some specific methods in Python scripts from C++.

For now, I just compiled the example in the Python documentation about
Pure Embedding to try it out (
http://docs.python.org/2/extending/embedding.html#pure-embedding ).

I'm trying to test it on an extremely simple script called test.py which
contains the following:

def testPY( value ):
print('You input ', value )

  def Hello():
 print('Hello')


I hope that the second def is not really indented in your original ;-).


When I run the generated exe, I get errors about the functions not
existing...

TestPython.exe test Hello
AttributeError: 'module' object has no attribute 'Hello'
Cannot find function Hello

My Python version is 2.7.3 because that's the version used in the module


The windows 2.7 on python.org is compiled with VS2008.


we need to access. And I'm using VS2010 SP1 for compiling my C++ because
that's the version used to generate our DLLs and EXEs.


Mixing VS compilers can be a problem, though I don't know if that is the 
case here. Even if not, it might be for your real application.


You can try compiling 2.7.3 (or later from repository) with vs2010. I 
know people have tried it. I presume it has been done. I don't know if 
there is an (unofficial) vs2010 project file in the repository.


Python.org 3.3 *is* compiled with 2010. You can also try running the 
module with that, possibly with the help of 2to3. It might not take too 
work. The author of the module might be interested in a port anyway, 
though maybe not. Or maybe extract just the part of the module you need 
for conversion.


You might start with 3.3 for your tests and initial learning to make 
sure that compiler mismatch is not a factor. When you get that to work, 
then decide what to do.


I suppose the worst alternative might be to regenerate all the needed 
dlls and exes with 2008.


--
Terry Jan Reedy

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


Re: Python Newbie

2013-02-26 Thread Larry Hudson

On 02/24/2013 02:43 PM, piterrr.dolin...@gmail.com wrote:
snip

...  But for the moment I am trying to imitate familiar ground.

snip
This is EXACTLY why you're having trouble grasping Python.  Python is a different language and 
requires a different mind-set and different approach.  In this, it is NO different from ANY 
other new (to you) programming language.


Of course, don't forget general programming principles -- how to approach a problem, how to 
select algorithms, and such.  These apply to any language, but the details of syntax and such 
ARE different in different languages.  Trying to apply these old details to a new language only 
hinders your learning process, it definitely does NOT help.


Actually, your comments and questions make me wonder HOW you are trying to learn Python.  All 
the things you're asking about are clearly and completely discussed in any decent book or 
tutorial.  It makes me speculate that you're simply trying to use a Python reference instead of 
something that actually teaches anything.  A reference may give you the rules and syntax, but 
not much about how to apply them properly.


Please think about finding some better fundamental material -- there is a LOT available.  And 
please quit trying to force Python to be something it isn't.  That is never going to be 
effective and definitely harmful to your learning.


snip

I wanted Python to register what type of variable I'm after...


Python variables do NOT have any data type.  The objects they reference have data types. 
Variables can be assigned and RE-assigned to any data type at any time.  Again, I emphasize, 
QUIT THINKING IN ANOTHER LANGUAGE, it simply doesn't work.  You might like it if it were so, but 
it simply does not match reality.


 -=- Larry -=-

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


Re: Python Newbie

2013-02-26 Thread Matej Cepl
On 2013-02-23, 15:51 GMT, Chris Angelico wrote:
 When you learn your first language, you think you're learning to
 program, but that's not really accurate. Once you've learned half a
 dozen, you begin to understand something of the art of coding as
 distinct from any particular language; after that, you can learn any
 language fairly easily.

And then you find out that to be REALLY good in one language, you 
have to focus on one language, because otherwise you are writing 
in some kind of mishmash. The point is that you don’t need to 
know any language but to at home in the whole universe of 
libraries, idioms, patterns, etc. and if you can manage to be 
REALLY at home in more than one (or let’s say two) universes, you 
are better than most (professional programmers) I know.

Shakespeare wasn’t good in writing German poetry, as far as 
I know.

Matěj
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-26 Thread Matej Cepl
On 2013-02-23, 18:44 GMT, jmfauth wrote:
 Very easy to explain: wrong, incorrect, naive unicode
 handling.

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


Re: Python Newbie

2013-02-26 Thread rurpy
On 02/26/2013 01:32 AM, Larry Hudson wrote:
 On 02/24/2013 02:43 PM, piterrr.dolin...@gmail.com wrote:
 snip
 ...  But for the moment I am trying to imitate familiar ground.
 snip
 This is EXACTLY why you're having trouble grasping Python.  Python is a 
 different language and 
 requires a different mind-set and different approach.  In this, it is NO 
 different from ANY 
 other new (to you) programming language.

No.  Programming languages have far more in common with other 
languages than differences.  This is particularly true of Python 
which has always seemed to me as a very well-selected compilation 
of existing programming language features rather than consisting 
of groundbreaking new concepts. 

 Of course, don't forget general programming principles -- how to approach a 
 problem, how to 
 select algorithms, and such.  These apply to any language, but the details of 
 syntax and such 
 ARE different in different languages.  Trying to apply these old details to a 
 new language only 
 hinders your learning process, it definitely does NOT help.
 
 Actually, your comments and questions make me wonder HOW you are trying to 
 learn Python.  All 
 the things you're asking about are clearly and completely discussed in any 
 decent book or 
 tutorial.  It makes me speculate that you're simply trying to use a Python 
 reference instead of 
 something that actually teaches anything.  A reference may give you the rules 
 and syntax, but 
 not much about how to apply them properly.

That is sadly true of the Python reference manuals (Language 
and Library) but need not and should not be true in general.  
There is no reason why someone with basic programming experience
in another similar language should not be able to learn a new 
language from its *well written* reference manuals.

 Please think about finding some better fundamental material -- there is a LOT 
 available.  And 
 please quit trying to force Python to be something it isn't.  That is never 
 going to be 
 effective and definitely harmful to your learning.

Part of learning, indeed much of the value in learning, a new 
language when one already knows several others, is mentally 
unifying the things that are similar in the old and new languages,
and distinguishing what is different.

You do NOT need to throw out everything you learned about those
other language to learn new one.  Thinking of the features of the 
new language in terms of the old one is a necessary part of this
process.  I still think in terms of C pointers when thinking 
about how Python references objects.  The problem arises when
when one assumes that syntax that looks similar *should* behave 
similarly.

As for migrating idioms from the previous language to the new
one, such as adding redundant parenthesis around the conditional
expression in an if statement, I think it is relatively
harmless.  Contrary to previous claims, it will NOT result
in an unmaintainable mess.  I doubt if any maintainabilty 
difference in such code could even be measured other than that
caused by a prima-donna-ish eew, I'm not going to work on
that code because I think it is UGLY! effect.  Perhaps if
we were talking about a program manager setting such idioms
in stone for 100's of kilolines of code it would be different
but for the OPs situation, I see no harm in it.
If it helps the OP transition to python, then I say do it.

For the record, I did much the same thing coming to Python from
Perl.  After a while I came to the common view that such parens
were more noise than clarifying but I reached that conclusion 
based on my own experience rather than being bludgeoned into
it by extreme predictions of doom read here.

 snip
 I wanted Python to register what type of variable I'm after...
 
 Python variables do NOT have any data type.  The objects they reference have 
 data types. 
 Variables can be assigned and RE-assigned to any data type at any time.  
 Again, I emphasize, 
 QUIT THINKING IN ANOTHER LANGUAGE, it simply doesn't work.  You might like it 
 if it were so, but 
 it simply does not match reality.

I have no problem interpreting the OP's statement (as quoted 
above) as meaning that he wanted to use a Python variable to 
consistently reference a particular type and wanted a name 
that would remind him of that type. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-26 Thread Jean-Michel Pichavant

- Original Message -
 Hi guys,
 
 Question. Have this code
 
 intX = 32  # decl + init int var
 intX_asString = None   # decl + init with NULL string var
 
 intX_asString = intX.__str__ ()# convert int to string
 
 What are these ugly underscores for?
 _str___
 
 Peter
 --
 http://mail.python.org/mailman/listinfo/python-list

I can't wait for the 

intX_asString_asBool = intX_asString.__bool__()

if (intX_asString_asBool == True):
  # do something 

;-)

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-26 Thread Ethan Furman

On 02/26/2013 10:23 AM, ru...@yahoo.com wrote:

On 02/26/2013 01:32 AM, Larry Hudson wrote:

Python variables do NOT have any data type.


I have no problem interpreting the OP's statement
as meaning that he wanted to use a Python variable to
consistently reference a particular type and wanted a name
that would remind him of that type.


Which is all well and good, so long as the OP also realizes that the name does not have any restriction's on it from 
Python's side, and certain functions will end up pointing the name at a different object with a possibly different type 
than his original, as in my int/float example.


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


Re: Python Newbie

2013-02-26 Thread Piterrr
Jean-Michel Pichavant jeanmic...@sequans.com wrote in message 
news:mailman.2567.1361905815.2939.python-l...@python.org...


- Original Message -

Hi guys,

Question. Have this code

intX = 32  # decl + init int var
intX_asString = None   # decl + init with NULL string var

intX_asString = intX.__str__ ()# convert int to string

What are these ugly underscores for?
_str___

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


I can't wait for the

intX_asString_asBool = intX_asString.__bool__()

if (intX_asString_asBool == True):
 # do something

;-)

JM


As serious a character as I am, I had good laughs at this. Don't you all 
like my questions for all the exitainment they offer?


The __str__ issue was a genuine question. I'm glad to find there is also a 
__bool_ () method, shall I need it. :-) Please note, this is not how I write 
my code. I'm not that bad a programmer, it's just Python which is so 
different that I am doing what I need to help clarify things and help me 
out.


I don't find this post offensive, even though JM is deliberately making fun 
of me. But to his credit, it is funny indeed. Let's laugh 2gether!


This reminds me, when I first started working with databases and saw an 
error msg which said that my query had ambiguous columns I laughed for 1/2 
hr. I found it incredibly exitaining that a 100% deterministic piece of 
hardware could have the word ambiguous in its internal dictionary.


:-))

Peter 


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


Re: Python Newbie

2013-02-26 Thread Chris Angelico
On Wed, Feb 27, 2013 at 6:42 AM, Piterrr piotr...@optonline.net wrote:
 This reminds me, when I first started working with databases and saw an
 error msg which said that my query had ambiguous columns I laughed for 1/2
 hr. I found it incredibly exitaining that a 100% deterministic piece of
 hardware could have the word ambiguous in its internal dictionary.

Enjoy your laugh (laughter's good!), but there are a couple of wrong
assumptions here. The hardware doesn't use the word ambiguous, and
the SQL engine (which is what does) isn't 100% deterministic. Or to be
more technically correct, it's 100% deterministic with such a large
set of inputs (many of which are outside your access, let alone
control) that it may as well have a random component.  Also, there's
nothing strange about ambiguity: Go and get the cornflour and the
icing sugar. Put some of it into the cake mix. - what should you put
in? Some of each? That's what the database has been asked to do, and
it's not clear what should be done.

Sorry to be the wet blanket on your joke (I think that metaphor's as
mixed as cake batter), but facts is facts :)

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


Re: Python Newbie

2013-02-26 Thread rurpy
On Tuesday, February 26, 2013 11:59:51 AM UTC-7, Ethan Furman wrote:
 On 02/26/2013 10:23 AM, ru...@yahoo.com wrote:
  On 02/26/2013 01:32 AM, Larry Hudson wrote:
  Python variables do NOT have any data type.
  I have no problem interpreting the OP's statement
  as meaning that he wanted to use a Python variable to
  consistently reference a particular type and wanted a name
  that would remind him of that type.
 
 Which is all well and good, so long as the OP also realizes
 that the name does not have any restriction's on it from 
 Python's side, and certain functions will end up pointing
 the name at a different object with a possibly different type 
 than his original, as in my int/float example.

Which I presume he did, given that he responded to your post with:

On Sunday, February 24, 2013 5:08:06 PM UTC-7, piterrr@gmail.com wrote:
[...]
 Yes I did see that it is possible to redefine the type of a variable.
 But I don't think I would ever do this intentionally; need to be really 
 careful with Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-25 Thread Serhiy Storchaka

On 24.02.13 17:52, Chris Angelico wrote:

By the way, when you're asking a completely new question, it usually
helps to do so as a brand new thread (not a reply) and with a new
subject line. Otherwise, you risk people losing the new question among
the discussion of the old.


You risk people losing your answer when you're answering such question.

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


Re: Python Newbie

2013-02-25 Thread Nick Mellor
Hi Piterr,

It's interesting how strong our habits are, isn't it? It's most likely you've 
just got a bit of culture shock.

I've used C# quite a bit as well as Python. I like them both.

What I like about Python is how it manages to be clear and terse at the same 
time.

if (flag==1) {
code
}

has quite a bit of redundancy in it (C or C#.) In Python:

if flag:
code

is a good shorthand that matches any non-zero value. Gone are the brackets and 
the braces and the meaning is crystal clear.

In the middle of a complex piece of code this clarity of syntax is fantastic 
for anyone reading the code-- so long as they know how Python works.

You may discover as you continue with Python that there is actually quite a lot 
of freedom about how you use white space. Python doesn't much care *how* much 
you indent, just that you're consistent within the block:

if flag:
# do something
# do something else
# continue coding after the if stmt

is equivalent to

if flag:
  # do something
  # do something else
# continue coding after the if stmt

You're also allowed to break a line inside brackets, braces etc and use any 
indenting you like:

if flag:
[o.process(i % 3 + w)
 for i, o, w
 in enumerate(zip(objects, words))
]
# do something else
# this is after the if block

The following is a good thread about implied line continuation (i.e. where 
line breaks and free indentation are allowed inside braces, square brackets or 
round brackets.)

http://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python

See also the Python style guide:

http://www.python.org/dev/peps/pep-0008/

There's also explicit line continuation, rather like Visual Basic:

if c + \
256 * \
(d + 256 * e)  69427:
   # do something
   # do something else
# then leave the if block

Again, the line continuation doesn't mind what indent you use after it.

In this case you could put brackets around the expression and use implied line 
continuation:

if (c +
256 *
(d + 256 * e))  69427:
   # do something
   # do something else
# then leave the if block

This is the preferred method according to the Python style guide.

I hope you manage to give Python (and your job) a little longer to charm you
:-)

Cheers,

Nick

On Friday, 22 February 2013 08:26:41 UTC+11, Piterrr  wrote:
 Hi folks.
 
 I am a long time C sharp dev, just learning Python now due to job 
 requirements. My initial impression is that Python has got to be the most 
 ambiguous and vague language I have seen to date. I have major issues with 
 the fact that white space matters. How do you deal with this? For example, 
 you open a source file in different editors and the indentation levels change 
 even though i only have spaces, no tabs (compare Windows Notepad and 
 Notepad++). Which editor do you trust? In addition, code is difficult to read 
 because you cannot lay it out in easily discernable blocks. For example, I 
 always tend to indent a full 'if' statement block so that it is easier to see 
 where the if block starts and ends. Can't do that in Python. What is even 
 more frustrating is that Python is inconsistent with its syntax. For example, 
 when I write if (myVariable != 0): then this is OK but for (i in intAry): 
 results in syntax error. Apparently Python has problems with my use of 
 parentheses. How retarded. 
 I think I will rather find another job than eat my nerves with Python.
 
 Any comments on this before I quit my job?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Vito De Tullio
piterrr.dolin...@gmail.com wrote:

 You see, Javascript, for one, behaves the same way as Python (no variable
 declaration) but JS has curly braces and you know the variable you have
 just used is limited in scope to the code within the { }. With Python, you
 have to search the whole file.

I don't know if you know javascript, but I think your experience with it is 
limited, as you listed two of of the many common pitfalls of javascript:

javascript has optional variable declaration, but if you don't declare a 
variable (such as a local variable in a function) it binds itself in the 
global scope;

in c/c++/c#/java... curly braces define a new scope, in javascript no.

if you do in javascript

function foo() {
if (some condition) {
   a = 'something';
}

alert(a);
}

the moment you call the foo() function (and some condition is true), a 
global variable a is created. (this time you *really* need to search not 
the whole .js file, but the whole project, as there is no file-level 
globals in javascript)

if you instead use the 'var' keyword to define explicitly a local variable

function foo() {
if (some condition) {
   var a = 'something';
}

alert(a);
}

while you don't create a global variable, the a variable is still 
accessible outside the if braces.

this is the reason most javascript linters (most notably jslint) force the 
first statement of every function to be the definition of all function 
variables.



by this point of view, python and javascript have the same philosophy, but 
at least python doesn't allow implicit global variable definition


-- 
ZeD


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


Re: Python Newbie

2013-02-24 Thread Mark Lawrence

On 24/02/2013 04:20, Larry Hudson wrote:

On 02/23/2013 03:46 PM, piterrr.dolin...@gmail.com wrote:

Hi all,


snip

... I have discovered today there is no do...while type loop. [Sigh]


No biggie.  This is easily simulated with:

while True:
 ...
 if exit condition:
 break

Less easily simulated is the lack of a switch/case structure.  This has
to be done with a less convenient extended if/elif/.../else structure.


Or a dict, there are umpteen recipes showing how to do this.




Peter



  -=- Larry -=-


--
Cheers.

Mark Lawrence

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


Re: Python Newbie

2013-02-24 Thread piterrr . dolinski
Hi guys,

Question. Have this code

intX = 32  # decl + init int var
intX_asString = None   # decl + init with NULL string var

intX_asString = intX.__str__ ()# convert int to string

What are these ugly underscores for? _str___

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


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 2:46 AM,  piterrr.dolin...@gmail.com wrote:
 Hi guys,

 Question. Have this code

 intX = 32  # decl + init int var
 intX_asString = None   # decl + init with NULL string var

 intX_asString = intX.__str__ ()# convert int to string

 What are these ugly underscores for? _str___

Normally you don't need them. Write it this way:

intX_asString = str(intX)

The dunder methods (double underscore, leading and trailing),
also called magic methods, are the implementations of various
special features. For instance, indexing foo[1] is implemented using
the __getitem__ method. Here's a list:

http://docs.python.org/3.3/reference/datamodel.html#special-method-names

You'll seldom, if ever, call these methods directly.

By the way, when you're asking a completely new question, it usually
helps to do so as a brand new thread (not a reply) and with a new
subject line. Otherwise, you risk people losing the new question among
the discussion of the old.

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


Re: Python Newbie

2013-02-24 Thread Roy Smith
In article mailman.2410.1361721167.2939.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

 The dunder methods (double underscore, leading and trailing),
 also called magic methods, are the implementations of various
 special features. For instance, indexing foo[1] is implemented using
 the __getitem__ method. Here's a list:
 
 http://docs.python.org/3.3/reference/datamodel.html#special-method-names
 
 You'll seldom, if ever, call these methods directly.

On the other hand, once you get into building your own classes, you will 
often be *writing* them.  The most common are __str__(), __repr__(), and 
__unicode__(), and of course, __init__().

A quick look over my current project shows 471 classes, and I've defined:

  1 __del__
  1 __getattr__
  1 __iter__
  1 __new__
  2 __cmp__
  2 __len__
  3 __ne__
  4 __contains__
  9 __eq__
 14 __str__
 38 __unicode__
 62 __repr__
140 __init__

Not to mention the boilerplate:

if __name__ == '__main__:

which shows up all over the place.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Mark Lawrence

On 22/02/2013 21:37, piterrr.dolin...@gmail.com wrote:


if (some statement):# short form

rather than

if (some statement == true):# long form



What all those ugly brackets are for?


Peter



--
Cheers.

Mark Lawrence

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


Re: Python Newbie

2013-02-24 Thread Steven D'Aprano
On Sun, 24 Feb 2013 07:46:07 -0800, piterrr.dolinski wrote:

 Hi guys,
 
 Question. Have this code
 
 intX = 32  # decl + init int var
 intX_asString = None   # decl + init with NULL string var
 
 intX_asString = intX.__str__ ()# convert int to string
 
 What are these ugly underscores for?
 _str___


To demonstrate that the person who wrote this code was not a good Python 
programmer. I hope it wasn't you :-) This person obviously had a very 
basic, and confused, understanding of Python.

And, quite frankly, was probably not a very good programmer of *any* 
language:

- poor use of Hungarian notation for variable names;
- pointless pre-declaration of values;
- redundant comments that don't explain anything.

If that code came from the code-base you are maintaining, no wonder you 
don't think much of Python! That looks like something I would expect to 
see at the DailyWTF.

http://thedailywtf.com/


The above code is better written as:

x = 32
x_asString = str(x)


Double-underscore methods are used for operator overloading and 
customizing certain operations, e.g. __add__ overloads the + operator. 
You might define a class with a __str__ method to customize converting 
the object to a string:

# Toy example.
class MyObject:
def __str__(self):
return This is my object


But you would not call the __str__ method directly. (I won't say never, 
because there are rare, advanced, uses for calling double-underscore 
methods directly.) You would use a public interface, such as the str() 
function.


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


Re: Python Newbie

2013-02-24 Thread Michael Torrie
On 02/24/2013 10:37 AM, Dennis Lee Bieber wrote:
   Decided to look up the VAX/VMS scheme...
 
 
 If you know the condition code for a message, you can use F$MESSAGE to
 translate the code to its associated message. For example:
 $ WRITE SYS$OUTPUT F$MESSAGE(%X0001)
 %SYSTEM-S-NORMAL, normal successful completion
 
 
   VMS used a status of 1 for normal success (which implies that all
 the odd integers were success/info messages, even integers would be
 warning/error/fatal.
 
 http://h71000.www7.hp.com/doc/73final/documentation/pdf/ovms_msg_ref_al.pdf

It's interesting to note that Windows NT sort of descends from VMS.  I
guess the end result was an unholy blend of VMS and CP/M.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Roy Smith
In article mailman.2420.1361728619.2939.python-l...@python.org,
 Michael Torrie torr...@gmail.com wrote:

 It's interesting to note that Windows NT sort of descends from VMS.

More than sort of.  Dave Cutler was the chief architect of both.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Grant Edwards
On 2013-02-23, Chris Angelico ros...@gmail.com wrote:

 It's worth noting, though, that there are self-perpetuating aspects to
 it. I can happily distribute a .py file to a Linux audience, because
 many Linux distros come with a Python already installed, or at very
 least can grab one easily via the package manager.

Are there any popular, mainstream Linux distros that don't come with
Python installed by default?

RedHat has had Python installed as part of the base system since day
1, since both the installer and some of the system admin stuff was
written in Python.  I always thought RPM also originally written in
Python, but can't find any references.  In any case, yum is written in
Python, so I doubt there are any RPM-based distros that don't have
Python as part of a base install.

Python is required by Gentoo, since the package management tools are
written (at least partially) in Python.  In theory, it might be
possible to do an install tha doesn't include Python by using a
different package-management system, but in practice Python is always
there on Gentoo systems.

All of the Debian systems I've seen had Python installed, but I'm not
sure how required it is.

AFAICT, Python is installed as part of all Ubuntu installations as
well.

-- 
Grant Edwards   grant.b.edwardsYow! Did you move a lot of
  at   KOREAN STEAK KNIVES this
  gmail.comtrip, Dingy?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread piterrr . dolinski
 To demonstrate that the person who wrote this code was not a good Python 
 
 programmer. I hope it wasn't you :-) This person obviously had a very 
 
 basic, and confused, understanding of Python.
 
 
 
 And, quite frankly, was probably not a very good programmer of *any* 
 
 language:
 
 
 
 - poor use of Hungarian notation for variable names;
 
 - pointless pre-declaration of values;
 
 - redundant comments that don't explain anything.
 
 
 
 If that code came from the code-base you are maintaining, no wonder you 
 
 don't think much of Python! That looks like something I would expect to 
 
 see at the DailyWTF.

Hi. Steve, I don't know where you have been over the past couple of days but it 
is widely known (if the thread title is any indication) that I am indeed very 
new to Python, but not new to programming in general.

To give a bit of background where I found __str__, I am using a Python IDE 
called PyScripter. Its Intellisense is full of methods starting and ending with 
__, hence the question.

Regarding Hungarian notation, I don't use it in any other language but Python 
and JS. Call it poor, but it helps me to remember what type a variable is. The 
redundant comments serve the same purpose. As for pointless predeclaration, 
it helps me know where in the code I first started using the variable, so I 
know there are no references to it before then.

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


Re: Python Newbie

2013-02-24 Thread piterrr . dolinski
  if (some statement):# short form
 
  rather than
 
  if (some statement == true):# long form
 
 
 What all those ugly brackets are for?
 

Mark,

Back in the day when C was king, or take many newer long established languages 
(C#, Java), the use of () has been widespread and mandated by the compilers. I 
have never heard anyone moan about the requirement to use parentheses. Now come 
Python in which parens are optional, and all of a sudden they are considered 
bad and apparently widely abandoned. Do you really not see that code with 
parens is much more pleasing visually? I could understand someone's reluctance 
to use parens if they are very new to programming and Pythons is their first 
language. But my impression here is that most group contributors are long-time 
programmers and have long used () where they are required. Again, I'm really 
surprised the community as a whole ignores the programming heritage and dumps 
the parens in a heartbeat.

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


Re: Python Newbie

2013-02-24 Thread Mitya Sirenef

On 02/24/2013 02:40 PM, piterrr.dolin...@gmail.com wrote:

if (some statement): #  short form


 rather than

 if (some statement == true): # long form


 What all those ugly brackets are for?


 Mark,

 Back in the day when C was king, or take many newer long established
 languages (C#, Java), the use of () has been widespread and mandated
 by the compilers. I have never heard anyone moan about the requirement
 to use parentheses. Now come Python in which parens are optional, and
 all of a sudden they are considered bad and apparently widely
 abandoned. Do you really not see that code with parens is much more
 pleasing visually? I could understand someone's reluctance to use
 parens if they are very new to programming and Pythons is their first
 language. But my impression here is that most group contributors are
 long-time programmers and have long used () where they are required.
 Again, I'm really surprised the community as a whole ignores the
 programming heritage and dumps the parens in a heartbeat.

 Peter


When I write in English, I write: If it rains, I'll get an umbrella.
I do not write: If (it rains), I'll get an umbrella. The second example
isn't any clearer. The only reason you like unneeded parens is that
you're used to them. I've never heard of anyone missing this feature
after a month or two of using Python.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The world is a perpetual caricature of itself; at every moment it is the
mockery and the contradiction of what it is pretending to be.
George Santayana

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


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 5:19 AM, Grant Edwards invalid@invalid.invalid wrote:
 On 2013-02-23, Chris Angelico ros...@gmail.com wrote:

 It's worth noting, though, that there are self-perpetuating aspects to
 it. I can happily distribute a .py file to a Linux audience, because
 many Linux distros come with a Python already installed, or at very
 least can grab one easily via the package manager.

 Are there any popular, mainstream Linux distros that don't come with
 Python installed by default?

Probably all the main desktop distros come with _some_ Python (but not
necessarily a recent one... RHEL with 2.4?!). I used many rather
than all in case there's one somewhere that doesn't, but even then,
Python will be an easily-added feature.

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


Re: Python Newbie

2013-02-24 Thread Michael Ross

On Sun, 24 Feb 2013 20:40:05 +0100, piterrr.dolin...@gmail.com wrote:


 if (some statement):   # short form

 rather than

 if (some statement == true):   # long form


What all those ugly brackets are for?



Mark,

Back in the day when C was king, or take many newer long established  
languages (C#, Java), the use of () has been widespread and mandated by  
the compilers. I have never heard anyone moan about the requirement to  
use parentheses.


You've never heard me then. I ... strongly dislike having to parse  
visual elements which I consider superfluous and implicit.


Does the English language have a proverb like not being able to see the  
forest for the trees?


To me, a C source looks like all brackets. Can't see the code for all the  
brackets.



Now come Python in which parens are optional, and all of a sudden they  
are considered bad and apparently widely abandoned. Do you really not  
see that code with parens is much more pleasing visually?


I guess one can get just as religious about the brackets as one can about  
the whitespace.



if ( condition ) { action }
vs
if condition: action


In time estimated, I'd say I can read and understand Python code about 20%  
faster than any of these brackety languages, even compared to languages I  
worked a with couple of years longer. That's a lot of effort saved.




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


Re: Python Newbie

2013-02-24 Thread MRAB

On 2013-02-24 19:40, piterrr.dolin...@gmail.com wrote:

if (some statement):# short form

rather than

if (some statement == true):# long form



What all those ugly brackets are for?



Mark,

Back in the day when C was king, or take many newer long established
languages (C#, Java), the use of () has been widespread and mandated
by the compilers. I have never heard anyone moan about the
requirement to use parentheses. Now come Python in which parens are
optional, and all of a sudden they are considered bad and apparently
widely abandoned. Do you really not see that code with parens is much
more pleasing visually? I could understand someone's reluctance to
use parens if they are very new to programming and Pythons is their
first language. But my impression here is that most group
contributors are long-time programmers and have long used () where
they are required. Again, I'm really surprised the community as a
whole ignores the programming heritage and dumps the parens in a
heartbeat.


Some languages require parentheses, others don't.

C does. C++, Java and C# are descended from, or influenced by, C.

Algol didn't (doesn't?). Pascal, Modula-2, Oberon, Ada, and others
don't.

Parentheses are used where required, but not used where they're not
required, in order to reduce visual clutter.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 7:34 AM, MRAB pyt...@mrabarnett.plus.com wrote:
 Some languages require parentheses, others don't.

 C does. C++, Java and C# are descended from, or influenced by, C.

 Algol didn't (doesn't?). Pascal, Modula-2, Oberon, Ada, and others
 don't.

 Parentheses are used where required, but not used where they're not
 required, in order to reduce visual clutter.

And just to muddy the waters, parens are used in Python when the
condition goes over a line break:

if (condition1
and condition2
and condition3):

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


Re: Python Newbie

2013-02-24 Thread Mark Lawrence

On 24/02/2013 19:40, piterrr.dolin...@gmail.com wrote:

if (some statement):# short form

rather than

if (some statement == true):# long form



What all those ugly brackets are for?



Mark,

Back in the day when C was king, or take many newer long established languages (C#, 
Java), the use of () has been widespread and mandated by the compilers. I have never 
heard anyone moan about the requirement to use parentheses. Now come Python in which 
parens are optional, and all of a sudden they are considered bad and apparently widely 
abandoned. Do you really not see that code with parens is much more pleasing visually? I 
could understand someone's reluctance to use parens if they are very new to programming 
and Pythons is their first language. But my impression here is that most group 
contributors are long-time programmers and have long used () where they are required. 
Again, I'm really surprised the community as a whole ignores the programming 
heritage and dumps the parens in a hea
  rtbeat.

Peter



Your words the use of () has been widespread and mandated by the 
compilers and have long used () where they are required.  As they are 
neither mandated nor required in Python it just wastes the time of 
anybody reading code as they have to parse something that offers nothing 
except visual noise.  As for being visually pleasing that's simply 
laughable.  I want to be able to read code, not hang it in an art gallery.


--
Cheers.

Mark Lawrence

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


Re: Python Newbie

2013-02-24 Thread Ethan Furman

On 02/24/2013 11:40 AM, piterrr.dolin...@gmail.com wrote:

Back in the day when C was king, or take many newer long established languages (C#, 
Java), the use of () has been widespread and mandated by the compilers. I have never 
heard anyone moan about the requirement to use parentheses. Now come Python in which 
parens are optional, and all of a sudden they are considered bad and apparently widely 
abandoned. Do you really not see that code with parens is much more pleasing visually? I 
could understand someone's reluctance to use parens if they are very new to programming 
and Pythons is their first language. But my impression here is that most group 
contributors are long-time programmers and have long used () where they are required. 
Again, I'm really surprised the community as a whole ignores the programming 
heritage and dumps the parens in a heartbeat.


Python will also allow you to have ';' at the end of your lines.  It does nothing for you, but perhaps you also find 
that visually pleasing?


I find () to be four extra keystrokes, not visually pleasing, and needed only 
to override order of operations.

One of the things I love about Python is its ability to get out of the way and 
let me work:

  - no variable declarations, just use 'em
  - no type declarations, just use 'em
  - no need to remember what's an object and what's not -- everything is an 
object
  - no need to cast to bool as everything has a truthy/falsey (something vs 
nothing) value


From a different email you said PyScripter was showing you all the dunder methods?  You might want to try one of the 
others.


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


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 7:34 AM, Ethan Furman et...@stoneleaf.us wrote:
 One of the things I love about Python is its ability to get out of the way
 and let me work:

   - no variable declarations, just use 'em
   - no type declarations, just use 'em
   - no need to remember what's an object and what's not -- everything is an
 object
   - no need to cast to bool as everything has a truthy/falsey (something vs
 nothing) value

Variable declarations can go either way; Python requires you to name
all globals that you mutate, and to be careful when working with
nested functions. With declared variables, you name all locals, and
can enforce scoping and destructors without language features like
'with'. Both options are viable.

I absolutely agree with your third point. Treat 'em all as objects!
But of *course*, Java is more object oriented than Python. Everyone
knows that.

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


Re: Python Newbie

2013-02-24 Thread Roy Smith
In article mailman.2434.1361738581.2939.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

 On Mon, Feb 25, 2013 at 7:34 AM, MRAB pyt...@mrabarnett.plus.com wrote:
  Some languages require parentheses, others don't.
 
  C does. C++, Java and C# are descended from, or influenced by, C.
 
  Algol didn't (doesn't?). Pascal, Modula-2, Oberon, Ada, and others
  don't.
 
  Parentheses are used where required, but not used where they're not
  required, in order to reduce visual clutter.
 
 And just to muddy the waters, parens are used in Python when the
 condition goes over a line break:
 
 if (condition1
 and condition2
 and condition3):
 
 ChrisA

That could also be written:

if condition1 \
   and condition2 \
   and condition3:

but as a practical matter, I would write it in the parens style, if for 
no other reason than because emacs does a better job of auto-indenting 
it that way :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Roy Smith
In article mailman.2438.1361739512.2939.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

  no need to remember what's an object and what's not -- everything is an
  object

Well, not quite everything.  If I write:

if foo:
   do_this()
   and_this()

the code block making up the body of the if statement is not an 
object.  In some languages, it is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 19:29, piterrr.dolin...@gmail.com wrote:

 Hi. Steve, I don't know where you have been over the past couple of days
 but it is widely known (if the thread title is any indication) that I am
 indeed very new to Python, but not new to programming in general.

 To give a bit of background where I found __str__, I am using a Python IDE
 called PyScripter. Its Intellisense is full of methods starting and ending
 with __, hence the question.

 Regarding Hungarian notation, I don't use it in any other language but
 Python and JS. Call it poor, but it helps me to remember what type a
 variable is.


If you can't remember what type a variable is, you're doing something
incorrectly.


 The redundant comments serve the same purpose.


To help you remember the type of the variable?

 intX = 32  # decl + init int var
How is it not obvious that intX is an integer *without* the comment?

 X = 32
How is it not obvious that X is an integer?

 intX_asString = None   # decl + init with NULL string var
How is it not obvious that intX_asString is an integer (it starts with
int, duh... oh wait)

The comment says it's the NULL string, so it's . F*ck.

It's None. Why? No idea.

 intX_asString = intX.__str__ ()# convert int to string
Wait. So why'd you write the previous line?

Just write:
 X_as_string = str(X)
'Cause str *always* returns a string. So it's a string. How is that not
obvious?


But then, what's the context?

X is a *useless* name. Why are you converting X to a string? I have no
idea. The problem with the code isn't that you could be overwriting X.
The problem is that your code is contradictory, pretends it's C, has
useless names and doesn't try to be readable.


 As for pointless predeclaration, it helps me know where in the code I
 first started using the variable, so I know there are no references to it
 before then.


Why? Why can't you overwrite old variables? Why can't a variable change
type? If your functions are so large that you're likely to lose track of
what's defined, you have a different problem indeed.


For example:
def floatA_floatB_floatC_to_tupleR(floatA, floatB, floatC): # decl with
floatA, floatB, floatC parameters
floatD = None # decl + init with NULL float var
floatD = ((floatB ** 2) - (4 * floatA * floatC)) # set to B² - 4AC
floatD = floatD ** 0.5 # set to √floatD

floatR1 = None # decl + init with NULL float var
floatR1 = (((- floatB) + floatD) / (2 * floatA)) # set to (-B+D)/(2A)

floatR2 = None # decl + init with NULL float var
floatR2 = (((- floatB) - floatD) / (2 * floatA)) # set to (-B-D)/(2A)

return (floatR1, floatR2)

Versus

def solve_quadratic(a, b, c):
Solve a quadratic equation of the form ax² + bx + c = 0

The result will be a tuple of the two results; the results can be equal if
the determinant is 0.
This supports imaginary results for if the determinant is negative.

# The method used is the quadratic equation:
# http://en.wikipedia.org/wiki/Quadratic_equation

# b² - 4ac
determinant = b**2 - 4*a*c

# ±√(b² - 4ac)
 sqrt_determinant = determinant ** 0.5
squareroots = sqrt_determinant, -sqrt_determinant

 # -b ± √(b² - 4ac)
fraction_tops = [(-b + d) for d in squareroots]

results = [top/(2*a) for top in fraction_tops]

return results

Which is easier to read? Reading through it you don't just suddenly forget
what the type of determinant is (which must be a number because it's a
determinant) or results (which is a container since it's plural). The
names tell you.

The useful comments such as The method used is... and ±√(b² - 4ac) give
you context, too, which is a lot more than can be said of
floatA_floatB_floatC_to_tupleR. For that, I tried to emulate what I saw
in your code.

I'm not a good programmer. But because of that the code I write makes
sense, so I can understand it. Tell the reader what they want to know, not
what they see.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 20:48, Roy Smith r...@panix.com wrote:

 In article mailman.2434.1361738581.2939.python-l...@python.org,
  Chris Angelico ros...@gmail.com wrote:

  On Mon, Feb 25, 2013 at 7:34 AM, MRAB pyt...@mrabarnett.plus.com
 wrote:
   Some languages require parentheses, others don't.
  
   C does. C++, Java and C# are descended from, or influenced by, C.
  
   Algol didn't (doesn't?). Pascal, Modula-2, Oberon, Ada, and others
   don't.
  
   Parentheses are used where required, but not used where they're not
   required, in order to reduce visual clutter.
 
  And just to muddy the waters, parens are used in Python when the
  condition goes over a line break:
 
  if (condition1
  and condition2
  and condition3):
 
  ChrisA

 That could also be written:

 if condition1 \
and condition2 \
and condition3:

 but as a practical matter, I would write it in the parens style, if for
 no other reason than because emacs does a better job of auto-indenting
 it that way :-)


Pah,

condition1 = long_condition_expression_1
condition2 = long_condition_expression_2
condition3 = long_condition_expression_3

if condition1 and condition2 and condition3:
STUFF

No multiline needed. If you have *many* conditions, then:

supercondition = all(
condition1,
condition2,
condition3,
condition4,
condition5,
condition6,
condition7,
condition8,
condition9
) # or equiv.

if supercondition:
STUFF


Reason:
Indentation should be *really simple*.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 8:35 AM, Joshua Landau
joshua.landau...@gmail.com wrote:
 def solve_quadratic(a, b, c):
 Solve a quadratic equation of the form ax² + bx + c = 0

 The result will be a tuple of the two results; the results can be equal if
 the determinant is 0.
 This supports imaginary results for if the determinant is negative.
 ...
 results = [top/(2*a) for top in fraction_tops]

Yeah, I think we know which one is the more readable... Just to
nit-pick a little though, that returns a list when its docstring says
it'll return a tuple :)

Other than that (which is probably better solved by changing the docs
than the code), the only change I'd make would be to ditch the
fraction_tops temporary (and to throw out some of the comments that
serve only to reexpress the code that immediately follows them, though
for a demo they're entirely appropriate). Even in a language with
mandatory declarations, the code would look pretty similar:

# Assume that the declaration 'complex' permits a float - otherwise
you need a Pike-style piped declaration eg float|complex
# Details elided for brevity, keep the docstring and comments from the
above version
list(complex) solve_quadratic(float a, float b, float c):
float determinant = b**2 - 4*a*c
complex sqrt_determinant = determinant ** 0.5
tuple(complex) squareroots = sqrt_determinant, -sqrt_determinant
return [(-b + d)/(2*a) for top in squareroots]

Variable names seldom if ever need to identify their types, if by
type you mean what the language sees as a type. There are times when
it's useful to adorn a variable name with a unit, perhaps (length_ft
and height_m shouldn't be multiplied together), or some other special
marker (a tainted flag on all data that's come from user input, and
which therefore must not be executed or interpolated into SQL or
anything), but this is a much higher level of abstraction.

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


Re: Python Newbie

2013-02-24 Thread Mitya Sirenef

On 02/24/2013 04:44 PM, Chris Angelico wrote:

On Mon, Feb 25, 2013 at 8:08  AM, Roy Smith r...@panix.com wrote:

 In article mailman.2438.1361739512.2939.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

 no need to remember what's an object and what's not -- everything 
is an

 object

 Careful on the citations - Ethan Furman said that, I just quoted him.

 Well, not quite everything. If I write:

 if foo:
 do_this()
 and_this()

 the code block making up the body of the if statement is not an
 object. In some languages, it is.

 Maybe, but the code of an entire function *is*. Granted, it's not an
 object that can be built up manually (at least, not that I know of),
 and it offers only limited functionality (dis.dis, but not a lot
 else), so really it could be seen as just an implementation detail of
 the function object itself. But it's still an object.

 ChrisA


But if block doesn't have to be inside a function, right? It needs
to be inside a module, but then again everything is inside a module, but
it wouldn't be very object-oriented if the module was the only object in
Python :-).

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The press, the machine, the railway, the telegraph are premises whose
thousand-year conclusion no one has yet dared to draw.  Friedrich Nietzsche

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


Re: Python Newbie

2013-02-24 Thread Ethan Furman

On 02/24/2013 12:58 PM, Chris Angelico wrote:

On Mon, Feb 25, 2013 at 7:34 AM, Ethan Furman et...@stoneleaf.us wrote:


   - no variable declarations, just use 'em


Variable declarations can go either way; Python requires you to name
all globals that you mutate


I'm not sure what you mean -- example?

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


Re: Python Newbie

2013-02-24 Thread piterrr . dolinski
Josh,

Not thank you for your malicious post.
I think you are missing the point here.

My source code was just a dummy to offer context for the question I wanted to 
ask. Further down the line, if I ever feel I don't need to pseudo-declare 
variables I will stop doing it. But for the moment I am trying to imitate 
familiar ground.

My code as written has no syntax errors, so what's the problem? It is highly 
unlikely you will ever read any of my Python code - no need to get excited over 
a few of my lines.

And you don't need to answer questions which were not posed, thank you.

I wanted Python to register what type of variable I'm after. So I init my vars 
accordingly, int might be 0, float 0.0 and string with null, err... None.

In practice, I wouldn't define an intX_asString var, I would do str (num) 
every time a string representation is needed, provided it isn't a loop, as in 
that context the expression would probably negatively impact performance in an 
interpreted language.

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


Re: Python Newbie

2013-02-24 Thread Dave Angel

On 02/24/2013 10:46 AM, piterrr.dolin...@gmail.com wrote:

Hi guys,

Question. Have this code

intX = 32  # decl + init int var
intX_asString = None   # decl + init with NULL string var


None is not a str, and it's not a NULL string var   Perhaps what you 
want is intX_asString = 


 I am using a Python IDE called PyScripter. Its Intellisense is full
 of methods starting and ending with __, hence the question.

I'm surprised;  I'd expect the Intellisense to filter those out by 
default, since people seldom should call them.


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


Re: Python Newbie

2013-02-24 Thread Joel Goldstick
On Sun, Feb 24, 2013 at 5:43 PM, piterrr.dolin...@gmail.com wrote:

 Josh,

 Not thank you for your malicious post.
 I think you are missing the point here.

 My source code was just a dummy to offer context for the question I wanted
 to ask. Further down the line, if I ever feel I don't need to
 pseudo-declare variables I will stop doing it. But for the moment I am
 trying to imitate familiar ground.

 My code as written has no syntax errors, so what's the problem? It is
 highly unlikely you will ever read any of my Python code - no need to get
 excited over a few of my lines.

 And you don't need to answer questions which were not posed, thank you.

 I wanted Python to register what type of variable I'm after. So I init my
 vars accordingly, int might be 0, float 0.0 and string with null, err...
 None.


In a language that defines Names that are bound to objects, there can't be
a 'type' inferred.  In C or similar, when you delcair the variable you are
setting aside the memory to hold something of that type.  This is compile
time typing.  That isn't how python works, so naming something an int will
never make it an int.  intMe = 'Joel' is totally valid in python.

Sticking to ideas like this will hinder understanding of how python works.
I suggest taking two hours to study the python documentation at python.org.
I don't speak Chinese, but I know that I can't just use a dictionary of
English to Chinese and use the same syntax.  It won't be Chinese.

Get over your prejudice and learn the new language or don't, but trying
to shoe horn python into the concepts of another language won't help you
understand python, it will produce ugly, messy, unsupportable code.


 In practice, I wouldn't define an intX_asString var, I would do str
 (num) every time a string representation is needed, provided it isn't a
 loop, as in that context the expression would probably negatively impact
 performance in an interpreted language.

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




-- 
Joel Goldstick
http://joelgoldstick.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 22:43, piterrr.dolin...@gmail.com wrote:

 Josh,

 Not thank you for your malicious post.


Be careful, us programmers do *eventually* catch on to who is a troll, and
if you say things like that we may eventually mark you off as just to
hostile.
I *honestly* meant no malice or insult. If you can't take my word, you can
point out what I said that was otherwise.

(Then again, you'll have about a week before we really start to notice :P)


 I think you are missing the point here.

 My source code was just a dummy to offer context for the question I wanted
 to ask. Further down the line, if I ever feel I don't need to
 pseudo-declare variables I will stop doing it. But for the moment I am
 trying to imitate familiar ground.

 My code as written has no syntax errors, so what's the problem? It is
 highly unlikely you will ever read any of my Python code - no need to get
 excited over a few of my lines.


You said Any comments on this before I quit my job?.

I commented on how I think you should approach Python in order to
appreciate its virtues rather than get stuck in its differences. Again, I
am no good programmer, but I think these methods will help you.


 And you don't need to answer questions which were not posed, thank you.


Nor do I need to answer questions which were posed.


 I wanted Python to register what type of variable I'm after. So I init my
 vars accordingly, int might be 0, float 0.0 and string with null, err...
 None.


You seem to think that a null version of a type is the falsy version.
Then:
int - 0
float - 0.
tuple - ()
list - []

And then (*dun dun duuun!*):

str -  (NOT None, which is a different type)

Other people have commented on whether this is a good idea (it's not), so
I'll suggest you read those, too.

In practice, I wouldn't define an intX_asString var, I would do str (num)
 every time a string representation is needed, provided it isn't a loop, as
 in that context the expression would probably negatively impact performance
 in an interpreted language.


PS: Guess what str(None) is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 22:08, Chris Angelico ros...@gmail.com wrote:

 On Mon, Feb 25, 2013 at 8:35 AM, Joshua Landau
 joshua.landau...@gmail.com wrote:
  def solve_quadratic(a, b, c):
  Solve a quadratic equation of the form ax² + bx + c = 0
 
  The result will be a tuple of the two results; the results can be equal
 if
  the determinant is 0.
  This supports imaginary results for if the determinant is negative.
  ...
  results = [top/(2*a) for top in fraction_tops]

 Yeah, I think we know which one is the more readable... Just to
 nit-pick a little though, that returns a list when its docstring says
 it'll return a tuple :)


Good catch.


 Other than that (which is probably better solved by changing the docs
 than the code), the only change I'd make would be to ditch the
 fraction_tops temporary (and to throw out some of the comments that
 serve only to reexpress the code that immediately follows them, though
 for a demo they're entirely appropriate).


I knew someone would critique it. It's an exaggerated demo for foo's sake.
Heck, who even uses a function like that (or uses unicode in comments :P)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 24 February 2013 23:18, Oscar Benjamin oscar.j.benja...@gmail.comwrote:

 On 24 February 2013 21:35, Joshua Landau joshua.landau...@gmail.com
 wrote:
 
  determinant = b**2 - 4*a*c

 It's called the discriminant. A determinant is something altogether
 different.


*cries at own idiocy*

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


Re: Python Newbie

2013-02-24 Thread Albert Hopkins


 Most of what gets hung in art galleries these days is far less
 visually pleasing than well-written code.

+1 QOTW
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread piterrr . dolinski

 intX = 32  # decl + init int var
 How is it not obvious that intX is an integer *without* the comment?

Indeed the assignment is enough to deduce intX is an int. The comment is 
there to let me know it is unlikely intX appears earlier in the code. Please, 
let me do things my way until I find reasons to the contrary.

Regarding my use of None to mean NULL, point taken to use  instead.

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


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 9:33 AM, Ethan Furman et...@stoneleaf.us wrote:
 On 02/24/2013 12:58 PM, Chris Angelico wrote:

 On Mon, Feb 25, 2013 at 7:34 AM, Ethan Furman et...@stoneleaf.us wrote:


- no variable declarations, just use 'em


 Variable declarations can go either way; Python requires you to name
 all globals that you mutate


 I'm not sure what you mean -- example?

Whoops, said the wrong thing. All globals that you assign to.

 a=1
 b=[]
 def foo(x):
y=x+1
global a
a+=x
b.append(y) 
 foo(2)
 a
3
 b
[3]

Python requires that you name 'a' in a global statement; C would
require a declaration for 'y' to make it local. PHP, meanwhile, would
require declarations for both a and b.

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


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 10:38 AM,  piterrr.dolin...@gmail.com wrote:

 intX = 32  # decl + init int var
 How is it not obvious that intX is an integer *without* the comment?

 Indeed the assignment is enough to deduce intX is an int. The comment is 
 there to let me know it is unlikely intX appears earlier in the code. Please, 
 let me do things my way until I find reasons to the contrary.

 Regarding my use of None to mean NULL, point taken to use  instead.

It's worth noting that None does make a good rendition of
null-as-opposed-to-blank, for instance when you're fetching data
from an VARCHAR field in an SQL database. You'd use a string for
anything that isn't NULL, and None for the others.

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


Re: Python Newbie

2013-02-24 Thread Ethan Furman

On 02/24/2013 03:38 PM, piterrr.dolin...@gmail.com wrote:



intX = 32  # decl + init int var

How is it not obvious that intX is an integer *without* the comment?


Indeed the assignment is enough to deduce intX is an int. The comment is 
there to let me know it is unlikely intX appears earlier in the code. Please, let me do 
things my way until I find reasons to the contrary.


Of course you can, but wouldn't you rather find reasons to the contrary by us 
telling you, instead of tripping
over something yourself?

For example (I believe it's already been mentioned) declaring intX with some integer value does *nothing* to maintain 
X as an integer:


-- intX = 32
-- intX = intX / 3.0
-- intX
10.66

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


Re: Python Newbie

2013-02-24 Thread piterrr . dolinski
 For example (I believe it's already been mentioned) declaring intX with 
 some integer value does *nothing* to maintain 
 
 X as an integer:
 
 -- intX = 32
 
 -- intX = intX / 3.0
 
 -- intX
 
 10.66
 

Yes I did see that it is possible to redefine the type of a variable. But I 
don't think I would ever do this intentionally; need to be really careful with 
Python.

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


Re: Python Newbie

2013-02-24 Thread Joshua Landau
On 25 February 2013 00:08, piterrr.dolin...@gmail.com wrote:

  For example (I believe it's already been mentioned) declaring intX
 with some integer value does *nothing* to maintain
 
  X as an integer:
 
  -- intX = 32
 
  -- intX = intX / 3.0
 
  -- intX
 
  10.66
 

 Yes I did see that it is possible to redefine the type of a variable. But
 I don't think I would ever do this intentionally; need to be really careful
 with Python.


Not necessarily.

Python duck types. If you don't know what that means, Google's got a ton on
it.

Take a look at my really bad quadratic equation solver. It supports integer
input, float input and complex input. It will output a list of two floats
or complex numbers.

That's a use for having one variable have different types. You'll find
thousands of parallels in real, working code.

Hence, you don't really need to be careful. You'd probably benefit if you
stopped thinking of supporting type-changing as dangerous and started
thinking of it as useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Mark Lawrence

On 25/02/2013 00:08, piterrr.dolin...@gmail.com wrote:

For example (I believe it's already been mentioned) declaring intX with some 
integer value does *nothing* to maintain

X as an integer:

-- intX = 32

-- intX = intX / 3.0

-- intX

10.66



Yes I did see that it is possible to redefine the type of a variable. But I 
don't think I would ever do this intentionally; need to be really careful with 
Python.

Peter



Yes this is a big downside with Python.  Sadly it means us poor Python 
programmers have to waste a lot of time and effort testing our code, 
unlike those who use statically typed languages which work perfectly 
once they've been compiled.


--
Cheers.

Mark Lawrence

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


Re: Python Newbie

2013-02-24 Thread Ethan Furman

On 02/24/2013 04:08 PM, piterrr.dolin...@gmail.com wrote:

For example (I believe it's already been mentioned) declaring intX with some 
integer value does *nothing* to maintain

X as an integer:

-- intX = 32

-- intX = intX / 3.0

-- intX

10.66



Yes I did see that it is possible to redefine the type of a variable.


And that right there is one of the key aspects of Python:  there are no variables, only objects, and objects' types 
cannot be changed.  objects can be labeled with names, but the names are more like sticky notes, and can be peeled off 
and stuck on some other object.


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


Re: Python Newbie

2013-02-24 Thread Steven D'Aprano
On Sun, 24 Feb 2013 16:08:01 -0500, Roy Smith wrote:

 In article mailman.2438.1361739512.2939.python-l...@python.org,
  Chris Angelico ros...@gmail.com wrote:
 
  no need to remember what's an object and what's not -- everything is
  an object
 
 Well, not quite everything.  If I write:
 
 if foo:
do_this()
and_this()
 
 the code block making up the body of the if statement is not an
 object.  In some languages, it is.


In Python, that code block isn't any *thing*. It's merely a small part of 
the enclosing code block, which *is* an object.

When we say everything is an object in Python, we're talking about 
values, not arbitrary language constructs. The *3 bit of y = x*3 is 
not a value, a for-loop is not a value, and the delay you experience when 
you call time.sleep(30) is not a value, so none of these things are 
objects. This is not to reduce the importance of these things as 
programming concepts, but they aren't the kind of things we mean when we 
say everything is an object.


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


Re: Python Newbie

2013-02-24 Thread Roy Smith
In article mailman.2461.1361749985.2939.python-l...@python.org,
 Ethan Furman et...@stoneleaf.us wrote:

 On 02/24/2013 03:38 PM, piterrr.dolin...@gmail.com wrote:
 
  intX = 32  # decl + init int var
  How is it not obvious that intX is an integer *without* the comment?
 
  Indeed the assignment is enough to deduce intX is an int. The comment is 
  there to let me know it is unlikely intX appears earlier in the code. 
  Please, let me do things my way until I find reasons to the contrary.
 
 Of course you can, but wouldn't you rather find reasons to the contrary by us 
 telling you, instead of tripping
 over something yourself?
 
 For example (I believe it's already been mentioned) declaring intX with 
 some integer value does *nothing* to maintain 
 X as an integer:
 
 -- intX = 32
 -- intX = intX / 3.0
 -- intX
 10.66

I could imagine a getattr-based implementation of DBC (Design By 
Contract) which does use the variable name to enforce type.  Unclear if 
this is a Good Thing, a Bad Thing, or a just plain Crazy Thing.  In any 
cae, it would be a neat (if somewhat advanced) exercise for somebody 
interested in enforcing types and looking to explore some of the more 
arcane corners of Python.

class DBC_Example:
   # Ad-libbing this, code not tested
   def __setattr__(self, name, value):
  if name.startswith('int'):
 assert isinstance(value, int)
  self.__dict__[name] = value
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Oscar Benjamin
On 25 February 2013 00:08,  piterrr.dolin...@gmail.com wrote:
Chris Angelico wrote:
 For example (I believe it's already been mentioned) declaring intX with 
 some integer value does *nothing* to maintain

 X as an integer:

 -- intX = 32

 -- intX = intX / 3.0

 -- intX

 10.66


 Yes I did see that it is possible to redefine the type of a variable. But I 
 don't think I would ever do this intentionally; need to be really careful 
 with Python.

You do need to be careful around types in Python (as in all
languages). It took some time for me to understand how to use types in
Python. After a while I came to realise that not knowing exactly the
type of a particular object is not as much of a problem as I initially
thought. Once you understand how to use this ambiguity to your
advantage it becomes possible to write very flexible code that can be
reused without ambiguity in situations that you haven't yet
anticipated.

The key mental hurdle, I think, is to realise that instead of relying
on compilation errors to spot (a small subset of) your programming
errors, you are relying on runtime exceptions. Python still gives
errors when you use an object in a way that is inconsistent with its
type; you just don't see those errors at compile time.

The trickier cases are ones where two types are very similar and can
be used similarly in most, but not all, situations. An example of this
would be the one that Chris has highlighted where an object that you
expected to be an int is actually a float. I find that I need to be
careful when using division on quantities that I expected to be
integers (true in all languages) and careful about the notation used
in a numeric literal. Once you get used to it, you will find it easy
to see that the '.0' that Chris appended was deliberate in order to
control the type of the resulting object.


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


Re: Python Newbie

2013-02-24 Thread Roy Smith
In article da0ec7a1-decd-4cfb-9a0b-5722879f5...@googlegroups.com,
 piterrr.dolin...@gmail.com wrote:

 Yes I did see that it is possible to redefine the type of a variable. But I 
 don't think I would ever do this intentionally

One does not need language features to protect themselves against things 
they do intentionally.  They need language features to protect 
themselves against things they do by accident.  Different languages 
protect you from different things.

Compare, for example, C++ and Python.

C++ protects you against accidentally passing an int where you were 
supposed to pass a float.  Well, no, with automatic type promotion, 
that's a bad example.  But it does prevent you from passing an IntThing 
where you were supposed to pass a FloatThing (assuming IntThing is not a 
subclass of FloatThing, and a few other details).

But, Python protects you from dereferencing a null pointer, or 
double-freeing a pointer.  There's just no way to even write those 
concepts in Python.

You pays your money and you takes your chances.  Pick which type of 
protection you feel is more important and use the language which gives 
you that.

 need to be really careful with Python.

You need to be really careful with all programming languages.  You just 
need to be careful about different things.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Steven D'Aprano
On Sun, 24 Feb 2013 11:40:05 -0800, piterrr.dolinski wrote:

  if (some statement):   # short form
 
  rather than
 
  if (some statement == true):   # long form
 
 
 What all those ugly brackets are for?
 
 
 Mark,
 
 Back in the day when C was king, or take many newer long established
 languages (C#, Java),

Python is older than either C# or Java. Why have those languages paid no 
attention to the innovations of Python, instead of copying the 
misfeatures of C?

Pascal and Algol and Fortran are older than C. Why did C introduce 
unnecessary brackets when these older languages did not need them?


 the use of () has been widespread and mandated by
 the compilers. I have never heard anyone moan about the requirement to
 use parentheses.

You have not been paying attention.

In many ways, C has been a curse on programming. It has trained large 
numbers of coders to expect and *demand* poor syntax.


 Now come Python in which parens are optional, and all
 of a sudden they are considered bad and apparently widely abandoned. Do
 you really not see that code with parens is much more pleasing visually?

That's funny. Perhaps you should be programming in Lisp.


 I could understand someone's reluctance to use parens if they are very
 new to programming and Pythons is their first language. But my
 impression here is that most group contributors are long-time
 programmers and have long used () where they are required. Again, I'm
 really surprised the community as a whole ignores the programming
 heritage and dumps the parens in a heartbeat.

(Because they are unnecessary) (visual noise) (that don't add anything) 
(useful) (to the reader's understanding) (of the code).



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


Re: Python Newbie

2013-02-24 Thread Steven D'Aprano
On Sun, 24 Feb 2013 16:08:06 -0800, piterrr.dolinski wrote:

 For example (I believe it's already been mentioned) declaring intX
 with some integer value does *nothing* to maintain
 
 X as an integer:
 
 -- intX = 32
 
 -- intX = intX / 3.0
 
 -- intX
 
 10.66
 
 
 Yes I did see that it is possible to redefine the type of a variable.

Variables do not have types in Python.

Reset your thinking. Python is a dynamic language with name bindings and 
strongly-typed objects, not a static language with strongly-typed 
variables. If you don't understand the difference, ask. But so long as 
you make the wrong assumptions about the language, you will have a bad 
time.

You will find programming much easier, and more pleasant, if you learn 
the semantics and idioms of the language you are using, instead of trying 
to treat every language as the same.


 But I don't think I would ever do this intentionally; need to be really
 careful with Python.

Not at all. The only difference is whether you get a compiler error or a 
runtime error. Instead of:

10 Write code.
20 Compile.
30 If compiler error, GO TO 10.
40 REM code compiles, but it still needs to be tested
50 Test code.
60 If error, GO TO 10.
70 Deploy.

we have:

10 Write code.
20 Test code.
30 If error, GO TO 10.
40 Deploy.



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


Re: Python Newbie

2013-02-24 Thread Steven D'Aprano
On Sun, 24 Feb 2013 17:40:54 -0500, Mitya Sirenef wrote:

 But if block doesn't have to be inside a function, right? It needs to be
 inside a module, but then again everything is inside a module, but it
 wouldn't be very object-oriented if the module was the only object in
 Python :-).

Python doesn't have code blocks as distinct values. I suppose you could 
fake it using compile() and eval() by hand, but it wouldn't work very 
well.

Ruby-style code blocks have been requested for many years. GvR has given 
his support to this *in principle*, but it depends on somebody thinking 
up decent, unambiguous syntax that works with the rest of Python.


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


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 11:45 AM, Oscar Benjamin
oscar.j.benja...@gmail.com wrote:
 On 25 February 2013 00:08,  piterrr.dolin...@gmail.com wrote:
 Chris Angelico wrote:
 For example (I believe it's already been mentioned) declaring intX with 
 some integer value does *nothing* to maintain

 X as an integer:

 -- intX = 32

 -- intX = intX / 3.0

 -- intX

 10.66


 Yes I did see that it is possible to redefine the type of a variable. But I 
 don't think I would ever do this intentionally; need to be really careful 
 with Python.

 The trickier cases are ones where two types are very similar and can
 be used similarly in most, but not all, situations. An example of this
 would be the one that Chris has highlighted where an object that you
 expected to be an int is actually a float. I find that I need to be
 careful when using division on quantities that I expected to be
 integers (true in all languages) and careful about the notation used
 in a numeric literal. Once you get used to it, you will find it easy
 to see that the '.0' that Chris appended was deliberate in order to
 control the type of the resulting object.

Once again, Ethan gets the short end of the citations stick...
'twarn't me wrote that, he did. Not that it's at all contrary to my
views, and I might well have said it if he hadn't, but credit should
go his direction :)

Note though that in Python 3, you don't need the explicit .0 to force
it to float (and __future__ can bring that to Python 2 too). 32/3 -
10.6, int/int-float.

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


Re: Python Newbie

2013-02-24 Thread Chris Angelico
On Mon, Feb 25, 2013 at 12:04 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 Not at all. The only difference is whether you get a compiler error or a
 runtime error. Instead of:

 10 Write code.
 20 Compile.
 30 If compiler error, GO TO 10.
 40 REM code compiles, but it still needs to be tested
 50 Test code.
 60 If error, GO TO 10.
 70 Deploy.

 we have:

 10 Write code.
 20 Test code.
 30 If error, GO TO 10.
 40 Deploy.

The advantage of compile-time errors is that you don't have to wait
for *that branch* to be executed. So they're hugely advantageous when
it comes to the obvious problems like syntactic errors... and looky
here, Python does exactly that :) The only difference between static
and dynamic is how much is done at each phase.

If your program has no inputs or side effects, the compiler could
theoretically convert it into a single static output statement. Voila!
All your run-time errors have become compile-time errors. Conversely,
you could compile your application from source just before running it.
Voila! Everything's a run-time error, even the omission of a semicolon
in C. Okay, both of those are pretty stupid examples, but there's
really no fundamental difference.

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


Re: Python Newbie

2013-02-24 Thread Michael Torrie
On 02/24/2013 03:40 PM, Mitya Sirenef wrote:
 But if block doesn't have to be inside a function, right? It needs
 to be inside a module, but then again everything is inside a module, but
 it wouldn't be very object-oriented if the module was the only object in
 Python :-).

A module indeed fits into the OOP paradigm.  It's called a singleton and
I love the fact that I can define and use them in python without
wrapping them in tons of boilerplate class and factory code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Newbie

2013-02-24 Thread Michael Torrie
On 02/24/2013 06:04 PM, Steven D'Aprano wrote:
 Variables do not have types in Python.
 
 Reset your thinking. Python is a dynamic language with name bindings and 
 strongly-typed objects, not a static language with strongly-typed 
 variables. If you don't understand the difference, ask. But so long as 
 you make the wrong assumptions about the language, you will have a bad 
 time.

Yes, but according to my computer language theory class, strictly
speaking, python has no variables, only names and objects, which for the
most part aren't mutable.  A variable by definition is a box in memory
that you can write to.  The closest thing python has to that are
instances of mutable types like a list.

a=5 certainly doesn't allocate a box in memory somewhere and stick 5
in it.  And then later a += 1 or a=6 doesn't mutate the value stored
in the box represented by a.  Instead it allocates a new object and
makes a refer to that new object.

I know all this is what you meant, but with the original poster's
frustrations with python, it's important that he just throw out the
notion of variations entirely because sooner or later that will get him
in trouble here, like if he tries to make an empty list be a default
value for a function parameter.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   >