Re: [Tutor] problem with program

2017-10-13 Thread Mark Lawrence via Tutor

On 13/10/17 13:04, Chris Coleman wrote:

just learning python as my first programming language.  going through the
book "python in easy steps" by mike mcgrath.  i am going through the
programs in chapter 7 and can't get them to work.  here is the first one in
the chapter:
class Bird:
 '''A base class to define bird properties.'''
 count=0
 def_init_(self,chat):
 self.sound=chat
 Bird.count+=1
 def talk(self):
 return self.sound
from Bird import*
print('\nClass Instances Of:\n',Bird._doc_)
polly=Bird('Squawk,squawk!')
print('\nNumber Of Birds:',polly.count)
print('Polly Says:',polly.talk())
harry=Bird('Tweet,tweet!')
print('\nNumber Of Birds:',harry.count)
print('Harry Says:',harry.talk())

i am getting this error message:

File "scripts/bird.py", line 4
 def_init_(self,chat):


You need a space between the `def` and the `__init__`.


   ^
SyntaxError: invalid syntax

what am i doing or not doing that is causing this?




--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] coding help with maxwell-boltzmann distribution

2017-10-13 Thread Mark Lawrence via Tutor

On 12/10/17 21:22, Cameron McKay wrote:

Hello,

I've never used python trying to plot a graph. Thus I am having
difficulties trying to plot the maxwell-boltzmann distribution. right now
i've defined the y-axis given the probability, but the difficult part is
trying to plot x in the form of:

x = v/(2kT/m)^(1/2)

before i used the linspace function but i believe that was wrong as it just
gave me an exponential growth function as i need a bellcurve.

Thanks for looking into this,

Cameron



Hopefully this helps 
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.maxwell.html


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] logging to cmd.exe

2017-10-01 Thread Mark Lawrence via Tutor

On 26/09/2017 12:22, Albert-Jan Roskam wrote:


PS: sorry about the missing quote (>>) markers. Hotmail can't do this. Is Gmail 
better?

>

Get a decent email client and it'll do the work for you.  I use 
Thunderbird on Windows with hotmail, gmail and yahoo addresses and never 
have a problem.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Most common words in a text file

2017-10-01 Thread Mark Lawrence via Tutor

On 30/09/2017 18:12, Sri G. wrote:

I'm learning programming with Python.

I’ve written the code below for finding the most common words in a text
file that has about 1.1 million words. It's working fine, but I believe
there is always room for improvement.

When run, the function in the script gets a text file from the command-line
argument sys.argv[1], opens the file in read mode, converts the text to
lowercase, makes a list of words from the text after removing any
whitespaces or empty strings, and stores the list elements as dictionary
keys and values in a collections.Counter object. Finally, it returns a
dictionary of the most common words and their counts. The
words.most_common() method gets its argument from the optional top
  parameter.

import sysimport collections
def find_most_common_words(textfile, top=10):
 ''' Returns the most common words in the textfile.'''

 textfile = open(textfile)
 text = textfile.read().lower()
 textfile.close()


The modern Pythonic way is:-

with open(textfile) as textfile:
text = textfile.read().lower()

The file close is handled automatically for you.  For those who don't 
know this construct using the "with" keyword is called a context 
manager, here's an article about them 
https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/



 words = collections.Counter(text.split()) # how often each word appears

 return dict(words.most_common(top))

filename = sys.argv[1]


How about some error handling if the user forgets the filename?  The 
Pythonic way is to use a try/except looking for an IndexError, but 
there's nothing wrong with checking the length of sys.argv.



top_five_words = find_most_common_words(filename, 5)

I need your comments please.

Sri


Pretty good all in all :)

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with putting numbers from highest to lowest.

2017-09-27 Thread Mark Lawrence via Tutor

On 27/09/2017 20:36, Derry, James R wrote:




[Top posting fixed]



From: Tutor [tutor-bounces+jderry=mail.utexas@python.org] on behalf of 
edmundo pierre via Tutor [tutor@python.org]
Sent: Wednesday, September 27, 2017 8:10 AM
To: Tutor Python
Subject: [Tutor] Help with putting numbers from highest to lowest.

Hello,
When I used sort() to do that, but my problem is that sort() just arrange 
numbers from small to big, not from big to small. That is the issue I am having 
now. For instance:
# The user is entering those numbers:a = 2.7b = 4.7c= 5.8d = 7.9# I will like 
the answer to be like this: 7.9  5.8  4.7 2.7
#but if I use sort(), I will have that answer, but I do not want that:2.7 4.7 
5.8 7.9
Thank you!


> In [2]: ?sorted

Noting that this is iPython specific...

> Signature: sorted(iterable, /, *, key=None, reverse=False)
> Docstring:
> Return a new list containing all items from the iterable in ascending 
order.

>
> A custom key function can be supplied to customize the sort order, 
and the

> reverse flag can be set to request the result in descending order.
> Type:  builtin_function_or_method
>
> In [3]: sorted([3,1,5], reverse=True)
> Out[3]: [5, 3, 1]

...as are all the In[x] and Out[y] bits and pieces.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with putting numbers from highest to lowest.

2017-09-27 Thread Mark Lawrence via Tutor

On 27/09/2017 14:10, edmundo pierre via Tutor wrote:

Hello,
When I used sort() to do that, but my problem is that sort() just arrange 
numbers from small to big, not from big to small. That is the issue I am having 
now. For instance:
# The user is entering those numbers:a = 2.7b = 4.7c= 5.8d = 7.9# I will like 
the answer to be like this: 7.9  5.8  4.7 2.7
#but if I use sort(), I will have that answer, but I do not want that:2.7 4.7 
5.8 7.9
Thank you!


You need reverse=True on the call to sort.

You can find this out by:-

1. Using the interactive interpreter help, e.g.

>>> l = [2.7, 4.7, 5.8, 7.9]
>>> help(l.sort)
Help on built-in function sort:

sort(*, key=None, reverse=False) method of builtins.list instance
Stable sort *IN PLACE*.

None

2. clicking `index` to the top right of https://docs.python.org/3/, then 
`s` then `(list method)` under `sort`.


3. using your favourite search engine.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] logging to cmd.exe

2017-09-25 Thread Mark Lawrence via Tutor

On 25/09/2017 14:20, Albert-Jan Roskam wrote:

Hi,


With Python 3.5 under Windows I am using the logging module to log messages to 
stdout (and to a file), but this occasionally causes logging errors because 
some characters cannot be represented in the codepage used by cmd.exe (cp850, 
aka OEM codepage, I think). What is the best way to prevent this from 
happening? The program runs fine, but the error is distracting. I know I can 
use s.encode(sys.stdout.encoding, 'replace') and log that, but this is ugly and 
tedious to do when there are many log messages. I also don't understand why %r 
(instead of %s) still causes an error. I thought that the character 
representation uses only ascii characters?!


import logging
import sys

assert sys.version_info.major > 2
logging.basicConfig(filename="d:/log.txt", 
level=logging.DEBUG,format='%(asctime)s %(message)s')
handler = logging.StreamHandler(stream=sys.stdout)
logger = logging.getLogger(__name__)
logger.addHandler(handler)

s = '\u20ac'
logger.info("euro sign: %r", s)



--- Logging error ---
Traceback (most recent call last):
   File "c:\python3.5\lib\logging\__init__.py", line 982, in emit
 stream.write(msg)
   File "c:\python3.5\lib\encodings\cp850.py", line 19, in encode
 return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in position 12: 
character maps to 
Call stack:
   File "q:\temp\logcheck.py", line 10, in 
 logger.info("euro sign: %r", s)
Message: 'euro sign: %r'
Arguments: ('\u20ac',)


Thanks in advance for your replies!


Albert-Jan



Rather than change your code can you change the codepage with the chcp 
command?


C:\Users\Mark\Documents\MyPython>chcp
Active code page: 65001

C:\Users\Mark\Documents\MyPython>type mytest.py
import logging
import sys

assert sys.version_info.major > 2
logging.basicConfig(filename="d:/log.txt", 
level=logging.DEBUG,format='%(asctime)s %(message)s')

handler = logging.StreamHandler(stream=sys.stdout)
logger = logging.getLogger(__name__)
logger.addHandler(handler)

s = '\u20ac'
logger.info("euro sign: %r", s)
C:\Users\Mark\Documents\MyPython>mytest.py
euro sign: '€'
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write database-agnostic python code? (Is this even possible?)

2017-09-14 Thread Mark Lawrence via Tutor

On 14/09/2017 00:51, Cameron Simpson wrote:


Secondly, there's SQLAlchemy. It knows the dialects and asks you to 
write "native" looking python syntax for selects etc. So stuff like:


  db_conn.select(t.col1 == 9 and t.col2 == 10)

where "t" is a "table" object it has handed you. I believe these are 
just special objects with attributes for columns and the right __eq__ 
etc dunder methods to compute the correct SQL syntax. No escaping or 
param substitution in your own code. It also has an ORM, which I've not 
used.


Cheers,
Cameron Simpson  (formerly c...@zip.com.au)


SQLAlchemy isn't the only Python ORM of course.  There is a useful 
little article about ORMs and their availability here 
https://www.fullstackpython.com/object-relational-mappers-orms.html.  A 
more detailed comparison is given here 
http://pythoncentral.io/sqlalchemy-vs-orms/ which refers to storm, which 
is only mentioned in passing in the first link.  I've successfully used 
peewee, I can't really comment on the others.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] intro book for python

2017-09-03 Thread Mark Lawrence via Tutor

On 01/09/17 18:51, Raghunadh wrote:

Hello Derek,

I would start with this book

https://learnpythonthehardway.org

Raghunadh



I cannot recommend anything from the author of LPTHW after he had the 
audacity to write this 
https://learnpythonthehardway.org/book/nopython3.html about Python 3, in 
addition to which there are several vastly superior books and/or 
tutorials anyway.


Kindest regards.

Mark Lawrence.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Understanding error in recursive function

2016-04-09 Thread Mark Lawrence via Tutor

On 08/04/2016 21:48, Tom Maher wrote:

Hi,

As a test I am trying to write a function that returns the sum of values
attached to one key in a dictionary. I am wondering why the code that I
wrote is returning:
"maximum recursion depth exceeded"
Here is the code:

animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
x = animals['a']
def howMany(aDict):
   count = 0
   for value in howMany(aDict):
count += 1
   return count

howMany(x)

Just wondering why I would be getting that error.

Thanks


howMany calls howMany which calls howMany...

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaring variables

2016-04-07 Thread Mark Lawrence via Tutor

On 07/04/2016 18:49, Dimitar Ivanov wrote:

Hello everyone,

I have a (hopefully) quick and easy to explain question. I'm currently
using MySQLdb module to retrieve some information from a database. In my
case, the result that's being yield back is a single line.

As far as my understanding goes, MySQLdb function called 'fetchone()'
returns the result as a tuple. Problem is, the tuple has some unnecessary
characters, such as an additional comma being returned. In my case:


  idquery = 'select id from table;'
  cur = mysql.cursor()
  cur.execute(idquery)
  id = cur.fetchone()


Note that using 'id' is frowned upon as you're overriding the builtin of 
the same name.  I'll use id_ below.



  print id

('idinhere',)


No, it isn't an additional comma, it's a tuple that only has one field.



I stumbled across an example given like this:


  (id,) = cur.fetchone()


So I decided to give it a try and the result is exactly what I need:


  (id,) = cur.fetchone()
  print id

idinhere

My question is - can I reliably use this method? Is it always going to
return the string between the brackets as long as I define the variable
with '(,)'? I'm planning to use another query that will be using the result
from this one and then update another database with this result but I must
be sure that the variable will always be the string in and between the
brackets otherwise I'm risking to mess up a lot of things big time.


I'd write it as:-

id_ = cur.fetchone()[0]



A backup plan I had was to use the following:


  id = cur.fetchone()
  for x in id:
id = x


Yuck :)



But if the method above is certain to always return only the value I need,
I find it to be a far more elegant solution.

Also, just to clarify things for myself - what does this method of
declaring variables do exactly? I'm sorry if this isn't the right place the
ask and if this has been documented clearly already, I'm not sure what to
use as a search term in order to find an answer.


In Python nothing is declared as in C or Java. A name is bound to an 
object.  So from the above the name 'id_' is bound to the string object 
that happens to be 'idinhere'.  Once this has been done there is nothing 
to stop you from writing:-


id_ = 1
id_ = 1.0
id_ = Point(1, 2)
id_ = Complicated(lots, of, parameters, here)



Thanks a lot in advance! I hope I posted all the details needed and my
question is easy to comprehend.


The only things that are sometimes needed are your OS and Python 
version.  The latter can be deduced from your 'print id' rather than 
'print(id)', indicating that it is 2.x, not 3.y.




Regards,
Dimitar




--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Drawing simple graphics objects

2016-04-04 Thread Mark Lawrence via Tutor

On 04/04/2016 04:17, Ashley Jacobs wrote:

Hi,
could you help me with python 3.5 coding for graphics?



Yes, if you provide some code that we can comment on.  We do not write 
code for you.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fw: About the Round Function

2016-04-01 Thread Mark Lawrence via Tutor

On 01/04/2016 20:46, Nacir Bouali wrote:

-Forwarded by Nacir Bouali/sse/stud/aui/ma on 04/01/2016 08:46PM -
To: tutor@python.org
From: Nacir Bouali/sse/stud/aui/ma
Date: 11/14/2015 08:21PM
Subject: About the Round Function

Dear Python Tutor(s),
My students and I are interested in knowing the rationale behind Python's
choice of the Banker's rounding algorithm to be the default rounding
algorithm in the third release of Python.


I'm sorry but I do not understand the above at all, what third release 
of Python, for what type of Python object, please explain?



We'd also like to know how the function is actually implemented.


I'm sorry but I cannot say until you give us precise details as I've 
asked above.



Regards,
Nacir


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor