Re: [Tutor] python question

2019-08-18 Thread Steven D'Aprano
On Sun, Aug 18, 2019 at 12:35:52PM +0800, Thejal Ramesh wrote:
> Hi, i have a question regarding this question. I'm not quite sure what the
> question is asking.

Ask your tutor. We can help you with learning Python the programming 
language, not graph theory.

https://en.wikipedia.org/wiki/Graph_theory


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


Re: [Tutor] python question

2019-08-18 Thread Alan Gauld via Tutor
On 18/08/2019 05:35, Thejal Ramesh wrote:
> Hi, i have a question regarding this question. I'm not quite sure what the
> question is asking.

> Part A: Popular (1.5 Marks)
>  Write a function popular(graph list, n) that returns a list of people who
> have at least n friends. Each person is identified by the number of their
> vertex.

>  Examples clayton_list = [ [1,2,3], [0,3], [0,4], [0,1], [2] ]
> The example graph clayton list is provided for illustrative purpose. Your
> implemented function must be able to handle arbitrary graphs in list form
> . a) Calling popular(clayton list,2) returns [0,1,2,3].
>  b) Calling popular(clayton list,3) returns [0]
> . c) Calling popular(clayton list,0) returns [0,1,2,3,4].

The question is asking you to write a function that returns the
indexes of the elements in the input list of length equal to or
greater than the input value.

Looking at the sample data, clayton_list
a) returns all but the last item because only the last item has less
   than 2 members
b) returns only the first item because only the first item contains
   3 or more members
c) returns all items because all have zero or more members.

What the question does not specify is what the function should return
if there are no members found. I would assume an empty list...

To do this you will need some kind of loop and a test and build a list.
If you know about list comprehensions that might be one option. (If you
don't, use a normal for loop)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python code

2019-08-01 Thread David Rock
maybe a copy/paste of your terminal session so we can see the text of the steps 
you are actually performing will give use some clues.

—
David

> On Aug 1, 2019, at 18:22, David L Neil  wrote:
> 
> On 2/08/19 3:23 AM, Spencer Wannemacher wrote:
>> I'm new to python and I was trying to perform a simple one code. All that is 
>> included in the code is print(61). I save it as 61.py and change the 
>> directory before typing in python 61.py and I don't get an output. There is 
>> no error and the output is blank. Please let me know what I'm doing wrong. 
>> Thank you so much!
> 
> 
> What do you mean by "and change the directory before"?
> 
> Python will start searching for 61.py in the *current* directory!
> 
> -- 
> Regards =dn
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Python code

2019-08-01 Thread David L Neil

On 2/08/19 3:23 AM, Spencer Wannemacher wrote:

I'm new to python and I was trying to perform a simple one code. All that is 
included in the code is print(61). I save it as 61.py and change the directory 
before typing in python 61.py and I don't get an output. There is no error and 
the output is blank. Please let me know what I'm doing wrong. Thank you so much!



What do you mean by "and change the directory before"?

Python will start searching for 61.py in the *current* directory!

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


Re: [Tutor] Python code

2019-08-01 Thread Cameron Simpson

On 01Aug2019 15:23, Spencer Wannemacher  wrote:
I'm new to python and I was trying to perform a simple one code. All 
that is included in the code is print(61). I save it as 61.py and 
change the directory before typing in python 61.py and I don't get an 
output. There is no error and the output is blank. Please let me know 
what I'm doing wrong. Thank you so much!


Can you confirm that your entire "61.py" file is this:

 print(61)

That should print a "61" on the output, as I think you expected.

Can you confirm your operating system? I'm guessing Windows, but a 
detailed description would be helpful.


Are you are typing "python 61.py" at the shell prompt (I presume 
Windows' CMD.EXE prompt)? And not to some other interface?


It is my recollection that "python" isn't a command under windows, 
there's a "py" command (I'm not on Windows here). So it may be that when 
you issue the command "python" it isn't running the Python interpreter 
but something else.


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


Re: [Tutor] python idle file couldn't start

2019-07-24 Thread Flynn, Stephen (Life & Pensions)
What (precisely) did you type to "start python through idle"? Don't guess - cut 
and pasted EXACTLY what you type and what you see on screen.

S.

-Original Message-
From: Tutor  On Behalf Of 
siva
Sent: 24 July 2019 08:57
To: tutor@python.org
Subject: [Tutor] python idle file couldn't start

I have tried to start python through idle .but the software didn’t start.it 
displays “subprocess error”.tell me some solution.
Thank you. 

Sent from Mail for Windows 10

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


This message has been scanned by Capita systems, but if you believe it to be 
spam, please send it to s...@forcepoint.com.

Messages sent to s...@forcepoint.com are queued for email analysis by 
Forcepoint Threat Lab.


This email is security checked and subject to the disclaimer on web-page: 
http://www.capita.co.uk/email-disclaimer.aspx
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Generator expressions

2019-07-23 Thread Steven D'Aprano
On Wed, Jul 24, 2019 at 11:26:26AM +1200, David L Neil wrote:

> Clarifying the difference/similarity in appearance between a generator 
> expression and a tuple, it might help to think that it is the comma(s) 
> which make it a tuple!

David makes an excellent point here. Except for the special case of the 
empty tuple, it is *commas* that create tuples, not parentheses. The 
round brackets are used for grouping, and are optional:

py> a = 1, 2, 3
py> type(a)



The only times you *need* parens around a non-empty tuple is to group 
the items or to avoid ambiguity, e.g. a tuple inside a tuple:

a = 1, 2, (3, 4, 5), 6
assert len(a) == 4

or when passing a literal tuple as argument to a function:

function(1, 2, 3, 4, 5, 6)# six arguments
function(1, 2, (3, 4, 5), 6)  # four arguments




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


Re: [Tutor] Python Generator expressions

2019-07-23 Thread Steven D'Aprano
On Tue, Jul 23, 2019 at 10:36:01PM +0530, Animesh Bhadra wrote:
> Hi All,
> 
> Need one help in understanding generator expression/comprehensions.
> 
> This is my sample code.

Lots of missing spaces in your code! Don't forget to hit the space bar 
between words :-)

Also missing indentation, which is probably Gmail being "helpful".

I'm just going to fix the obvious typos without comment.


> # This code creates a generator and not a tuple comprehensions.
> my_square =(num*num for num in range(11))
> print(my_square) #  at 0x7f3c838c0ca8>
> # We can iterate over the square generator like this.
> try:
> while True:
> print(next(my_square)) # Prints the value 0,1,4
> except StopIteration as SI:
> print("Stop Iteration")
> # Another iteration
> for x in my_square:
> print(x) # This prints nothing.


> Does the generator exhausts its values when we run the iterator once?

Correct.


> Lastly any specific reason for not having a tuple comprehensions?

(1) History and (2) because tuple comprehensions are not useful enough 
to dedicate syntax to them.


Originally, Python introduced *list comprehensions* using square bracket 
syntax:

[expression for x in values]

which created a list. If I remember correctly, I think this was about 
Python 2.2. 

Tuples are mostly intended for *small* numbers of heterogeneous values, 
like a struct or record in other languages:

# Typical example of tuple
(1, "Hello", 4.5)

while lists are intended for potentially large numbers of homogeneous 
values, like an array of data:

[2.3, 4.5, 0.9, 7.2, 9.3, 4.5, 6.1, 0.2, 8.7, ... # and many more

(heterogeneous = "different types", homogeneous = "same types")

That makes lists a really good fit for comprehensions, and tuples a bad 
fit. So it was decided that the need for a direct tuple comprehension 
was pretty low. If you wanted a tuple, you could easily get one:

tuple([expression for x in values])

and that was good enough without wasting useful syntax on something that 
would hardly ever be needed.

It would be a tiny bit more expensive to run (first you create a list, 
then copy it to a tuple, and then garbage collect the list) but so what? 
Not every rare operation needs to be optimized.

A few years later, generator comprehensions were added as a lazy version 
of list comprehensions. List comprehensions produce all the values up 
front, while generator comprehensions produce them one at a time as 
needed. The syntax chosen used round brackets ( ... ) instead of square 
brackets [ ... ] but otherwise was identical.

What other syntax could have been chosen? Curly brackets are used for 
dicts (Python 2 and 3) and sets (Python 3 only), so they are unsuitable, 
and later on in Python 3 we gained dict and set comprehensions as well.

Had we wasted the ( ... ) syntax on tuples, which hardly anyone would 
have ever used, we would have missed out on the super-useful lazy 
generator comprehensions.


 
> Have checked this link, but could not understood the reason?
> 
>  * 
>  
> https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python

Don't believe everything you read on Stackoverflow. There's lots of 
utter nonsense on that page, for example:

"The answer is obviously because tuple syntax and parenthesis are 
ambiguous"

is rubbish. The parser can tell the difference between tuples and 
parentheses. Tuples use *commas*, not parentheses, except for the 
empty tuple () which is a special case. There's no ambiguity in Python.

The top rated answer

"parentheses were already taken for … generator expressions"

is incorrect, because generator expressions came second, not first. 
Python could have added tuple comprehensions at the same time it added 
list comprehensions, but the developers decided not to:

- it wasn't clear how useful comprehensions would be; they were really 
useful in Haskell, but people weren't sure if Python developers would 
take to them (they sure did!);

- list comprehensions are clearly useful, but tuple comprehensions not 
so much. Not ever single use has to get its own special syntax.

Of course, *later on* once Python had generator comprehensions using 
parentheses, we couldn't easily add tuple comprehensions because 
there's no good syntax left. But why would we want them?



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


Re: [Tutor] Python Generator expressions

2019-07-23 Thread Mats Wichmann
On 7/23/19 11:06 AM, Animesh Bhadra wrote:
> Hi All,
> 
> Need one help in understanding generator expression/comprehensions.
> 
> This is my sample code.
> 
> # This code creates a generator and not a tuple comprehensions.
> my_square =(num *num fornum inrange(11))
> print(my_square) #  at 0x7f3c838c0ca8>
> # We can iterate over the square generator like this.
> try:
> whileTrue:
> print(next(my_square)) # Prints the value 0,1,4
> exceptStopIterationasSI:
> print("Stop Iteration")

is this code you were actually running? because it won't work... an
except needs to be matched with a try, it can't match with a while.

you *can* comsume your the values your generator expression generates by
doing a bunch of next's, but why would you?  Instead, just iterate over
it (every generator is also an iterator, although not vice versa):

for s in my_square:
print(s)

you don't have to manually catch the StopIteration here, because that's
just handled for you by the loop.


> # Another iteration
> forx inmy_square:
> print(x) # This prints nothing.
> 
> 
> Does the generator exhausts its values when we run the iterator once?
> Lastly any specific reason for not having a tuple comprehensions?
> 
> Have checked this link, but could not understood the reason?
> 
>  *
> https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python
> 
> 
> Regards,
> Animesh
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Python Generator expressions

2019-07-23 Thread David L Neil

Hi Animesh,
Unfortunately the list server/email has removed the formatting from your 
sample, but no matter...



On 24/07/19 5:06 AM, Animesh Bhadra wrote:

# This code creates a generator and not a tuple comprehensions.
my_square =(num *num fornum inrange(11))
print(my_square) #  at 0x7f3c838c0ca8>
# We can iterate over the square generator like this.
try:
whileTrue:
print(next(my_square)) # Prints the value 0,1,4
exceptStopIterationasSI:
print("Stop Iteration")
# Another iteration
forx inmy_square:
print(x) # This prints nothing.
Does the generator exhausts its values when we run the iterator once?


Yes, it involves a "lazy" approach - the value is not calculated until 
the next() requests it. Whereas, a list comprehension calculates all its 
values at one time (and requires the storage space to hold them).


https://docs.python.org/3/reference/datamodel.html?highlight=generator - 
notice that there is a yield and a next facility, but when it terminates 
StopIteration is raised. There is no 'start again' command!



The Python docs are informative:
https://docs.python.org/3/reference/expressions.html?highlight=generator
https://docs.python.org/3/tutorial/classes.html?highlight=generator#generators


If you have an actual reason for running through a generator expression 
more than once, then consider return-ing it from a function/class (which 
will then be directly accessible to the for-loop/next method).




Lastly any specific reason for not having a tuple comprehensions?
Have checked this link, but could not understood the reason?
https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python 


I don't know.

Have you understood the differences between lists and tuples - 
specifically "mutability" and "immutability"?


Let's take a list comprehension. If you 'unwind it', can you reproduce 
it as a multi-line for-loop? Yes, but before the loop the 'target' list 
must be defined/declared to be a list; and within the loop the list is 
appended with the 'generated' values.


Ok? (sorry, don't know if this will be new to you, or not)

Now, instead of a list, try using a tuple? How do you append() to a tuple?


Yes, many people have confused generator expressions - 
surrounded/"delimited" by parentheses, ie ( and ), with tuples.

However, try this little demonstration:


a, b = 1, 2
a

1

b

2

a, b = ( 1, 2 )
a

1

b

2

( a, b ) = ( 1, 2 )
a

1

b

2

type( a )



type( ( 1, 2 ) )



The principle here is known as "tuple unpacking". The two constants 
(right-hand side) are arranged as a tuple, as are the two variables (a 
and b/left-hand side), regardless of the presence/absence of the 
parentheses!


https://treyhunner.com/2018/03/tuple-unpacking-improves-python-code-readability/


Clarifying the difference/similarity in appearance between a generator 
expression and a tuple, it might help to think that it is the comma(s) 
which make it a tuple!



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


Re: [Tutor] Python Imported Code

2019-07-20 Thread Albert-Jan Roskam


On 25 Jun 2019 15:50, stephen.m.sm...@comcast.net wrote:

Introduction:

I have written a 'program' that does some reasonable screen scraping off of
a specific website. The program has gotten too large so I have tried to
segment it into logical pieces (tkinter logic as a start) but I am having
problems. Specifically I need to pass several dictionaries to the module
(imported code) that validates some user selection and into the code that
navigates through the website.

》》 Hi, not sure if you could use it here, but I was triggered by the term 
"validation":
* Tkinter allows you to define a validationcommand, 
https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter
* You can also define tracers. These are functions that are triggered when a 
Tkinter var (e.g  StringVar) is changed.
* You can also bind events to a function. For example a  event from 
an Entry checks the entry contents and colors it red if it's invalid.

It's been a while since I've used this but those tricks may come in handy!

Albert-Jan

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


Re: [Tutor] Python 3.7 Grids

2019-06-29 Thread boB Stepp
On Sat, Jun 29, 2019 at 2:02 AM David Merrick  wrote:
>
> Hi Looking for a way to use the determine the position of a card in a grid
> using the mouse click event in Python. Code is attached. There are no
> viruses.
>
> Unfortunately using Tinkter grids / frames can't determine between the two
> demo cards.

As Bob Gailer mentioned this is a text only list which does not allow
attachments, so I cannot see what you are actually attempting with
your code.  But with what you said, two thoughts come to my mind:

1) You can embed each card image on a button widget and if such a
button is clicked have the button's callback function respond
accordingly.

2) tkinter allows you to know the size of your window and can report
back what the cursor's current position is.  If you ensure that your
cards take up a known coordinate space in the window, when a mouse
click event happens you can write code to determine if the cursor fell
within either card's known coordinate space.

Hope this gives you some idea of how to tackle your problem.

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


Re: [Tutor] [Python-Help] Writing hello world

2019-06-29 Thread Bob Gailer
On Jun 28, 2019 9:26 AM, "Erastus muriithi" 
wrote:
>
> Iam a student..iam interested in learning python,,I don't know how to
study this python.kindly help me how to go about it..Thankyou

First make sure you have python installed on your computer. If you need
help with that let us know what kind of computer and operating system you
are using.

At the python. Org website you will find links to tutorials. Try some of
these out.

Direct future emails to tutor@python.org.
Always reply all so a copy goes back to the list.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.7 Grids

2019-06-29 Thread Bob Gailer
On Jun 29, 2019 3:01 AM, "David Merrick"  wrote:
>
> Hi Looking for a way to use the determine the position of a card in a grid
> using the mouse click event in Python. Code is attached.

Unfortunately this list does not forward attachments. Either give us a link
to the code or even better if it's not terribly complicated paste it into
the reply. be sure to reply all so everyone on the tutor list will see your
reply.

> There are no viruses.

That's kind of like a Salesman saying "trust me".

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


Re: [Tutor] Python and DB

2019-06-27 Thread Alan Gauld via Tutor
On 27/06/2019 22:20, Brave Heart via Tutor wrote:
> I would like python to write to DB so  I can from DB write on a webpage with 
> PHP...

Yes, that's easy enough. Python supports access to many databases,
do you have one in mind? If not the SQLite module that comes in
the standard library is probably more than adequate for your needs.
PHP has modules for reading SQLite too.

If you are familiar with using databases in any other language the
Python DBAPI should be easy to pick up.

If you don;t know SQL then you might like the database topic in
my tutorial(see below)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python and DB

2019-06-27 Thread Cameron Simpson

On 27Jun2019 23:20, Brave Heart  wrote:

I have a little RSS program , I current the out are basically outputted on my 
screen, but I would like python to write to DB so  I can from DB write on a 
webpage with PHP...
Kinda like I want to run a news website ..


See the "sqlite3" module with ships with Python. It creates a database 
in a local file and provides an SQL interface:


 https://docs.python.org/3/library/sqlite3.html#module-sqlite3

SQLite3 also has a command line tool for interactive access to the 
database; you might need to install that separately.


For the web side you'd need an SQLite library for PHP, but I cannot 
believe that one does not exist. (Or you could also write your web 
application in Python instead of PHP.)


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


Re: [Tutor] Python and DB

2019-06-27 Thread Mats Wichmann
On 6/27/19 3:20 PM, Brave Heart via Tutor wrote:
> I have a little RSS program , I current the out are basically outputted on my 
> screen, but I would like python to write to DB so  I can from DB write on a 
> webpage with PHP...
> 
> Kinda like I want to run a news website ..

There doesn't seem to be a question here.

Does this help in any way?

https://docs.python.org/3.7/library/sqlite3.html


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


Re: [Tutor] Python Imported Code

2019-06-25 Thread Alan Gauld via Tutor
On 25/06/2019 14:50, stephen.m.sm...@comcast.net wrote:

> using global, but that fails. I also can't seem to use arguments because the
> module that tkinter fires up with this command:
> 
> self.process_button = tk.Button(master, text='Process Request', \
> font = ('times', regular_font,
> 'bold'),\
> fg = "blue",
> command=self.Process_Reservation_Request)
> 
> does not seem to support the presence of arguments.

There is a common trick to get round that:


self.process_button = tk.Button(master,
  text='Process Request',
  font = ('times', regular_font,'bold'),
  fg = "blue",
  command=lambda :self.Process_Reservation_Request(x,y)
  )

The lambda defines a function that takes no arguments but
which then calls your function with arguments.

Of course x and y need to be visible within the function
defining the lambda.

> Demo Program - This currently bombs in part 3 - it can't seem to see the
> value/space created in part1. Any help or reference that will clearly show

> Part 1
> 
> import nice
> import nice2
> global myGlobal
> myGlobal = "initial value"

global here does nothing. global is only useful inside a function.
Remember that global in Python means module level - it does not
mean visible between modules!

> print(myGlobal)
> nice.changeGlobal()
> print (nice.myGlobal)
> nice2.changeGlobal()
> 
> print("nice version = ", nice.myGlobal)
> print("nice2 version = ", nice2.myGlobal)
> print("mainline=", myGlobal)
> 
> part 2 - stored as nice.py
> 
> def changeGlobal():
>global myGlobal

This tells changeGlobal() that there is a variable called myGlobal
defined at the module level. That is, within nice. It does not
refer to the one you defined in Part 1.

>#print("entering  changeGlobal part 1", myGlobal)
>myGlobal = "hello"

This now creates that module level variable with the value 'hello'.

>print("top of myGlobal", myGlobal) 
>
>myGlobal="bye"

And this redefines nice.myGlobal to be 'bye'
The final value  will now be seen by Part 1 code as
nice.myGlobal with a value of 'bye'.

> Part3 stored as nice2
> myGlobal = "hello"

This creates a new global variable called myGlobal within
the nice2 module. It is visible to Part 1 as nice2.myGlobal

> def changeGlobal():
>global myGlobal

This tells changeGlobal() to use the module level variable
above. ie nice2.myGlobal.

>print("first value = ", nice.myGlobal)

You didn't import nice into nice2 so this should give an error.

>myGlobal="it worked"
>print("in changeGlobal2 =", myGlobal)

This should set the variable nice2.myGlobal to 'it worked'
and that will be seen in Part 1 code as nice2.myGlobal.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] python

2019-06-25 Thread Bob Gailer
On Jun 25, 2019 8:52 AM, "Shaon Debnath"  wrote:
>
> I just wanted to know all about map() function in python.

See https://www.geeksforgeeks.org/python-map-function/.

If after reading that you still have questions please come back and ask
them.

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


Re: [Tutor] Python type annotation question

2019-06-24 Thread Mats Wichmann
On 6/24/19 12:48 PM, Arup Rakshit wrote:
> I am little experimenting with Python type annotation today. I wrote a simple 
> class as below:
> 
 from datetime import date
 class Person:
> ... dob: date
> ... def __init__(self, dob):
> ... self.dob = dob
> ... 
 Person(11)
> <__main__.Person object at 0x10e078128>
 p = Person(11)
 p.dob
> 11
> 
> Although I marked dob as date type, why am I able to assign it an int? So my 
> question how does type annotation helps, when should we use them and what 
> advantages it brings?

it's a mechansim to support static checking in various forms - tools,
IDES, etc.  It also serves to document your intent without having to
write as much in the docstring.

Python remains a "consenting adults" language, that is if you really
want to do something, you can, so the type hints are not enforced at
runtime.  Since it's not always the case that doing something possible
is a good idea, the type hints are there to make it easier to detect issues.


Your annotation looks funky, by the way, I'd expect to see it written as:

> ... def __init__(self, dob: date):
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python printing parentheses and quotes

2019-06-11 Thread Sai Allu
Thank you Cameron,

This was something that I was working on last week and I've been able to fix 
the script since then. I was just curious why the previous version did that and 
you might be right, thank you for the help though!

Best Wishes,
Sai Allu

From: Cameron Simpson 
Sent: Monday, June 10, 2019 5:34 PM
To: Sai Allu
Cc: Mats Wichmann; tutor@python.org; Deepak Dixit
Subject: Re: [Tutor] Python printing parentheses and quotes

On 10Jun2019 19:04, Sai Allu  wrote:
>Actually I'm pretty sure what happened was that the "#! usr/bin/python" was in 
>a module that was being imported. So the Python interpreter cached it or 
>somehow crashed randomly, which meant that the print was working as a keyword 
>instead of a function.
>
>But when I removed that "#! usr/bin/python" line and then rewrote the print 
>statements, it went back to working normally.

My personal suspicision is that what you might have been doing is this
(notice the trailing comma):

  print("",)

or maybe:

  print("this", that")

Look:

  % python
  Python 2.7.16 (default, Apr  1 2019, 15:01:04)
  [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
  >>> print("",)
  ('',)
  >>>

  % python3
  Python 3.7.3 (default, Mar 30 2019, 03:38:02)
  [Clang 8.0.0 (clang-800.0.42.1)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
  >>> print("",)

  >>>

What is happening?

In Python 2, print is a statement unless you use the __future__ import
already mentioned. That means that this:

  print("",)

is a "print" of the expression ("",), which is a 1-tuple, and gets
printed as a tuple. The more likely scenario is when you're printing
mulitple things:

  print("this", "that")

which is still a "print" of a tuple.

However, in Python 3 print is a function which means that the brackets
are part of the function call. So this:

  print("")

or:

  print("this", "that")

is a call to the "print()" function, passing one or two arguments, which
get printed. And printing "" (the former case) is an empty string.

Please revisit your code can test this.

Subtle issues like this are why we like to receive _exact_ cut/paste of
your code and the matching output, not a retype of what you thought you
ran. If you encounter something weird like this, it is well worth your
time (and ours) if you make a tiny standalone script showing the
problem, as small as possible. Then paste it into your message and paste
in the output (this list drops attachments). That we we can all run
exactly the same code, and solve your actual problem.

And start always using:

  from __future__ import print_function

in Python if you're using print. That will make your prints behave the
same regardless if whether they are using Python 2 or 3.

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


Re: [Tutor] Python printing parentheses and quotes

2019-06-10 Thread Cameron Simpson

On 10Jun2019 19:04, Sai Allu  wrote:

Actually I'm pretty sure what happened was that the "#! usr/bin/python" was in 
a module that was being imported. So the Python interpreter cached it or somehow crashed 
randomly, which meant that the print was working as a keyword instead of a function.

But when I removed that "#! usr/bin/python" line and then rewrote the print 
statements, it went back to working normally.


My personal suspicision is that what you might have been doing is this 
(notice the trailing comma):


 print("",)

or maybe:

 print("this", that")

Look:

 % python
 Python 2.7.16 (default, Apr  1 2019, 15:01:04)
 [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
 Type "help", "copyright", "credits" or "license" for more information.
 >>> print("",)
 ('',)
 >>>

 % python3
 Python 3.7.3 (default, Mar 30 2019, 03:38:02)
 [Clang 8.0.0 (clang-800.0.42.1)] on darwin
 Type "help", "copyright", "credits" or "license" for more information.
 >>> print("",)

 >>>

What is happening?

In Python 2, print is a statement unless you use the __future__ import 
already mentioned. That means that this:


 print("",)

is a "print" of the expression ("",), which is a 1-tuple, and gets 
printed as a tuple. The more likely scenario is when you're printing 
mulitple things:


 print("this", "that")

which is still a "print" of a tuple.

However, in Python 3 print is a function which means that the brackets 
are part of the function call. So this:


 print("")

or:

 print("this", "that")

is a call to the "print()" function, passing one or two arguments, which 
get printed. And printing "" (the former case) is an empty string.


Please revisit your code can test this.

Subtle issues like this are why we like to receive _exact_ cut/paste of 
your code and the matching output, not a retype of what you thought you 
ran. If you encounter something weird like this, it is well worth your 
time (and ours) if you make a tiny standalone script showing the 
problem, as small as possible. Then paste it into your message and paste 
in the output (this list drops attachments). That we we can all run 
exactly the same code, and solve your actual problem.


And start always using:

 from __future__ import print_function

in Python if you're using print. That will make your prints behave the 
same regardless if whether they are using Python 2 or 3.


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


Re: [Tutor] Python printing parentheses and quotes

2019-06-10 Thread Sai Allu
Actually I'm pretty sure what happened was that the "#! usr/bin/python" was in 
a module that was being imported. So the Python interpreter cached it or 
somehow crashed randomly, which meant that the print was working as a keyword 
instead of a function.

But when I removed that "#! usr/bin/python" line and then rewrote the print 
statements, it went back to working normally.

Thank you for the help though!
Sai Allu

From: Sai Allu
Sent: Monday, June 10, 2019 11:53 AM
To: Mats Wichmann; tutor@python.org; Deepak Dixit
Subject: Re: [Tutor] Python printing parentheses and quotes

But then how come it was working earlier for me without that import statement. 
Python doesn't interpret it as a statement exclusively, before it worked fine 
as a function.

Best Wishes,
Sai Allu

From: Mats Wichmann 
Sent: Monday, June 10, 2019 11:12 AM
To: Sai Allu; tutor@python.org
Subject: Re: [Tutor] Python printing parentheses and quotes

On 6/10/19 10:50 AM, Sai Allu wrote:
> Hello!
>
> I was just wondering if anybody encountered an issue where the Python 
> interpreter was changing how it interprets print statements. So I'm using 
> default Python on Mac OSX (2.7.10 I'm pretty sure) and running with the 
> "python script.py" command.
>
> Basically what happened was that I had a few lines in the script like this
> ip = "10.41.17.237"
> print(" Welcome to Squid Monitoring for ", ip)
> print("")
>
> and the output was like this
>
> ("   Welcome to Squid Monitoring for 10.41.17.237")
>
> ("")
>
> So it was printing parentheses and quotes. The above result might not be 
> exactly accurate because I didn't save the output, but it was something 
> generally like that.

In Python 2, print is a statement. In Python 3 it's a function and
behaves like you're expecting.

However, the behavior you're seeing is odd (printing parentheses is a
surprise unless there's more going on than you've listed)

If you want them consistent across both versions, add a statement at the
very top:

from __future__ import print_function



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


Re: [Tutor] Python printing parentheses and quotes

2019-06-10 Thread Sai Allu
But then how come it was working earlier for me without that import statement. 
Python doesn't interpret it as a statement exclusively, before it worked fine 
as a function.

Best Wishes,
Sai Allu

From: Mats Wichmann 
Sent: Monday, June 10, 2019 11:12 AM
To: Sai Allu; tutor@python.org
Subject: Re: [Tutor] Python printing parentheses and quotes

On 6/10/19 10:50 AM, Sai Allu wrote:
> Hello!
>
> I was just wondering if anybody encountered an issue where the Python 
> interpreter was changing how it interprets print statements. So I'm using 
> default Python on Mac OSX (2.7.10 I'm pretty sure) and running with the 
> "python script.py" command.
>
> Basically what happened was that I had a few lines in the script like this
> ip = "10.41.17.237"
> print(" Welcome to Squid Monitoring for ", ip)
> print("")
>
> and the output was like this
>
> ("   Welcome to Squid Monitoring for 10.41.17.237")
>
> ("")
>
> So it was printing parentheses and quotes. The above result might not be 
> exactly accurate because I didn't save the output, but it was something 
> generally like that.

In Python 2, print is a statement. In Python 3 it's a function and
behaves like you're expecting.

However, the behavior you're seeing is odd (printing parentheses is a
surprise unless there's more going on than you've listed)

If you want them consistent across both versions, add a statement at the
very top:

from __future__ import print_function



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


Re: [Tutor] Python printing parentheses and quotes

2019-06-10 Thread Alan Gauld via Tutor
On 10/06/2019 17:50, Sai Allu wrote:

> Basically what happened was that I had a few lines in the script like this
> ip = "10.41.17.237"
> print(" Welcome to Squid Monitoring for ", ip)
> print("")
> 
> and the output was like this
> 
> ("   Welcome to Squid Monitoring for 10.41.17.237")
> 
> ("")

Are you sure? Is that a cut n paste or just how you think you remember
it? The reason i ask is that its not what i see and not what I'd expect.

In Python v2 print is a statement which means that Python sees your
first print line like:

print  (" Welcome to Squid Monitoring for ", "10.41.17.237")

That is it thinks you want it to print a tuple of 2 strings and what I
see as output is:

(' Welcome to Squid Monitoring for ', '10.41.17.237')

Which is a tuple of 2 strings...

Now if I remove the parentheses it looks like:

print " Welcome to Squid Monitoring for ", "10.41.17.237"

Which is telling Python to print two strings joined by a space.
And I see the output:

 Welcome to Squid Monitoring for  10.41.17.237

And in both cases the second print just prints out an empty
string with no quotes.

Are you sure that's not what you saw?

> P.S. After I upgrade to Python3 this started working. 

In Python 3 print is a function so it needs the parentheses.
Without them it will report a syntax error. So for Python 3
your original code is correct.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python printing parentheses and quotes

2019-06-10 Thread Mats Wichmann
On 6/10/19 10:50 AM, Sai Allu wrote:
> Hello!
> 
> I was just wondering if anybody encountered an issue where the Python 
> interpreter was changing how it interprets print statements. So I'm using 
> default Python on Mac OSX (2.7.10 I'm pretty sure) and running with the 
> "python script.py" command.
> 
> Basically what happened was that I had a few lines in the script like this
> ip = "10.41.17.237"
> print(" Welcome to Squid Monitoring for ", ip)
> print("")
> 
> and the output was like this
> 
> ("   Welcome to Squid Monitoring for 10.41.17.237")
> 
> ("")
> 
> So it was printing parentheses and quotes. The above result might not be 
> exactly accurate because I didn't save the output, but it was something 
> generally like that.

In Python 2, print is a statement. In Python 3 it's a function and
behaves like you're expecting.

However, the behavior you're seeing is odd (printing parentheses is a
surprise unless there's more going on than you've listed)

If you want them consistent across both versions, add a statement at the
very top:

from __future__ import print_function



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


Re: [Tutor] Python Django Query

2019-04-02 Thread nitin chandra
Thanks Cameron,

Just got lucky yesterday and found a resource at my end to help me out.

Thank you

On Tue, 2 Apr 2019 at 04:31, Cameron Simpson  wrote:
>
> On 29Mar2019 21:18, nitin chandra  wrote:
> >Hi Everyone,
> >I need some guidance / corrections to my code.
> >I hosted a demo site on pythonanywhere.com and to test the initial
> >pages I wrote some test code.
> [...]
>
> Hi Nitin,
>
> I looks like nobody has replied; this probably means that nobody has the
> required specialty expertise to help you. (I don't.)
>
> >Good news, put in 10 hrs, tried so many suggestion given on the net,
> >yet non worked. So finally mailing the list.
>
> Might I suggest that you ask on the django-users mailing list, here:
>
>   https://www.djangoproject.com/community/
>
> You want the "Using Django" list there.
>
> There's a guideline to posting here:
>
>   https://code.djangoproject.com/wiki/UsingTheMailingList
>
> but your post looks fairly good on the face of it.
>
> Hoping this helps,
> Cameron Simpson 
>
> >
> >Objective : display main page with multiple links to other pages. Use
> >jQuery plugins, click the link on main page and open other pages.
> >
> >The following path and pages are posted below.
> >
> >Thanks
> >
> >Nitin Chandra
> >
> >
> >ERROR
> >When I click on 'Table' link on 'home' page, the following error is displayed
> >
> >http://selftech.pythonanywhere.com/table.html
> >Page not found (404)
> >
> >Request Method:GET
> >Request URL:http://selftech.pythonanywhere.com/table.html
> >
> >Using the URLconf defined in eduinfra.urls, Django tried these URL
> >patterns, in this order:
> >
> >admin/
> >[name='home.html']
> >
> >The current path, table.html, didn't match any of these.
> >
> >You're seeing this error because you have DEBUG = True in your Django
> >settings file. Change that to False, and Django will display a
> >standard 404 page.
> >
> >+++
> >
> >/home/selfTech/edu/tech/
> >
> > __init__.py
> > admin.py
> > apps.py
> > models.py
> > tests.py
> > urls.py
> > views.py
> >
> >/home/selfTech/edu/tech/templates/
> >
> > base.html
> > home.html
> > table.html
> >***
> >our 'base.html' code below (test code, gets rendered correctly)
> >
> >
> >  Navbar
> >   >data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02"
> >aria-expanded="false" aria-label="Toggle navigation">
> >
> >  
> >
> >  
> >
> >  
> >Home  >class="sr-only">(current)
> >  
> >  
> >Link
> >  
> >  
> >Table
> >  
> >  
> > >aria-disabled="true">Disabled
> >  
> >
> >
> >  
> >   >type="submit">Search
> >
> >  
> >
> >   *
> >home.html
> >
> >{% extends 'base.html' %}
> >
> >{% block content%}
> >Hello TEAM :)
> >{% endblock %}
> >***
> >table.html (gives ERROR 404)
> >
> >
> >
> >
> >Name
> >
> >
> >
> >
> >*
> >/home/selfTech/edu/tech/
> >
> >urls.py
> >
> >from django.urls import path
> >from . import views
> >
> >urlpatterns = [
> >path('', views.home, name='home'),
> >path('table/', views.table, name='table') ## various combo did not work
> >   # path (' ', views.table, name='table') ## nope
> >   # path (' ', views.table, name='table.html') # nope
> >]
> >
> >*///
> >views.py
> >
> >from django.shortcuts import render
> >from django.http import HttpResponse
> ># Create your views here.
> >
> >def home (request):  /// correctly renders
> >return render (request, "home.html",{})
> >
> >def table (request): gives error
> >return HttpResponse ('This is a test Page')
> ># Tried the below code, nada
> ># return render (request, "table.html",{})
> >
> >*\
> >___
> >Tutor maillist  -  Tutor@python.org
> >To unsubscribe or change subscription options:
> >https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Django Query

2019-04-01 Thread Cameron Simpson

On 29Mar2019 21:18, nitin chandra  wrote:

Hi Everyone,
I need some guidance / corrections to my code.
I hosted a demo site on pythonanywhere.com and to test the initial
pages I wrote some test code.

[...]

Hi Nitin,

I looks like nobody has replied; this probably means that nobody has the 
required specialty expertise to help you. (I don't.)



Good news, put in 10 hrs, tried so many suggestion given on the net,
yet non worked. So finally mailing the list.


Might I suggest that you ask on the django-users mailing list, here:

 https://www.djangoproject.com/community/

You want the "Using Django" list there.

There's a guideline to posting here:

 https://code.djangoproject.com/wiki/UsingTheMailingList

but your post looks fairly good on the face of it.

Hoping this helps,
Cameron Simpson 



Objective : display main page with multiple links to other pages. Use
jQuery plugins, click the link on main page and open other pages.

The following path and pages are posted below.

Thanks

Nitin Chandra


ERROR
When I click on 'Table' link on 'home' page, the following error is displayed

http://selftech.pythonanywhere.com/table.html
Page not found (404)

Request Method:GET
Request URL:http://selftech.pythonanywhere.com/table.html

Using the URLconf defined in eduinfra.urls, Django tried these URL
patterns, in this order:

admin/
[name='home.html']

The current path, table.html, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.

+++

/home/selfTech/edu/tech/

__init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py

/home/selfTech/edu/tech/templates/

base.html
home.html
table.html
***
our 'base.html' code below (test code, gets rendered correctly)


 Navbar
 
   
 

 
   
 
   Home (current)
 
 
   Link
 
 
   Table
 
 
   Disabled
 
   
   
 
 Search
   
 

  *
home.html

{% extends 'base.html' %}

{% block content%}
Hello TEAM :)
{% endblock %}
***
table.html (gives ERROR 404)


   
   
   Name
   
   


*
/home/selfTech/edu/tech/

urls.py

from django.urls import path
from . import views

urlpatterns = [
   path('', views.home, name='home'),
   path('table/', views.table, name='table') ## various combo did not work
  # path (' ', views.table, name='table') ## nope
  # path (' ', views.table, name='table.html') # nope
]

*///
views.py

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def home (request):  /// correctly renders
   return render (request, "home.html",{})

def table (request): gives error
   return HttpResponse ('This is a test Page')
   # Tried the below code, nada
   # return render (request, "table.html",{})

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

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


Re: [Tutor] Python Regular Expressions (Re.sub) Function

2019-03-04 Thread Alan Gauld via Tutor
On 04/03/2019 08:04, Edward Kanja wrote:
> ... Unfortunately after i extract the data
> my output has too much of square brackets and by so doing the output cant
> be well exported in a csv file. 

I can't see the data so can't be definitive but the number of square
brackets shouldn't affect a CSV file (except that it will be messy to
read). Are you using the csv module to produce the csv file?
It is much safer to do that than to try to write a csv file yourself.

> I have worked on an idea of Re.sub function
> where i'm trying to replace all square brackets in my output with an empty
> string.

See Steve's reply.

> Below are images of what i have been working on.

Images don't work on this (and many other) mailing list.
The server sees them as potential security threats and
throws them away. Please put sample code directly in
the mail message or, if it is very long ( >100 lines?)
paste it on a pastebin type web site and include a link.

> 4.*try one code. 
> *6. try two code:
> *8.try four code.
> *10.try five code.
> *13.try six code.
Multiple versions of the code just results in confusion
as different people respond to different versions.
Pick one version that's closest to what you want and
use that as the basis of discussion. Ideally remove all
code that's not directly relevant to the problem,
eg the code that loads your data in the first place.
Show a small sample of input data and the output data.
Show us any error messages in full.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python Regular Expressions (Re.sub) Function

2019-03-04 Thread Steven D'Aprano
Hi Edward, and welcome.

Please remember that we're volunteers, doing this for free. Unless your 
problem is really interesting, you're not likely to get people 
volunteering to spend a long time slogging through multiple attachments, 
screenshots, at least five seperate attempts, etc.

By the way, most of your attachments have been deleted by the mailing 
list. Only things which it considers text files will get through.

Please try to simplify the question you are asking, and keep the code 
you show as short and simple as practical. You might find it helpful to 
read this:

http://www.sscce.org/

In the meantime, this might help you:

py> import re
py> text = "abcd[][]...[x]yz"
py> re.sub(r'\[|\]', '@', text)
'abcd...@x@yz'
py> re.sub(r'\[|\]', '', text)
'abcd...xyz'






On Mon, Mar 04, 2019 at 11:04:15AM +0300, Edward Kanja wrote:
> Hi there,
> Hope this finds you well, I'm working on a simple project to analyse data
> using
> regular expressions. I have successfully worked on a regular expression
> pattern
> that extracts data from my txt file. Unfortunately after i extract the data
> my output has too much of square brackets and by so doing the output cant
> be well exported in a csv file. I have worked on an idea of Re.sub function
> where i'm trying to replace all square brackets in my output with an empty
> string.
> Below are images of what i have been working on.
> 
> Explanations of the attachments and images named as follows:
> *1. mydata in txtfile. *This images shows how my data looks in the txt file
> although
> i have also attached the real txt file with the actual data below.
> *2. code for the output. *This image shows the regular expression that is
> well extracting the data from my txt file.
> 3. *my output. *This image shows the out after i ran my code . it shows the
> square brackets that are in my output and ones i need to do away with.
> 4.*tryone code. *This image shows my first try using re.sub to eliminate
> the square brackets.
> *5. tryone output.*This images shows the output i had after running the
> code in the image named tryone code.
> *6. try two code:*This image shows my second try using re.sub to eliminate
> the square brackets.
> *7.trytwo output.*This images shows the output i had after running the code
> in the image named trytwo code.
> *8.try four code.*This image shows my fourth try using re.sub to eliminate
> the square brackets.
> *9.try four output.* This images shows the output i had after running the
> code in the image named tryfour code.
> *10.try five code.*This image shows my number five try using re.sub to
> eliminate the square brackets
> *11.*  *try five output.*This images shows the output i had after running
> the code in the image named tryfive code.
> *12.line five name code regex.*This image shows the full code for the name
> regular expression with the re.sub function for the code
> in the image named try five code.
> *13.try six code.*This image shows my sixth try using re.sub to eliminate
> the square brackets
> *14. try six output.*This images shows the output i had after running the
> code in the image named tryfsix code
> *15.try six full name code.*This image shows the full code for the name
> regular expression with the re.sub function for the code
> in the image named try six code.
> *16. unon.TXT. *This is the txt file that has the data i am extracting.
> 
> Kindly assist and kindly copy my work email ( edward.mwa...@un.org ) when
> replying .
> Thanks alot.
> 
> Regards,
> Kanja Edward.
> P.O.BOX 1203-00300,
> NAIROBI.
> *+254720724793*
> www.linkedin.com/in/edward-kanja-bba16a106
> 

> --
> |Rawzeea NLKPP | VE11-Nairobi 
>| 20002254-MADIZ| 00   | 00   
> |Regular Scheme B | 15-JAN-2019 To 31-DEC-2019 | No   |
> ||
> | 3648 | 18-FEB-2020 | Yes | 03   
>|  .00 USD  | 0.00 USD  | Leased Commercially  
>  |   00.00 KES| No   |
> ||
> | R-9-01   | 00.00%  |0023.28 KES  |000.18 
> USD   |   |  1.0  |  0.00|  0.00  
>   | No  | 10-JAN-2019 To 31-DEC-2019|
> -

Re: [Tutor] Python Websocket Server

2019-02-14 Thread Mats Wichmann
On 2/14/19 9:44 AM, Simon Connah wrote:
> Hi,
> 
> I was wondering what the best practice for writing web socket servers in
> Python was in 2019? I found an old example on the web which used the
> tornado library but that was talking about Chrome 22 as the client which
> is ancient now so I'm not sure if things have changed?
> 
> Any suggestions on the best library to use would be greatfully accepted.
> I'd ideally like to be able to do it in an asynchronous manner.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


Full Stack Python's page on the topic has quite a lot of resources:

https://www.fullstackpython.com/websockets.html


The thing to keep in mind with old tutorials is that the state of
Python's own async support has evolved a lot recently.  Before, you
absolutely had to depend on a framework which would do the work of
supporting concurrenct connections or you would go insane, but now
you'll start to see examples, I expect, of doing simple things without
bringing in one of the frameworks.  (If your intent is production work,
the well tested frameworks are still going to be the best bet)



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


Re: [Tutor] Python Websocket Server

2019-02-14 Thread Alan Gauld via Tutor
On 14/02/2019 16:44, Simon Connah wrote:

> I was wondering what the best practice for writing web socket servers in 
> Python was in 2019? 

I can't answer that directly since I've never used web
sockets in Python (and only played with them in Java).
But...

> I found an old example on the web which used the 
> tornado library but that was talking about Chrome 22 as the client which 
> is ancient now so I'm not sure if things have changed?

THe Websocket API standard was finalized at the end of 2011
so since 2012 there should have been little or no changes.
I would therefore expect your Tornado tutorial to be
fairly reliable.

However, I'd suggest follow up questions are addressed to
either the main python list or to the Tornadso community
directly since it's a bit off the beaten path for the
tutor list community.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] python-files

2019-01-27 Thread Alan Gauld via Tutor
On 27/01/2019 14:57, Asad wrote:

> print("first:", args.first)
> print("second:", args.second)
> 
> When I execute the script it gives error :
> 
> python python_json_20001_oratest_v1.py "file1"
> ('first:', 'file1')
> ('second:', None)

Note that the second file is None.

> Traceback (most recent call last):
>   File "test.py", line 211, in 
> with open(args.second, 'r') as f :
> TypeError: coercing to Unicode: need string or buffer, NoneType found

Note that you get a TypeError because you passed None instead
of a valid filename.

> try :
> with open(args.second, 'r') as f :
>  for line in f:
> print line
> except IOError:
>  print "The default error is err-1 because file2 was not provided "

Note that you are trying to catch an IOError but you are getting a
TypeError. You need to add another except clause for the TypeError.
Or test for a None second file value at the start of your code...

> Does that mean my try and except block is not working because if
> args.second  is None as in this case then it should print "The default
> error is err-1 because file2 was not provided "

It is working. You just aren't catching the correct error type.
It will only type the message you've given if you get an
IOError, but the open() code isn't getting that far,
it's failing on the parameter type.

> Please advice ,

OK, I advise you to delete the text below where you no longer
need it. Some users pay by the byte and all this excess text
costs them money. More than 75% of your message is included
text that we have already seen.

> Thanks,
> 
> 
>> -- Forwarded message --
>> From: Peter Otten <__pete...@web.de>
>> To: tutor@python.org
...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] python-files

2019-01-27 Thread Peter Otten
Asad wrote:

> Hi All ,
> 
>   I tried the following code  :
> 
> parser = argparse.ArgumentParser()
> parser.add_argument("first")
> parser.add_argument("second", nargs="?")
> args = parser.parse_args()
> print("first:", args.first)
> 
> print("second:", args.second)
> 
> When I execute the script it gives error :
> 
> python python_json_20001_oratest_v1.py "file1"
> ('first:', 'file1')
> ('second:', None)
> Traceback (most recent call last):
>   File "test.py", line 211, in 
> with open(args.second, 'r') as f :
> TypeError: coercing to Unicode: need string or buffer, NoneType found
> 
> 
> if I see in line number 211 it with open(args.second, 'r') as f :
> 
> try :
> with open(args.second, 'r') as f :
>  for line in f:
> print line
> except IOError:
>  print "The default error is err-1 because file2 was not provided
>  "

How do you know that the file was not provided? The name might have been 
misspelt or the user lacks the permission to read it.

> Does that mean my try and except block is not working because if
> args.second  is None as in this case then it should print "The default
> error is err-1 because file2 was not provided "
> 
> Please advice ,

If you just want to terminate the script with a helpful message you should 
make the second argument mandatory, too:

parser = argparse.ArgumentParser()
parser.add_argument("first")
parser.add_argument("second")
args = parser.parse_args()

That way the parse_args() call will terminate the script and the user will 
see an error message immediately.

If for some reason you want to keep the argument optional you can check for 
None before trying to open the file:

if args.second is not None:
try:
with open(args.second, 'r') as f :
for line in f:
print line
except IOError as err:
print err  # print actually what happened, not what you guess
else:
print "File 'second' was not provided on the command line"



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


Re: [Tutor] python-files

2019-01-27 Thread Asad
Hi All ,

  I tried the following code  :

parser = argparse.ArgumentParser()
parser.add_argument("first")
parser.add_argument("second", nargs="?")
args = parser.parse_args()
print("first:", args.first)

print("second:", args.second)

When I execute the script it gives error :

python python_json_20001_oratest_v1.py "file1"
('first:', 'file1')
('second:', None)
Traceback (most recent call last):
  File "test.py", line 211, in 
with open(args.second, 'r') as f :
TypeError: coercing to Unicode: need string or buffer, NoneType found


if I see in line number 211 it with open(args.second, 'r') as f :

try :
with open(args.second, 'r') as f :
 for line in f:
print line
except IOError:
 print "The default error is err-1 because file2 was not provided "

Does that mean my try and except block is not working because if
args.second  is None as in this case then it should print "The default
error is err-1 because file2 was not provided "

Please advice ,

Thanks,


> -- Forwarded message --
> From: Peter Otten <__pete...@web.de>
> To: tutor@python.org
> Cc:
> Bcc:
> Date: Sun, 27 Jan 2019 10:30:12 +0100
> Subject: Re: [Tutor] python - files
> Cameron Simpson wrote:
>
> > Mats has mentioned the modules getopt and argparse etc. These are
> > primarily aimed at option parsing ("-v", "-o foo"). Your situation
> > occurs _after_ the option parsing (in your case, there are no options).
>
> Not argparse. The main advantage over optparse is its handling of
> positional
> arguments. Your custom logic
>
> >   def main(argv):
> > cmd = argv.pop(0)   # collect the command word
> > badopts = False
> > # mandatory first argument
> > if not argv:
> >   print("%s: missing first argument" % cmd, file=sys.stderr)
> >   badopts = True
> > else:
> >   first = argv.pop(0)
> >   # optional second argument
> >   if argv:
> > second = argv.pop(0)# explicit argument 2, use it
> >   else:
> > second = None   # or some otherdefault
> >   if argv:
> > print("%s: extra arguments: %r" % (cmd, argv), file=sys.stderr)
> > badopts = true
> > if badopts:
> >   print("%s: invalid invocation, aborting" % cmd, file=sys.stderr)
> >   return 2
> > ... work with first and second ...
>
> can roughly be replicated with the two lines
>
> parser.add_argument("first")
> parser.add_argument("second", nargs="?")
>
> A working script:
>
> $ cat test.py
> #!/usr/bin/python3
> import argparse
>
> def main():
> parser = argparse.ArgumentParser()
>
> parser.add_argument("first")
> parser.add_argument("second", nargs="?")
>
> args = parser.parse_args()
>
> print("first:", args.first)
> print("second:", args.second)
>
> if __name__ == "__main__":
> main()
>
> $ ./test.py
> usage: test.py [-h] first [second]
> test.py: error: the following arguments are required: first
>
> $ ./test.py -h
> usage: test.py [-h] first [second]
>
> positional arguments:
>   first
>   second
>
> optional arguments:
>   -h, --help  show this help message and exit
>
> $ ./test.py ONE
> first: ONE
> second: None
>
> $ ./test.py ONE TWO
> first: ONE
> second: TWO
>
> $ ./test.py ONE TWO THREE
> usage: test.py [-h] first [second]
> test.py: error: unrecognized arguments: THREE
>
> Argparse makes a usable standard command line interface easy to set up (if
> you need non-standard behaviour it gets a bit harder).
>
> There is also a companion module argcomplete (not in the stdlib) that
> enables autocompletion.
>
>
>
>
>
>
> -- Forwarded message --
> From: Cameron Simpson 
> To: tutor@python.org
> Cc:
> Bcc:
> Date: Sun, 27 Jan 2019 20:54:13 +1100
> Subject: Re: [Tutor] python - files
> On 27Jan2019 10:30, Peter Otten <__pete...@web.de> wrote:
> >Cameron Simpson wrote:
> >> Mats has mentioned the modules getopt and argparse etc. These are
> >> primarily aimed at option parsing ("-v", "-o foo"). Your situation
> >> occurs _after_ the option parsing (in your case, there are no options).
> >
> >Not argparse. The main advantage over optparse is its handling of
> positional
> >arguments.
>
> I stand c

Re: [Tutor] python - files

2019-01-27 Thread Cameron Simpson

On 27Jan2019 10:30, Peter Otten <__pete...@web.de> wrote:

Cameron Simpson wrote:

Mats has mentioned the modules getopt and argparse etc. These are
primarily aimed at option parsing ("-v", "-o foo"). Your situation
occurs _after_ the option parsing (in your case, there are no options).


Not argparse. The main advantage over optparse is its handling of positional
arguments.


I stand corrected.


Your custom logic

[...]

can roughly be replicated with the two lines

parser.add_argument("first")
parser.add_argument("second", nargs="?")
[... extended example ...]


Thank you!

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


Re: [Tutor] python - files

2019-01-27 Thread Peter Otten
Cameron Simpson wrote:

> Mats has mentioned the modules getopt and argparse etc. These are
> primarily aimed at option parsing ("-v", "-o foo"). Your situation
> occurs _after_ the option parsing (in your case, there are no options).

Not argparse. The main advantage over optparse is its handling of positional 
arguments. Your custom logic 

>   def main(argv):
> cmd = argv.pop(0)   # collect the command word
> badopts = False
> # mandatory first argument
> if not argv:
>   print("%s: missing first argument" % cmd, file=sys.stderr)
>   badopts = True
> else:
>   first = argv.pop(0)
>   # optional second argument
>   if argv:
> second = argv.pop(0)# explicit argument 2, use it
>   else:
> second = None   # or some otherdefault
>   if argv:
> print("%s: extra arguments: %r" % (cmd, argv), file=sys.stderr)
> badopts = true
> if badopts:
>   print("%s: invalid invocation, aborting" % cmd, file=sys.stderr)
>   return 2
> ... work with first and second ...

can roughly be replicated with the two lines

parser.add_argument("first")
parser.add_argument("second", nargs="?")

A working script:

$ cat test.py
#!/usr/bin/python3
import argparse

def main():
parser = argparse.ArgumentParser()

parser.add_argument("first")
parser.add_argument("second", nargs="?")

args = parser.parse_args()

print("first:", args.first)
print("second:", args.second)

if __name__ == "__main__":
main()

$ ./test.py
usage: test.py [-h] first [second]
test.py: error: the following arguments are required: first

$ ./test.py -h
usage: test.py [-h] first [second]

positional arguments:
  first
  second

optional arguments:
  -h, --help  show this help message and exit

$ ./test.py ONE
first: ONE
second: None

$ ./test.py ONE TWO
first: ONE
second: TWO

$ ./test.py ONE TWO THREE
usage: test.py [-h] first [second]
test.py: error: unrecognized arguments: THREE

Argparse makes a usable standard command line interface easy to set up (if 
you need non-standard behaviour it gets a bit harder).

There is also a companion module argcomplete (not in the stdlib) that 
enables autocompletion.


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


Re: [Tutor] python - files

2019-01-26 Thread Cameron Simpson
Mats has mentioned the modules getopt and argparse etc. These are 
primarily aimed at option parsing ("-v", "-o foo"). Your situation 
occurs _after_ the option parsing (in your case, there are no options).


Alan has talked about explicitly checking the length of sys.argv, much 
as you are doing, or accessing the (missing) argument and catching an 
exception.


There's a middle ground, which is a little more flexible, which is to 
_consume_ the command line arguments. The argv array is a list, and can 
be modified. So:


 def main(argv):
   cmd = argv.pop(0)   # collect the command word
   badopts = False
   # mandatory first argument
   if not argv:
 print("%s: missing first argument" % cmd, file=sys.stderr)
 badopts = True
   else:
 first = argv.pop(0)
 # optional second argument
 if argv:
   second = argv.pop(0)# explicit argument 2, use it
 else:
   second = None   # or some otherdefault
 if argv:
   print("%s: extra arguments: %r" % (cmd, argv), file=sys.stderr)
   badopts = true
   if badopts:
 print("%s: invalid invocation, aborting" % cmd, file=sys.stderr)
 return 2
   ... work with first and second ...

You can see here that we process the arguments from left to right, 
consuming the valid ones as we find them, and setting a flag for 
incorrect arguments. At the end we test the flag and abort if it is set.  
otherwise we process knowing we have valid values.


One important aspect of the above code is that you do not wire in an 
explicit length for sys.argv such as 2 or 3. That way you can easily 
change your code later if you want more arguments without running around 
adjusting such fixed numbers.


The other important aspect is usability: the above code complains about 
each issue it encounters, and finally quits with an additional message.  
In a real programme that addition message would include a "usage" 
message which describes the expected arguments.


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


Re: [Tutor] python - files

2019-01-26 Thread Mats Wichmann
On 1/26/19 1:20 AM, Asad wrote:
> Hi All ,
> 
>I would like to know how do I make and option file as an argument on
> command propmnt in python 

I don't know your context for asking this question. Alan has already
explained what you need to do for your issue, and whatever your needs it
is certainly worthwhile to understand how sys.argv works.


Just wanted to add, you find yourself having a need for processing a
non-trivial amount of arguments, this is a problem that is well
addressed in the Python community... the standard library now has three
modules for that - the "original" (UNIX/POSIX like) getopt module, the
currently preferred argparse module, and the optparse module it replaced
(which is now considered deprecated), as well as several very good
modules which are not in the standard library like docopt and click
(just naming two as examples, not endorsing anything).  So you don't
need to reinvent the wheel here if you have heavy duty needs - spend
your time on other parts of the problems you are solving.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python - files

2019-01-26 Thread Alan Gauld via Tutor
On 26/01/2019 08:20, Asad wrote:

>At present I using :
> 
>   if len(sys.argv) == 3:
> first = sys.argv[1]
> second = sys.argv[2]
>   else:
> print "enter the second argument"

> It works well for the following command :
> python test.py file1 file2

Correct because it tests if there are 2 arguments passed

> However I have another case where only file1 may be present so file1 is
> mandatory for this script to run however file2 is optionnal :
> 
>   if len(sys.argv) == 2:
> first_log = sys.argv[1]
> second_log = sys.argv[2]

But this will always give an error because you test
for only one argument but then try to read two!
It will always give an error.

> It gives error :
> 
>second_log = sys.argv[2]
> IndexError: list index out of range
> 
> 
> How do I acheive this because if python test.py file1 file2   then I would
> process both files .

You need to check how many arguments are passed.

if len(sys.argv) == 2:
   # read one argument
elif len(sys.argv) == 3:
  # read 2 arguments
elif ... etc

You could alternatively use exception handling to
catch the IndexError but I think the explicit test
in this case more clearly shows what you are intending.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python installtion

2019-01-13 Thread Stephen Nelson-Smith
Hi,

On Mon, Jan 7, 2019 at 11:11 AM mousumi sahu
 wrote:
>
> Dear Sir,
> I am trying to install python 2.7.10 on HPC. Python 2.6 has already been
> install on root. I do not have root authority. Please suggest me how can I
> do this.

Sorry - I replied to you directly, by accident.  Take 2, with reply all:

You need to do a local installation of Python, and set up your system
to use that in preference to the one at the system level.  Although
it's possible to do this with various manual steps, there's a really
handy tool you can use which will make your life easier, and allow you
to manage multiple versions of Python, which might be useful, if you
wanted, say, to be able to run both Python 2 and Python 3.  The tool
is called `pyenv`, and as long as you have a bash/zsh shell, and your
system has a C compiler and associated tools already installed, you
can install and use it.

The simplest approach is to clone the tool it from git, modify your
shell to use it, and then use it to install Python.  Here's a sample
way to set it up.  This won't necessarily match your exact
requirements, but you can try it, and please come back if you have any
further questions:

1. Clone the git repo into your home directory

git clone https://github.com/pyenv/pyenv.git ~/.pyenv

Pyenv is very simple, conceptually.  It's just a set of shell scripts
to automate the process of fetching, compiling, and installing
versions of Python, and then massaging your shell to make sure the
versions you have installed are used in preference to anything else.
So now you have the tool, you need to configure your shell to use it.
I'm going to assume you're using Bash.

2. Make sure the contents of the pyenv tool is available on your path

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile

Note - this might need to be .bashrc, or something else, depending on
your os/distro/setup.  However, in principle you're just making the
pyenv tool (which itself is just a set of shell scripts) available at
all times.

3. Set your shell to initialise the pyenv tool every time you start a new shell

echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv
init -)"\nfi' >> ~/.bash_profile

Again: this might need to be .bashrc

4. Now open a new shell, and check you have pyenv available:

$ pyenv
pyenv 1.2.9-2-g6309aaf2
Usage: pyenv  []

Some useful pyenv commands are:
   commandsList all available pyenv commands
   local   Set or show the local application-specific Python version
   global  Set or show the global Python version
   shell   Set or show the shell-specific Python version
   install Install a Python version using python-build
   uninstall   Uninstall a specific Python version
   rehash  Rehash pyenv shims (run this after installing executables)
   version Show the current Python version and its origin
   versionsList all Python versions available to pyenv
   which   Display the full path to an executable
   whence  List all Python versions that contain the given executable

See `pyenv help ' for information on a specific command.
For full documentation, see: https://github.com/pyenv/pyenv#readme

If you don't have pyenv working at this stage, come back and I'll help
you troubleshoot.  Assuming you do, continue:

5. Now you can install a version of Python, locally :

pyenv install --list

This shows you the various options of Pythons you can install.  You
want the latest 2.7:

pyenv install 2.7.15

This will fetch the source code of Python, and compile and install it
for you, and place it in your local shell environment, where you can
use it.

If this step doesn't work, it's probably because your system doesn't
have a compiler and associated tools.  I can help you troubleshoot
that, but ultimately you'll need support from your system
administrator at this point.

Assuming it's install Python, now you just need to tell your shell
that you want to use it:

pyenv local 2.7.15

This will make your shell find your 2.7.15 installation ahead of the
system python:

$ python --version
Python 2.7.15

Now you can run and use your Python.

Any further questions, sing out.

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


Re: [Tutor] Python installtion

2019-01-07 Thread Oscar Benjamin
On Mon, 7 Jan 2019 at 11:10, mousumi sahu  wrote:
>
> Dear Sir,
> I am trying to install python 2.7.10 on HPC. Python 2.6 has already been
> install on root. I do not have root authority. Please suggest me how can I
> do this.

Does HPC stand for High-Performance Computing? Are you trying to set
up Python to run your code in a Linux super computer / compute
cluster?

You can compile Python yourself easily enough.

First download Python. If the cluster has internet access you can do
that with this:

$ wget https://www.python.org/ftp/python/3.7.2/Python-3.7.2.tgz

Then compile Python:

$ tar -xzf Python-3.7.2.tgz
$ cd Python-3.7.2
$ ./configure
$ make
$ ./python

This can all take place in your user directory without needing root.

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


Re: [Tutor] Python installtion

2019-01-07 Thread Steven D'Aprano
On Mon, Jan 07, 2019 at 03:36:01PM +0530, mousumi sahu wrote:
> Dear Sir,
> I am trying to install python 2.7.10 on HPC. Python 2.6 has already been
> install on root. I do not have root authority. Please suggest me how can I
> do this.

What's HPC?

If you don't have root permission, do you have permission to install 
anything?

Are you comfortable with installing from source? You will need a 
C compiler. If everything works, it is easy, but if there are problems, 
it be difficult or impossible to solve them.

Would it be easier to just ask your system administrator to install it 
for you?


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


Re: [Tutor] Python

2018-12-20 Thread Steven D'Aprano
On Thu, Dec 20, 2018 at 10:49:25AM -0500, Mary Sauerland wrote:

> I want to get rid of words that are less than three characters


> f1_name = "/Users/marysauerland/Documents/file1.txt"
> #the opinions
> f2_name = "/Users/marysauerland/Documents/file2.txt"
> #the constitution

Better than comments are meaningful file names:

opinions_filename = "/Users/marysauerland/Documents/file1.txt"
constitution_filename = "/Users/marysauerland/Documents/file2.txt"

> def read_words(words_file):
> return [word.upper() for line in open(words_file, 'r') for word in 
> line.split()]

Don't try to do too much in a single line of code. While technically 
that should work (I haven't tried it to see that it actually does) it 
would be better written as:

def read_words(words_file):
with open(words_file, 'r') as f:
return [word.upper() for line in f for word in line.split()]

This also has the advantage of ensuring that the file is closed after 
the words are read. In your earlier version, it is possible for the file 
to remain locked in an open state.

Note that in this case Python's definition of "word" may not agree with 
the human reader's definition of a word. For example, Python, being 
rather simple-minded, will include punctuation in words so that 

"HELLO"
"HELLO."

count as different words. Oh well, that's something that can be adjusted 
later. For now, let's just go with the simple-minded definition of a 
word, and worry about adjusting it to something more specialised later.



> read_words(f1_name)
> #performs the function on the file

The above line of code (and comment) are pointless. The function is 
called, the file is read, the words are generated, and then immediately 
thrown away. To use the words, you need to assign them to a variable, as 
you do below:


> set1 = set(read_words(f1_name))
> #makes each word into a set and removes duplicate words

A meaningful name is better. Also the comment is inaccurate: it is not 
that *each individual* word is turned into a set, but that the *list* of 
all the words are turned into a set. So better would be:

opinions_words = set(read_words(opinions_filename))
constitition_words = set(read_words(constitution_filename))

This gives us the perfect opportunity to skip short words:

opinions_words = set(
word for word in read_words(opinions_filename) if len(word) >= 3)
constitition_words = set(
word for word in read_words(constitution_filename) if len(word) >= 3)


Now you have two sets of unique words, each word guaranteed to be at 
least 3 characters long.

The next thing you try to do is count how many words appear in each set. 
You do it with a double loop:

> count_same_words = 0
> for word in set1:
> if word in set2:
> count_same_words += 1

but the brilliant thing about sets is that they already know how to do 
this themselves! Let's see the sorts of operations sets understand:


py> set1 = set("abcdefgh")
py> set2 = set("defghijk")
py> set1 & set2  # the intersection (overlap) of both sets
{'h', 'd', 'f', 'g', 'e'}
py> set1 | set2  # the union (combination) of both sets
{'f', 'd', 'c', 'b', 'h', 'i', 'k', 'j', 'a', 'g', 'e'}
py> set1 ^ set2  # items in one or the other but not both sets
{'i', 'k', 'c', 'b', 'j', 'a'}
py> set1 - set2  # items in set1 but not set2
{'c', 'b', 'a'}


(In the above, "py>" is the Python prompt. On your computer, your prompt 
is probably set to ">>>".)

Can you see which set operation, one of & | ^ or - , you would use to 
get the set of words which appear in both sets? Hint: it isn't the - 
operation. If you wanted to know how many words appear in the 
constitution but NOT in the opinions, you could write:


word_count = len(constitition_words - opinions_words)


Does that give you a hint how to approach this?



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


Re: [Tutor] Python

2018-12-20 Thread Avi Gross
Mary,

Mary,

It is often best to develop and test small parts of the project where you
can easily play with it, then move it into more complex configurations like
a function body

Here is your code:

def read_words(words_file):
return [word.upper() for line in open(words_file, 'r') for word in
line.split()]

I made a file on my local system and this works:

def read_words(words_file):
return [word.upper() for line in open(words_file, 'r') for word in
line.split()]

now you are returning an uppercase version of the current 'word" stored in
word. So what is the length of that word?

Here is the modified variation on your code:

>>> [word.upper() for line in open('TESTINK.txt', 'r') for word in
line.split()]
['THIS', 'IS', 'LINE', 'ONE', 'AND', 'THIS', 'IS', 'ANOTHER', 'LINE',
'JUST', 'TO', 'TEST', 'WITH.']

Here is yet another modification showing the length, instead:

>>> [len(word) for line in open('TESTINK.txt', 'r') for word in
line.split()]
[4, 2, 4, 3, 3, 4, 2, 7, 4, 4, 2, 4, 5]

By your rules, you want to only keep those words where "len(word) > 3"

So where in the list comprehension would you add this an if condition to get
this?

['THIS', 'LINE', 'THIS', 'ANOTHER', 'LINE', 'JUST', 'TEST', 'WITH.']

Since you read in all your data using the same function, you might even make
it take an optional value to cut at, defaulting with 3 or even 0.

-Original Message-
From: Tutor  On Behalf Of
Mary Sauerland
Sent: Thursday, December 20, 2018 10:49 AM
To: tutor@python.org
Subject: [Tutor] Python

Hi, 

I want to get rid of words that are less than three characters but I keep
getting errors. I tried multiple ways but keep getting errors. 

Here is my code:

f1_name = "/Users/marysauerland/Documents/file1.txt"
#the opinions
f2_name = "/Users/marysauerland/Documents/file2.txt"
#the constitution


def read_words(words_file):
return [word.upper() for line in open(words_file, 'r') for word in
line.split()]


read_words(f1_name)
#performs the function on the file
set1 = set(read_words(f1_name))
#makes each word into a set and removes duplicate words
read_words(f2_name)
set2 = set(read_words(f2_name))

count_same_words = 0

for word in set1:
if word in set2:
count_same_words += 1
#comparing the set1 (set of unique words in the opinions) with set2 (set of
unique words in the constitution) and adding 1 for each matching word found
which is just counting the words
print(count_same_words)


Best, 

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

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


Re: [Tutor] Python

2018-12-20 Thread Mats Wichmann
On 12/20/18 8:49 AM, Mary Sauerland wrote:
> Hi, 
> 
> I want to get rid of words that are less than three characters but I keep 
> getting errors. I tried multiple ways but keep getting errors. 

Just a quick note or two:
> 
> Here is my code:
> 
> f1_name = "/Users/marysauerland/Documents/file1.txt"
> #the opinions
> f2_name = "/Users/marysauerland/Documents/file2.txt"
> #the constitution
> 
> 
> def read_words(words_file):
> return [word.upper() for line in open(words_file, 'r') for word in 
> line.split()]
> 
> 
> read_words(f1_name)

^^^ this line is meaningless.  "everything is an object" in Python. your
function returns a list object - which you don't do anything with. you
should assign a name to it, like:

constitution_words = read_words(f1_name)

Since no name is assigned to that object, Python sees it has no
references, and it is just lost.

and then...

> #performs the function on the file
> set1 = set(read_words(f1_name))
if you saved the object returned from the earlier call to the function,
then you don't need to call the function again, instead you convert the
saved list object to a set object.  We can't tell whether you have an
eventual use for the unfiltered list of words, or only the set of unique
words, the answer to that determines how you write this section.

picking a more descriptive name than set1 would be a good idea (and
f1_name as well, and others - when writing software, the hard part is
maintenance, where you or others have to go in later and fix or change
something.  using meaningful names really helps with that, so it's a
good habit to get into).

since you have sets consisting of words from your two documents, you may
as well use set operations to work with them.  Do you know the set
operation to find all of the members of one set that are also in another
set? hint: in set theory, that is called the intersection.

you say you are trying to remove short words, but there seems to be no
code to do that.  instead you seem to be solving a different problem?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python

2018-12-20 Thread Bob Gailer
On Dec 20, 2018 12:17 PM, "Mary Sauerland"  wrote:
>
> Hi,
>
> I want to get rid of words that are less than three characters but I keep
getting errors. I tried multiple ways but keep getting errors.

Hi Mary welcome to the tutor list. We love to help. We are a few
volunteers. It is very difficult for us to be mind readers. So please give
us more information. Especially what the error is you are getting. I
presume it is what we call a trace back. It is important that you copy the
entire traceback and paste it into the email. It will also be very helpful
if you gave us a sample of the two text files and the output You're
Expecting.

>
> Here is my code:
>
> f1_name = "/Users/marysauerland/Documents/file1.txt"
> #the opinions
> f2_name = "/Users/marysauerland/Documents/file2.txt"
> #the constitution
>
>
> def read_words(words_file):
> return [word.upper() for line in open(words_file, 'r') for word in
line.split()]
>
>
> read_words(f1_name)
> #performs the function on the file
> set1 = set(read_words(f1_name))
> #makes each word into a set and removes duplicate words
> read_words(f2_name)
> set2 = set(read_words(f2_name))
>
> count_same_words = 0
>
> for word in set1:
> if word in set2:
> count_same_words += 1
> #comparing the set1 (set of unique words in the opinions) with set2 (set
of unique words in the constitution) and adding 1 for each matching word
found which is just counting the words
> print(count_same_words)
>
>
> Best,
>
> Mary
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python function

2018-12-14 Thread Avi Gross
If you know what a CommaSeparatedValues file looks like, then reading ONE
LINE gives you enough info to answer the question about how many columns of
data it describes. 

-Original Message-
From: Tutor  On Behalf Of
Alan Gauld via Tutor
Sent: Thursday, December 13, 2018 7:47 PM
To: tutor@python.org
Subject: Re: [Tutor] Python function

On 13/12/2018 17:21, Sammy Lee wrote:
> How do I create a python function that opens a CSV file and determines 
> how many columns of data are in the file? The CSV files have been 
> randomly generated from https://www.mockaroo.com/
> 
> def csv_column_count(openfile):

You will find a bunch of stuff on creating functions in the Functions and
Modules topic of my tutorial.(see below)

You will find a bunch of stuff on handling files in the Handling Files topic
of my tutorial.(see below)

You will find a lot of help on using CSV files in the csv module
documentation in the standard library. (Or you could buy my book "Python
Projects" which has a section on the topic.)



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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

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


Re: [Tutor] Python function

2018-12-13 Thread Alan Gauld via Tutor
On 13/12/2018 17:21, Sammy Lee wrote:
> How do I create a python function that opens a CSV file and determines how 
> many columns
> of data are in the file? The CSV files have been randomly generated from 
> https://www.mockaroo.com/
> 
> def csv_column_count(openfile):

You will find a bunch of stuff on creating functions in the Functions
and Modules topic of my tutorial.(see below)

You will find a bunch of stuff on handling files in the Handling Files
topic of my tutorial.(see below)

You will find a lot of help on using CSV files in the csv module
documentation in the standard library. (Or you could buy my book
"Python Projects" which has a section on the topic.)



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python function

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 1:55 PM, "Sammy Lee"  wrote:
>
> How do I create a python function that opens a CSV file and determines
how many columns
> of data are in the file? The CSV files have been randomly generated from
https://www.mockaroo.com/
>
> def csv_column_count(openfile):

Same comments as I made in response to your other question. What part of
this do you need help with? do need to know how to read a file? do you need
to understand what a CSV file is? do you need to know how to parse a
character string?

The more specific you are the easier it is for us to help you.

Have you ever written a Python program? What has your course taught you so
far? Do you know how to write pseudocode?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python script errors

2018-12-12 Thread Steven D'Aprano
On Wed, Dec 12, 2018 at 06:57:09AM -0600, Ravi Kumar wrote:

> I know this occurs when the api response is nulls but how do I handle this?

if response is None:
handle None case
else:
handle non-None case



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


Re: [Tutor] Python script errors

2018-12-12 Thread Peter Otten
Ravi Kumar wrote:

> Hi,
> 
> I have developed a python script to get api calls for meraki
> clientlogevents Thanks for all the help previously  I am facing few errors
> such as
> 
> Json_string=r.json()
> 
> raw_decode
> raise JSONDecodeError("Expecting value", s, err.value) from None
> json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)

> 
> '{0:20}   {1:30}   {2:16}   {3:18}   {4:10} {5:11} '.format(
> deviceserial, type, macaddress,occurredAt, details))
> TypeError: unsupported format string passed to NoneType.__format__
> 
> I know this occurs when the api response is nulls but how do I handle
> this?

Say x can be a string or None. 

>>> for x in ["a string", None]:
... "{:20}".format(x)
... 
'a string'
Traceback (most recent call last):
  File "", line 2, in 
TypeError: unsupported format string passed to NoneType.__format__

The string can be padded while None does not support that. The best solution 
is usually to replace None with a string that cannot occur normally, and 
then to use that instead of None. Example:

>>> for x in ["a string", None]:
... "{:20}".format("#NONE" if x is None else x)
... 
'a string'
'#NONE   '

Slightly more convenient: you can force string conversion before padding:

>>> for x in ["a string", None]:
... "{!s:20}".format(x)
... 
'a string'
'None'




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


Re: [Tutor] Python script errors

2018-12-12 Thread Alan Gauld via Tutor
On 12/12/2018 12:57, Ravi Kumar wrote:

> '{0:20}   {1:30}   {2:16}   {3:18}   {4:10} {5:11} '.format(
> deviceserial, type, macaddress,occurredAt, details))
> TypeError: unsupported format string passed to NoneType.__format__

You have 6 format holders in your string but you only
pass 5 values. Also you seem to have a spurious closing
parens at the end of the call to format (after details).

But without seeing the full code or error message
it is hard to know what is going on.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] [Python 3] Threads status, join() and Semaphore queue

2018-11-24 Thread Cameron Simpson

On 24Nov2018 16:08, Dimitar Ivanov  wrote:
Your explanation definitely clears up quite a bit of my 
misunderstanding,

thank you for that!

There was a reason why I shy away from using Queue, but for the life of me
I can't remember right now what that reason was. I will have to modify my
code using your example and give it another try, I will make sure to let
you know if I run into any issues or additional questions. :)


Questions are welcome.

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


Re: [Tutor] [Python 3] Threads status, join() and Semaphore queue

2018-11-24 Thread Dimitar Ivanov
Hi Cameron,

Massive apologies for the delayed answer!

Your explanation definitely clears up quite a bit of my misunderstanding,
thank you for that!

There was a reason why I shy away from using Queue, but for the life of me
I can't remember right now what that reason was. I will have to modify my
code using your example and give it another try, I will make sure to let
you know if I run into any issues or additional questions. :)

Regards,
Dimitar

On Tue, 20 Nov 2018 at 08:39, Cameron Simpson  wrote:

> On 19Nov2018 23:52, Dimitar Ivanov  wrote:
> >I'm having a hard time getting my head around threads so I was hoping
> >someone who has better understanding of their underlying functionality
> >could lend me a helping hand, in particular how threads work with each
> >other when using thread.join() and Semaphore set with maximum value. I'll
> >try to keep it as clear and concise as possible, but please don't hesitate
> >to ask if anything about my approach is unclear or, frankly, awful.
> >
> >I'm writing a script that performs a couple of I/O operations and CLI
> >commands for each element in a list of IDs. The whole process takes a
> while
> >and may vary based on the ID, hence the threading approach sounded like
> the
> >best fit since next ID can start once space has freed up. I'm parsing an
> >extract of my code below and will explain what I can't properly understand
> >underneath.
>
> I'm just going to scatter a few random remarks about your code in here
> with your listing before addressing your other queries lower down...
>
> >file1.py
> >-
> >ids = []
> >threadsPool = []
> >for id in ids:
>
> The name "id" is unfortunate as it conflicts with the id() builtin
> function. Maybe "element_id"? Wordier, but also more clear.
>
> >  thread = threading.Thread(target=file2.runStuff, name=str(id), args=(id,
> >))
> >  threadsPool.append(thread)
> >for thread in threadsPool:
> >  thread.start()
>
> You could start each thread right after creating it if you wished.
>
> >for thread in threadsPool:
> >  print(thread.enumerate())
>
> "enumerate" is a function from the threading module, not a method of a
> Thread. So try:
>
>   print(threading.enumerate())
>
> Frankly I'm surprised that "thread.enumerate" works at all.
>
> >  print("Queuing thread" + str(thread))
> >  thread.join()
> >
> >file2.py
> >--
> >queue = threading.Semaphore(2)
>
> I'd be disinclined to call this a "queue", which usually implies a FIFO
> list of some variety: put things onto it, and pull things off it,
> usually first in first off. Maybe just "sem" or "thread_capacity" or
> something?
>
> >def runStuff(id):
> >  queue.acquire()
> >  print("Lock acquired for " + str(id))
> >  file3.doMoreStuff()
> >  file4.evenMoreStuff()
> >  queue.release()
> >
> >Onto my confusion - as long as I don't try to print information about the
> >thread that's being queued or the total amount of threads using
> >.enumerate(), the script is working absolutely flawlessly, each thread
> that
> >doesn't have a lock is waiting until it acquires it and then moves on. I
> >decided it'd be nice to be able to provide more information about which
> >thread starts next and how many threads are active right now (each can
> take
> >a different amount of time), however, when I tried to do that, my log was
> >showing me some pretty funky output which at first made me believe I've
> >messed up all my threads, example:
> >
> >
> ><<  2018-11-19 15:01:38,094 file2 [ID09] INFO - Lock acquired for
> >ID09 < this is from file2.py
> >-- some time later and other logs in here -
> >[<_MainThread(MainThread, started 140431033562880)>,  >140430614177536)>] < output from thread.enumerate(), file1.py
> ><<  2018-11-19 15:01:38,103 file1 [MainThread] DEBUG - Queuing thread -
> > < output from print() right
> >after thread.enumerate()
> >
> >After some head scratching, I believe I've finally tracked down the reason
> >for my confusion:
> >
> >The .start() loop starts the threads and the first 2 acquire a lock
> >immediately and start running, later on the .join() queue puts the rest in
> >waiting for lock, that's fine, what I didn't realize, of course, is that
> >the .join() loop goes through threads that have already been instantly
> >kicked off by the .start() loop (the first 2 threads since Semaphore
> allows
> >2 locks) and then my print in that loop is telling me that those threads
> >are being queued, except they aren't since they are already running, it's
> >just my text is telling me that, since I wasn't smart enough to realize
> >what's about to happen, as seen below:
> >
> ><<  2018-11-19 15:01:33,094 file1.py [MainThread] DEBUG - Queuing thread -
> > <--- makes it clear the thread has
> >already even finished
>
> Yes. The .join() has NO EFFECT on the Thread itself: it doesn't start it
> or stop it. It just waits for the Thread to complete. So yes, your log
> message is misleading.
>
> >Which finally gets me to my cry for hel

Re: [Tutor] [Python 3] Threads status, join() and Semaphore queue

2018-11-19 Thread Cameron Simpson

On 19Nov2018 23:52, Dimitar Ivanov  wrote:

I'm having a hard time getting my head around threads so I was hoping
someone who has better understanding of their underlying functionality
could lend me a helping hand, in particular how threads work with each
other when using thread.join() and Semaphore set with maximum value. I'll
try to keep it as clear and concise as possible, but please don't hesitate
to ask if anything about my approach is unclear or, frankly, awful.

I'm writing a script that performs a couple of I/O operations and CLI
commands for each element in a list of IDs. The whole process takes a while
and may vary based on the ID, hence the threading approach sounded like the
best fit since next ID can start once space has freed up. I'm parsing an
extract of my code below and will explain what I can't properly understand
underneath.


I'm just going to scatter a few random remarks about your code in here 
with your listing before addressing your other queries lower down...



file1.py
-
ids = []
threadsPool = []
for id in ids:


The name "id" is unfortunate as it conflicts with the id() builtin 
function. Maybe "element_id"? Wordier, but also more clear.



 thread = threading.Thread(target=file2.runStuff, name=str(id), args=(id,
))
 threadsPool.append(thread)
for thread in threadsPool:
 thread.start()


You could start each thread right after creating it if you wished.


for thread in threadsPool:
 print(thread.enumerate())


"enumerate" is a function from the threading module, not a method of a 
Thread. So try:


 print(threading.enumerate())

Frankly I'm surprised that "thread.enumerate" works at all.


 print("Queuing thread" + str(thread))
 thread.join()

file2.py
--
queue = threading.Semaphore(2)


I'd be disinclined to call this a "queue", which usually implies a FIFO 
list of some variety: put things onto it, and pull things off it, 
usually first in first off. Maybe just "sem" or "thread_capacity" or 
something?



def runStuff(id):
 queue.acquire()
 print("Lock acquired for " + str(id))
 file3.doMoreStuff()
 file4.evenMoreStuff()
 queue.release()

Onto my confusion - as long as I don't try to print information about the
thread that's being queued or the total amount of threads using
.enumerate(), the script is working absolutely flawlessly, each thread that
doesn't have a lock is waiting until it acquires it and then moves on. I
decided it'd be nice to be able to provide more information about which
thread starts next and how many threads are active right now (each can take
a different amount of time), however, when I tried to do that, my log was
showing me some pretty funky output which at first made me believe I've
messed up all my threads, example:


<<  2018-11-19 15:01:38,094 file2 [ID09] INFO - Lock acquired for
ID09 < this is from file2.py
-- some time later and other logs in here -
[<_MainThread(MainThread, started 140431033562880)>, ] < output from thread.enumerate(), file1.py
<<  2018-11-19 15:01:38,103 file1 [MainThread] DEBUG - Queuing thread -
 < output from print() right
after thread.enumerate()

After some head scratching, I believe I've finally tracked down the reason
for my confusion:

The .start() loop starts the threads and the first 2 acquire a lock
immediately and start running, later on the .join() queue puts the rest in
waiting for lock, that's fine, what I didn't realize, of course, is that
the .join() loop goes through threads that have already been instantly
kicked off by the .start() loop (the first 2 threads since Semaphore allows
2 locks) and then my print in that loop is telling me that those threads
are being queued, except they aren't since they are already running, it's
just my text is telling me that, since I wasn't smart enough to realize
what's about to happen, as seen below:

<<  2018-11-19 15:01:33,094 file1.py [MainThread] DEBUG - Queuing thread -
 <--- makes it clear the thread has
already even finished


Yes. The .join() has NO EFFECT on the Thread itself: it doesn't start it 
or stop it. It just waits for the Thread to complete. So yes, your log 
message is misleading.



Which finally gets me to my cry for help - I know I can't modify the
threadsPool list to remove the threads already created on the fly, so I can
have only the ones pending to be queued in the 2nd loop, but for the life
of me I can't think of a proper way to try and extract some information
about what threads are still going (or rather, have finished since
thread.enumerate() shows both running and queued).


Well, what you'd probably _like_ is a way to be told about each Thread 
as it completes, and report them then. Which you can do using a Queue, 
getting each Thread to report its completion to the Queue as it happens.


Untested example:

 from queue import Queue
 q = Queue()
 threadsPool = []
 for id in ids:
   thread = threading.Thread(target=file2.runStuff, name=str(id), args=(id, q))
   threadsPool.append(thread)


Re: [Tutor] Python 3.6 update?

2018-10-27 Thread Jim

On 10/25/18 5:30 PM, Mats Wichmann wrote:

On 10/25/2018 03:07 PM, Jim wrote:

Mint 18.1
Default python3 = 3.5
Python 3.6 installed for use by a virtual environment.



Update manager just informed me of an update for python 3.6 to 3.6.7-1.
When I started to install it, I got a dialog saying:

this upgrade will trigger additional changes. The following 2 packages
will be removed  python3-dev & python3-venv.

I am wondering what will happen to the virtual environment I have
installed that uses python 3.6. Will the 2 packages be replaced and the
virtual environment continue to work or is there some other steps I will
need to take.

Regards,  Jim


we can't tell that from here.

Not sure whose bright idea it was to package venv separately, since it's
supposed to be a "standard" part of Python 3 since 3.3 (I guess it's
"batteries included, but you still have to install the batteries" :).
But removing the package doesn't affect a created virtual environment.

What can affect a created virtual environment is how it was created -
there are a few options, some combinations of which could leave things
going missing from underneath if the Python it's created from is
upgraded.  venv has an upgrade option that might help with that.

Mint forums (and probably Ubuntu forums) could be further help...
usually somebody's been through it before.


Asked on ubuntu forumn.



thanks,  Jim


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


Re: [Tutor] Python Help

2018-10-26 Thread Alan Gauld via Tutor
On 26/10/2018 18:20, Adam Eyring wrote:

> beef = (beefmeals * 15.95)

Note that the parens here are completely redundant.
They don't break anything but neither do they
contribute anything.

WE already have LISP(*) for those who love parens,
no need for (so many of) them in Python

(*)Lots of Irrelevant Silly Parentheses :

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python Help

2018-10-26 Thread Adam Eyring
On Fri, Oct 26, 2018 at 3:03 PM Bob Gailer  wrote:

> On Oct 26, 2018 1:20 PM, "Adam Eyring"  wrote:
> >
> > Try this cleaned up version with colons in the right places, dollar
> signs removed, and other corrections:
>
> Does it do what you want?
>
> > beefmeals=int(input("Enter number of beef meals: "))
> > shitmeals=int(input("Enter number of vegan meals: "))
> > party = beefmeals + shitmeals
> > print("Total meals", party)
> > a = 0
> > b = 0
> > c = 0
>
> There is no need for three variables here. You only need one to represent
> room cost. If you make that change then you will also not need to
> initialize the room cost variable. Makes the code simpler to maintain and
> read and understand.
>
> > if party <= 50:
> >
> > a=75
> > print("Room cost $75")
>
> If you use one variable for room cost then you can use just one print just
> above the room tax line.
>
> > elif party <= 150:
> >
> > b=150
> > print("Room cost $150")
> > else:
> > c=250
> > print("Room cost $250")
> > roomtax = party * 0.065
> > print("Room tx", roomtax)
> > print("Beef Meals", beefmeals)
> > beef = (beefmeals * 15.95)
> > print("Beef cost", beef)
> > print("Vegan Meals", shitmeals)
> > shit = (shitmeals * 10.95)
> > print("Vegan cost", shit)
> > cost=(beef + shit)
> > grat= cost * 0.18
> > print("Gratuity", grat)
> > GT = print("Grand total", grat + beef + shit + a + b + c)
>
> The print function always returns None. Therefore the effect of this
> statement is to assign None to GT. Also note that you don't use GT later on.
>

You're right - GT is not needed. The print does work with or without "GT
=" in Python 3.6.5, though.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help

2018-10-26 Thread Adam Eyring
Try this cleaned up version with colons in the right places, dollar signs
removed, and other corrections:

beefmeals=int(input("Enter number of beef meals: "))
shitmeals=int(input("Enter number of vegan meals: "))
party = beefmeals + shitmeals
print("Total meals", party)
a = 0
b = 0
c = 0
if party <= 50:
a=75
print("Room cost $75")
elif party <= 150:
b=150
print("Room cost $150")
else:
c=250
print("Room cost $250")
roomtax = party * 0.065
print("Room tx", roomtax)
print("Beef Meals", beefmeals)
beef = (beefmeals * 15.95)
print("Beef cost", beef)
print("Vegan Meals", shitmeals)
shit = (shitmeals * 10.95)
print("Vegan cost", shit)
cost=(beef + shit)
grat= cost * 0.18
print("Gratuity", grat)
GT = print("Grand total", grat + beef + shit + a + b + c)

On Fri, Oct 26, 2018 at 7:28 AM Bob Gailer  wrote:

> On Oct 26, 2018 6:11 AM, "Ben Placella" 
> wrote:
> >
> > I need to write code that runs a  cost calculating program with many
> > different variables and I honestly don't understand it
>
> Could you be more specific? What exactly don't you understand, or even
> better what do you understand?
>
> my code is:
>
> How could you have written so much code without understanding it?
>
> > beefmeals=int(input("Enter number of beef meals: "))
> > shitmeals=int(input("Enter number of vegan meals: "))
> > party=beefmeals+shitmeals
> > print(party)
> > if party<=50
>
> Something is missing from that last statement. Can you tell what it is? Do
> you know how to find out? Hint use help.
>
> Hint 2 it is also missing from the elif and else statements.
>
> > a=75
> > print("Room cost $75")
> > elif party <=150
> > b=150
> > print("Room cost $150")
> > else
> > c=250
> > print("Room cost $250")
> > roomtax=party*0.065
> > print(roomtax)
> > print("Beef Meals", beefmeals)
> > $beef=(beefmeals*15.95)
> > print($beef)
> > print("Beef cost", $$beef)
> > print("Vegan Meals", shitmeals)
> > $shit=(shitmeals*10.95)
> > print($shit)
> > cost=($beef+$shit)
> > grat=cost*0.18)
> > print(grat)
> > GT=(grat+$beef+$shit+(a,b,c))
>
> There is a convention in Python that and all uppercase name is a constant.
> This is not a requirement.
>
> > print(GT)
> >
> > This is what the output is supposed to be:
>
> I don't see any output here. Alan''s responses may help you figure that
> out.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help

2018-10-26 Thread Bob Gailer
On Oct 26, 2018 1:20 PM, "Adam Eyring"  wrote:
>
> Try this cleaned up version with colons in the right places, dollar signs
removed, and other corrections:

Does it do what you want?

> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))
> party = beefmeals + shitmeals
> print("Total meals", party)
> a = 0
> b = 0
> c = 0

There is no need for three variables here. You only need one to represent
room cost. If you make that change then you will also not need to
initialize the room cost variable. Makes the code simpler to maintain and
read and understand.

> if party <= 50:
>
> a=75
> print("Room cost $75")

If you use one variable for room cost then you can use just one print just
above the room tax line.

> elif party <= 150:
>
> b=150
> print("Room cost $150")
> else:
> c=250
> print("Room cost $250")
> roomtax = party * 0.065
> print("Room tx", roomtax)
> print("Beef Meals", beefmeals)
> beef = (beefmeals * 15.95)
> print("Beef cost", beef)
> print("Vegan Meals", shitmeals)
> shit = (shitmeals * 10.95)
> print("Vegan cost", shit)
> cost=(beef + shit)
> grat= cost * 0.18
> print("Gratuity", grat)
> GT = print("Grand total", grat + beef + shit + a + b + c)

The print function always returns None. Therefore the effect of this
statement is to assign None to GT. Also note that you don't use GT later on.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help

2018-10-26 Thread Bob Gailer
On Oct 26, 2018 6:11 AM, "Ben Placella"  wrote:
>
> I need to write code that runs a  cost calculating program with many
> different variables and I honestly don't understand it

Could you be more specific? What exactly don't you understand, or even
better what do you understand?

my code is:

How could you have written so much code without understanding it?

> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))
> party=beefmeals+shitmeals
> print(party)
> if party<=50

Something is missing from that last statement. Can you tell what it is? Do
you know how to find out? Hint use help.

Hint 2 it is also missing from the elif and else statements.

> a=75
> print("Room cost $75")
> elif party <=150
> b=150
> print("Room cost $150")
> else
> c=250
> print("Room cost $250")
> roomtax=party*0.065
> print(roomtax)
> print("Beef Meals", beefmeals)
> $beef=(beefmeals*15.95)
> print($beef)
> print("Beef cost", $$beef)
> print("Vegan Meals", shitmeals)
> $shit=(shitmeals*10.95)
> print($shit)
> cost=($beef+$shit)
> grat=cost*0.18)
> print(grat)
> GT=(grat+$beef+$shit+(a,b,c))

There is a convention in Python that and all uppercase name is a constant.
This is not a requirement.

> print(GT)
>
> This is what the output is supposed to be:

I don't see any output here. Alan''s responses may help you figure that out.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help

2018-10-26 Thread Alan Gauld via Tutor
On 25/10/2018 23:14, Ben Placella wrote:

Please always post code in plain text not HTML or Rich text.
Otherwise we lose all the formatting which is important in Python.

> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))
> party=beefmeals+shitmeals
> print(party)
> if party<=50

Python control statements are terminated by a colon(:)

> $beef=(beefmeals*15.95)

$ signs in front of variable names are an error in Python


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python Help (shits killing me)

2018-10-26 Thread Steven D'Aprano
On Thu, Oct 25, 2018 at 06:13:31PM -0400, Ben Placella wrote:
> So I have to make a fibonacci sequence, and I'm not sure what is wrong with
> my code
[...]

> attached is a photo of what the output SHOULD look like

No it isn't. For security (anti-spam, anti-virus) reasons, this mailing 
list deletes non-text attachments.

Code is text. Unless you edit your code with Photoshop, don't take 
screenshots or photos of the code. COPY AND PASTE the code, and any 
expected results, or error messages, as TEXT.

Text can be copied, edited, and pasted into the interpreter and run.

Photos of text can't be edited, or run in the interpeter. Screen-readers 
can't read them, making them invisible to the blind or visually 
impaired. Photos of text are useless for programming.

When you run your code, what error do you get? COPY AND PASTE the entire 
traceback, starting from the line "Traceback: ..." and including the 
error message at the end.


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


Re: [Tutor] Python Help

2018-10-26 Thread Steven D'Aprano
On Thu, Oct 25, 2018 at 06:14:41PM -0400, Ben Placella wrote:
> I need to write code that runs a  cost calculating program with many
> different variables and I honestly don't understand it, my code is:
> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))

What version of Python are you using?

> party=beefmeals+shitmeals
> print(party)
> if party<=50
> a=75

You have lost the indentation, making your code invalid.

Also, you are probably getting a SyntaxError when you try to run your 
code. As always, please COPY AND PASTE (don't retype it from memory, or 
take a photo) the entire traceback, starting from the line 
"Traceback..." and ending with the error message.


> print("Room cost $75")
> elif party <=150
> b=150
> print("Room cost $150")
> else
> c=250
> print("Room cost $250")

That's two more syntax errors.


> $beef=(beefmeals*15.95)

Dollar signs aren't used for Python variables.


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


Re: [Tutor] Python Help (shits killing me)

2018-10-26 Thread Alan Gauld via Tutor
Plain text is preferred for code since otherwise the mail
system removes all indentation making the code hard to understand.

On 25/10/2018 23:13, Ben Placella wrote:
> So I have to make a fibonacci sequence, and I'm not sure what is wrong with
> my code
> #This program illustrates the fibonacci sequence
> nterms=int(input("Please enter how many terms you would like to know: "))
> n1 = 1
> n2 = 1
> count = 0
> if nterms <= 0:
> print("Please enter a positive integer")
> elif nterms == 1:
> print("Fibonacci sequence upto",nterms,":")
> print(n1)
> else:
> print("Fibonacci sequence upto",nterms,":")
> while count < nterms:
> print(n1,end=' , ')
> nth = n1 + n

I suspect that n should be n2?

> n1 = n2
> n2 = nth

BTW in Python you can do that set of assignments more
concisely as

n1,n2 = n2, n1+n2

with no temporary variable required.

> count += 1

And rather than using a while loop and manually
maintaining a count you could just use a for loop:

for count in range(nterms):

It's slightly more reliable and a lot more "pythonic".

> attached is a photo of what the output SHOULD look like

This is a text only list so images or other binary files
are stripped off by the server. Please, in future,
cut n' paste any output into the mail body.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python Help (shits killing me)

2018-10-26 Thread Andrew Van Valkenburg
nth = n1 + n

I don't see where n is defined anywhere.  Should be n2?

On Fri, Oct 26, 2018 at 6:09 AM Ben Placella 
wrote:

> So I have to make a fibonacci sequence, and I'm not sure what is wrong with
> my code
> #This program illustrates the fibonacci sequence
> nterms=int(input("Please enter how many terms you would like to know: "))
> n1 = 1
> n2 = 1
> count = 0
> if nterms <= 0:
> print("Please enter a positive integer")
> elif nterms == 1:
> print("Fibonacci sequence upto",nterms,":")
> print(n1)
> else:
> print("Fibonacci sequence upto",nterms,":")
> while count < nterms:
> print(n1,end=' , ')
> nth = n1 + n
> n1 = n2
> n2 = nth
> count += 1
>
> attached is a photo of what the output SHOULD look like
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.6 update?

2018-10-25 Thread Mats Wichmann
On 10/25/2018 03:07 PM, Jim wrote:
> Mint 18.1
> Default python3 = 3.5
> Python 3.6 installed for use by a virtual environment.
> 
> 
> 
> Update manager just informed me of an update for python 3.6 to 3.6.7-1.
> When I started to install it, I got a dialog saying:
> 
> this upgrade will trigger additional changes. The following 2 packages
> will be removed  python3-dev & python3-venv.
> 
> I am wondering what will happen to the virtual environment I have
> installed that uses python 3.6. Will the 2 packages be replaced and the
> virtual environment continue to work or is there some other steps I will
> need to take.
> 
> Regards,  Jim

we can't tell that from here.

Not sure whose bright idea it was to package venv separately, since it's
supposed to be a "standard" part of Python 3 since 3.3 (I guess it's
"batteries included, but you still have to install the batteries" :).
But removing the package doesn't affect a created virtual environment.

What can affect a created virtual environment is how it was created -
there are a few options, some combinations of which could leave things
going missing from underneath if the Python it's created from is
upgraded.  venv has an upgrade option that might help with that.

Mint forums (and probably Ubuntu forums) could be further help...
usually somebody's been through it before.

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


Re: [Tutor] python game error

2018-10-15 Thread Peter Otten
Alan Gauld via Tutor wrote:

> On 15/10/18 08:57, Peter Otten wrote:
> 
>> By the way, you do not need a map (dict) at all to implement a game like
>> this, you may return the next scene directly. A sketch:
>> 
>> class Bridge:
>> def enter(self):
>> ...
>> action = ...
>> if action == "jump off the bridge":
>> return Death("You are eaten by the piranhas")
>> else:
>> ...
> 
> That was my initial thought when I saw this but thee is one
> caveat. The original design creates a single instance of a
> scene and returns that on each access. The suggestion above
> creates a new instance on every call. So if it is important
> to use the same instance each time then the map is a
> better solution.
> 
> (Although you could instead create a class variable holding
> the first instance of itself then use a class  constructor
> to either create the instance or access the class variable...)
> 

Or, to keep it really simple, return global class instances:

DEATH_BY_TORNADO = Death("The storm swept you off the bridge")

>> class Bridge:
>> def enter(self):
>> ...
>> action = ...
   if action == "tornado":
   return DEATH_BY_TORNADO

One advantage of both variants is that tools like pylint are likely to catch 
spelling errors like the one that prompted the initial question.

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


Re: [Tutor] python game error

2018-10-15 Thread Alan Gauld via Tutor
On 15/10/18 08:57, Peter Otten wrote:

> By the way, you do not need a map (dict) at all to implement a game like 
> this, you may return the next scene directly. A sketch:
> 
> class Bridge:
> def enter(self):
> ...
> action = ...
> if action == "jump off the bridge":
> return Death("You are eaten by the piranhas")
> else:
> ...

That was my initial thought when I saw this but thee is one
caveat. The original design creates a single instance of a
scene and returns that on each access. The suggestion above
creates a new instance on every call. So if it is important
to use the same instance each time then the map is a
better solution.

(Although you could instead create a class variable holding
the first instance of itself then use a class  constructor
to either create the instance or access the class variable...)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] python game error

2018-10-15 Thread Peter Otten
bob gailer wrote:


>  Python coding "trick"1  
> when I build a map I omit the () after the class e.g. 'death' = Death, 
> ... and apply them to the item retrieved from the map.
> 
> use a decorator to build the map dictionary:
> 
> # the decorator function:
> def add_to_map(cls, map={}): # map is initialized to a {} when function 
> is "compiled"
>  if cls:
>  map[cls.__name__] = cls # add entry to dictionary
>  return cls
>  else: return map
> 
> # apply decorator to class definitions
> # this will add 'Death': 
> @add_to_map
> class Death(Scene):
>  class_definition
> 
>   # ditto for all other classes based on Scene - then
> 
> class Map:
>  scenes  = add_to_map() # note when map is called with no arguments 
> it returns the dictionary

Hm, you have now replaced the dead simple

> class Map(object):
> scenes = {
> 'central_corridor': CentralCorridor(),
> 'laser_weapon_armory': LaserWeaponArmory(),
> 'the_bridge': TheBridge(),
> 'escape_pod': EscapePod(),
> 'death': Death()
> }

with a class decorator, a dunder name, a mutable default argument -- lots of 
clever Python specific stuff that I wouldn't put on a beginner's list of top 
priorities.

Don't use unless you spotted at least one bug in the code sample at first 
glance :)

By the way, you do not need a map (dict) at all to implement a game like 
this, you may return the next scene directly. A sketch:

class Bridge:
def enter(self):
...
action = ...
if action == "jump off the bridge":
return Death("You are eaten by the piranhas")
else:
...



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


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

More comments on code:
 guess = raw_input("[pod #]> ")
    if int(guess) != good_pod:
If user enters something that will not convert to integer an exception 
will be raised. For example

>>> int('a')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'a'

Either use try - except
- or
    good_pod = str(randint(1,5))
    guess = raw_input("[pod #]> ")
    if guess != good_pod:
- or if you import choice from random
    good_pod = choice('12345')

Migrating to a database (separating data from logic). Why?
- it keeps the code simple.
- makes adding / editing scenes easier.

Given a database (game.db) with 2 tables:
            table            columns
    scene_entry        scene, text, prompt
    scene_action       scene, action, text, next_scene

Example:
 CentralCorridor, The Gothons of Planet Percal #25 have invaded 
..., Do you shoot!, dodge!, or tell a joke?
 CentralCorridor, shoot!, Quick on the draw you yank out your 
, Death
 CentralCorridor, dodge!, Like a world class boxer you dodge 
, Death
 CentralCorridor, tell a joke!, Lucky for you they made 
you,, Laser_weapon_armory


The generic structure of a game program:
    next_scene = 'CentralCorridor'
    while next_scene != 'Finished':
        get text, prompt from scene_entry
        print entry text
        prompt user for action
        get text, next_scene from scene_action
        print text

A simple python game program utilizing the game database follows. You 
would first create c:/games/game.db
using a tool like SQLite Studio, or request a copy from me. It is up to 
you to fill in the rest of the various table rows.
What's missing? Code to handle the code and good_pod guesses. That will 
come later.


-- program --
import sqlite3 as sq

def sel(cols, rest, vals=(,)):
    # construct, execute a sql select statement from the arguments
    # get and return one row (there should be at most one)
    sql = "select " + cols + " from " + rest + ";"
    curs = conn.execute(sql, vals)
    x = curs.fetchone()
    if x: return x
    raise ValueError(sql, vals)

def game(next_scene):
    while next_scene != 'finished':
    text, prompt = sel("text, prompt", "scene_entry where scene = 
?", (next_scene,))

    print(text)
    action = input(prompt + '>') # tell a joke!
    text, next_scene = sel("text, next_scene", "scene_action where 
scene = ? and action= ?", (next_scene, action))

    print(text)

conn = sq.connect("c:/games/game.db")
game('CentralCorridor')
-- end program --


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


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

On 10/14/2018 1:42 PM, Mats Wichmann wrote:

Hint here: don't use 'map' as your own variable name, since it's a
built-in function.
Absolutely, I am always warning others about this gotcha. In this case 
map is local to add_to_map so it does not affect then global namespace.


The reason I used it here was because the OP was using map (actually 
Map). Duh!


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


Re: [Tutor] python game error

2018-10-14 Thread Mats Wichmann
On 10/14/2018 10:08 AM, bob gailer wrote:

>  Python coding "trick"1  
> when I build a map I omit the () after the class e.g. 'death' = Death,
> ... and apply them to the item retrieved from the map.
> 
> use a decorator to build the map dictionary:
> 
> # the decorator function:
> def add_to_map(cls, map={}): # map is initialized to a {} when function
> is "compiled"
>     if cls:
>         map[cls.__name__] = cls # add entry to dictionary
>         return cls
>     else: return map

Hint here: don't use 'map' as your own variable name, since it's a
built-in function. It's not that it won't work, but is likely to cause
confusion someday. Most "code inspection" systems will complain that you
are shadowing or redefining a builtin (terminology may vary).  The list
of builtins - thus names to avoid - is here:

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


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

More comments:

 User Friendly? 
I hope this game is not intended for actual use. No one will be able to 
guess the correct actions in a reasonable time. or 3 digit random code 
given 10 tries for any one code. I for one would give up pretty quickly.


The original colossal cave game is an excellent example of a 
user-friendly text adventure game. If you are using a Windows computer 
you can get a version from the Microsoft Store


It
- gives explicit directions
- keeps responses to a few words most chosen from a limited list or 
names of visible objects.


 Python coding "trick"1  
when I build a map I omit the () after the class e.g. 'death' = Death, 
... and apply them to the item retrieved from the map.


use a decorator to build the map dictionary:

# the decorator function:
def add_to_map(cls, map={}): # map is initialized to a {} when function 
is "compiled"

    if cls:
        map[cls.__name__] = cls # add entry to dictionary
        return cls
    else: return map

# apply decorator to class definitions
# this will add 'Death': 
@add_to_map
class Death(Scene):
    class_definition

 # ditto for all other classes based on Scene - then

class Map:
    scenes  = add_to_map() # note when map is called with no arguments 
it returns the dictionary


 Python coding "trick" 2 
instead of:     print(Death.quips[randint(0, len(self.quips)-1)])
try:                 print(random.choice(Death.quips)

 Python coding "trick" 3 
action = raw_input('>').title() # to make user input agree with class names

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


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

On 10/13/2018 4:25 AM, Mariam Haji wrote:
...
Your problem intrigued me enough to spend some time "fixing" your 
program so it will compile with no errors and run at least the initial 
case where I entered "shoot!"


Here are the problems I found: (line numbers refer to your original code)
- spelling error  return 'laser_weapon_armoury' - fixed
- line 122 there is no if preceding the elif - I added one
- line 160 returns 'finished'. There is no corresponding entry in Map.scenes
   - I added one and a corresponding class Finished.
- the logic for allowing 10 guesses of the code is flawed. It only 
allows 2 guesses.

  I will leave it up to you to figure out why.

In addition I
- used """ for all multi  line prints; a personal preference - it makes 
entry and reading easier.

- updated code so it will run under python 3. This involves:
  - changing print statements to print function calls
  - assigning input to raw_input for version 3
- added raise to Map.next_scene to handle undefined scenes

Try it out.

> how do I create a keyword to exit the game mid way?

You don't create keywords. To support mid-game exiting I added an abort 
method to Finished. Use:

Finished.abort('reason')

-- program --
from sys import exit, version
from random import randint
if versison[0] == '3':
    raw_input = input

class Scene(object):
    def enter(self):
    print("This scene is not yet configured. Subclass it and 
implement enter().")

    exit(1)

class Engine(object):

    def __init__(self, scene_map):
    self.scene_map = scene_map

    def play(self):
    current_scene = self.scene_map.opening_scene()
    while True:
    print("\n")
    next_scene_name = current_scene.enter()
    current_scene = self.scene_map.next_scene(next_scene_name)

class Death(Scene):

    quips = [
"You died. You Kinda suck at this.",
"Your mum would be proud if she were smarter.",
"Such a looser.",
"I have a small puppy that's better at this."
]

    def enter(self):
    print(Death.quips[randint(0, len(self.quips)-1)])
    exit(1)

class CentralCorridor(Scene):

    def enter(self):
    print("""The Gothons of Planet Percal #25 have invaded your 
ship and destroyed

Your entire crew, you are the only surviving memeber and your last
Mission is to get the neutron destruct a bomb from the weapons Armory
Put it in the bridge and blow the ship up after getting into an
escape pod

You're running down the central corridor to the Weapons Armory when
a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clow costume
flowing around his hate filled body. He's blocking the door to the
Armoury and about to pull a weapon to blast you.
Do you shoot!, dodge!, or tell a joke? enter below.""")
    action = raw_input("> ")
    if action == "shoot!":
    print("""Quick on the draw you yank out your blaster and 
fire it at the Gothon.

His clown costume is flowing and moving around his body, which throws
off your aim. Your laser hits his costume but misses him entirely. This
completely ruins his brand new costume his mother bought him, which
makes him fly into a rage and blast ou repeatedly in the face until
you are dead. Then he eats you""")
    return 'death'
    elif action == "dodge!":
    print("""Like a world class boxer you dodge, weave, slip 
and slide right

as the Gothon's blaster cranks a laser past your head
In the middle of your artful dodge your foot slips and you
bang your head on the metal wall and you pass out
You wake up shortly after, only to die as the Gothon stomps on
your head and eats you""")
    return 'death'
    elif action == "tell a joke":
    print("""Lucky for you they made you learn Gothon insults 
in the academy

you tell the one Gothon joke you know
Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq 
gur ubhfr.

The Gothon stops, tries not to laugh, he busts out laughing and can't move.
While he is laughing you run up and shoot him square in the head
putting him down, then jump through the Weapon Armory door.""")
    return 'laser_weapon_armory'
    else:
    print("DOES NOT COMPUTE!")
    return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
    print("""You do a drive roll into the weapon Armory, crouch and 
scan the room

for more Gothons that might be hiding. It's dead quiet, too quiet
You stand up and run to the far side of the room and find the
neutron bomb in it's container. There's a keypad lock on the box
Wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits""")
    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    guess = raw_input("[keypad]> ")
    guesses = 0
    while guess != code and guesses < 10:
    print("BZZZEE!")
    guesses += 1
    guess = raw_input("[keypad]> ")
    if guess == code

Re: [Tutor] python game error

2018-10-13 Thread Bob Gailer
suggestions:
1-Use triple-quoted strings:
  print """take the
short-cut!""'

2 - make the program much simpler to start with. The usual approach to
developing programs like this is to start simple get the simple things
working right then add more complicated scene descriptions.

Even better: separate data from logic. Create a sqlite database in which
you store the information about the various scenes. Then write a program
that does nothing but access the various database elements. This will
result in much much easier to read and maintain code, and much much easier
to read and maintain the description of the scenes. I realize this may
sound like a big chunk but it is well worth the effort to learn how to do
it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python game error

2018-10-13 Thread Peter Otten
Mariam Haji wrote:

> Hi guys,
> 
> I am still on the learn python the hard way.
> I built the below on python 2.7 and my OS is windows 7.
> 
> I am getting this error:
> Traceback (most recent call last):
>   File "ex43.py", line 205, in 
> a_game.play()
>   File "ex43.py", line 21, in play
> next_scene_name = current_scene.enter()
> AttributeError: 'NoneType' object has no attribute 'enter'

The value of current_scene is None here. If you dig a bit in your code 
looking for places where that can happen you end up with

> class Map(object):
> scenes = {
> 'central_corridor': CentralCorridor(),
> 'laser_weapon_armory': LaserWeaponArmory(),
> 'the_bridge': TheBridge(),
> 'escape_pod': EscapePod(),
> 'death': Death()
> }
> 
> def __init__(self, start_scene):
> self.start_scene = start_scene
> 
> def next_scene(self, scene_name):
> return Map.scenes.get(scene_name)

Map.scenes is a dict, and its get() method returns None when the lookup for 
a key fails. If you pass an unknown scene name to the next_scene() method it 
returns None rather than a Scene instance.

As a first step to fix this I recommend that you use the item lookup 
operator instead of the method:

  def next_scene(self, scene_name):
  return Map.scenes[scene_name]

This will fail immediately, and the error message should be more 
informative. I got:

Traceback (most recent call last):
  File "./game_mariam.py", line 181, in 
a_game.play()
  File "./game_mariam.py", line 20, in play
current_scene = self.scene_map.next_scene(next_scene_name)
  File "./game_mariam.py", line 173, in next_scene
return Map.scenes[scene_name]
KeyError: 'laser_weapon_armoury'

That is, you need to decide if you want British or American orthography.

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


Re: [Tutor] python game error

2018-10-13 Thread Steven D'Aprano
On Sat, Oct 13, 2018 at 11:25:20AM +0300, Mariam Haji wrote:
> Hi guys,
> 
> I am still on the learn python the hard way.
> I built the below on python 2.7 and my OS is windows 7.
> 
> I am getting this error:
> Traceback (most recent call last):
>   File "ex43.py", line 205, in 
> a_game.play()
>   File "ex43.py", line 21, in play
> next_scene_name = current_scene.enter()
> AttributeError: 'NoneType' object has no attribute 'enter'

The current_scene variable currently is set to None, instead of athe 
value that you think it has.

Try inserting the line 

print repr(current_scene), type(current_scene)

just before line 21. Then you need to work out why it is set to None, 
instead of whatever you expect it to be.

By the way, you shouldn't expect us to hunt through dozens or hundreds 
of lines of code trying to debug your program for you. We're volunteers, 
not being paid to do this. You should give us a *minimum* (small!) 
example of your program.

That might mean keeping two copies, one which has all the irrelevant 
code removed. (Like the dozens of calls to print -- not one 
single one of those lines of code could possibly have anything 
to do with the bug in your program.)

Removing that irrelevant code, cutting it down to a minimum, may even 
help you find the bug yourself! Please read this for more information:

http://sscce.org/

Even though this is written for Java programmers, the principles also 
apply to Python.


> Main code is as, an I have highlighted line 21 and 205 in green below.

Have you? That explains why the indentation is messed up for me, making 
the code impossible to understand correctly. And the green doesn't show up 
in my email program.

Code is PLAIN TEXT, with no formatting. When you add formatting, like 
colours, bold or italics, fancy fonts, animmated paperclips, etc, your 
email program will destroy the indentation and make it unusable.



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


Re: [Tutor] Python

2018-10-12 Thread Alan Gauld via Tutor
On 12/10/18 02:41, Tyler Travis via Tutor wrote:
> I used a shortcut by import the statistics function. 
...
> it does not print the expected output, 

Did you by any chance include your code as an attachment?
If so this mail server will strip it out as a security risk.
Please post any code in the body of your email
(using plain text) please.

If you didn't send your code at all then please do so
as we are not mind readers! :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python

2018-10-12 Thread Steven D'Aprano
On Thu, Oct 11, 2018 at 08:41:08PM -0500, Tyler Travis via Tutor wrote:

> I fully understand the concept of what I am trying to do 

I'm very glad that at least one of us understands what you are trying to 
do, but I have no clue what it is.


> and I know 
> that you can type out the algorithms to find mean, median, and mode 
> but I used a shortcut by import the statistics function. Which yields 
> the same results 

The same results as what?


> and the program passes with a 100% in the grading software 

Great!


> However, it does not print the expected output, but rather 
> some random sequence of characters and numbers. I do not understand 
> why. Do you know why?

Your computer is cursed? Your cat walked over the keyboard?

I don't understand how your two statements can be reconciled. You say 
that the program pass the grading software. Surely that means it must 
print the expected output. (How else will the grading software know it 
gives the correct results?)

But then you say it prints gibberish. So I imagine you are doing this:

print(mean([1, 2, 8, 9])  # expected output is "5"

# output actually printed is "dz!gwd{7p3^)n3d%hw8"
# and the grading software says "Correct, full marks!"

which makes no sense to me.

By the way, I'm the author of the statistics module, so I'm very glad to 
hear that you are using it, but if the point of the exercise is to write 
your own (simple?) versions of mean, median and mode, isn't it cheating 
to use the pre-written ones?



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


Re: [Tutor] Python

2018-10-12 Thread Mark Lawrence

On 12/10/18 02:41, Tyler Travis via Tutor wrote:

I fully understand the concept of what I am trying to do and I know that you 
can type out the algorithms to find mean, median, and mode but I used a 
shortcut by import the statistics function. Which yields the same results and 
the program passes with a 100% in the grading software However, it does not 
print the expected output, but rather some random sequence of characters and 
numbers. I do not understand why. Do you know why?



No, as I do not see any code, data, Python version or OS.

--
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] Python programming help!

2018-09-23 Thread V E G E T A L
Wow, didn't know attachments didn't work. I had posted my screenshot as an
attachment, never expected you to read my mind. I solved the problem, it
was a spelling mistake (I know, I'm stupid). Thank a lot though!

Στις Κυρ, 23 Σεπ 2018 - 16:25 ο χρήστης Bob Gailer 
έγραψε:

> On Sep 23, 2018 3:33 AM, "V E G E T A L" 
> wrote:
> >
> > Hello folks! So, I'm pretty much a noob still experimenting with basic
> > commands. I wanted to make a code that checks if the value of one
> variable
> > is less, equal or greater than the other. Pretty simple right? But then,
>
> > this problem emerged.
>
> What problem? I don't see any problem here. If you provided an attachment
> this email list does not forward attachments.
>
> The proper way is to copy and paste directly into the body of the email.
>
> If you did not attempt to show us the problem, why? You certainly can't
> expect us to read your mind.
>
> I would really love some help, since I'm stuck and
> > can't figure out what I've done wrong.
> >
> > PS: I'm using Anaconda and JupyterNotebook.
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python programming help!

2018-09-23 Thread Carlton Banks
Without having Seen the code, use og statements.. but please provide is the
code...

søn. 23. sep. 2018 15.26 skrev Bob Gailer :

> On Sep 23, 2018 3:33 AM, "V E G E T A L" 
> wrote:
> >
> > Hello folks! So, I'm pretty much a noob still experimenting with basic
> > commands. I wanted to make a code that checks if the value of one
> variable
> > is less, equal or greater than the other. Pretty simple right? But then,
>
> > this problem emerged.
>
> What problem? I don't see any problem here. If you provided an attachment
> this email list does not forward attachments.
>
> The proper way is to copy and paste directly into the body of the email.
>
> If you did not attempt to show us the problem, why? You certainly can't
> expect us to read your mind.
>
> I would really love some help, since I'm stuck and
> > can't figure out what I've done wrong.
> >
> > PS: I'm using Anaconda and JupyterNotebook.
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python programming help!

2018-09-23 Thread Bob Gailer
On Sep 23, 2018 3:33 AM, "V E G E T A L" 
wrote:
>
> Hello folks! So, I'm pretty much a noob still experimenting with basic
> commands. I wanted to make a code that checks if the value of one variable
> is less, equal or greater than the other. Pretty simple right? But then,

> this problem emerged.

What problem? I don't see any problem here. If you provided an attachment
this email list does not forward attachments.

The proper way is to copy and paste directly into the body of the email.

If you did not attempt to show us the problem, why? You certainly can't
expect us to read your mind.

I would really love some help, since I'm stuck and
> can't figure out what I've done wrong.
>
> PS: I'm using Anaconda and JupyterNotebook.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python programming help!

2018-09-23 Thread Mark Lawrence

On 21/09/18 16:12, V E G E T A L wrote:

Hello folks! So, I'm pretty much a noob still experimenting with basic
commands. I wanted to make a code that checks if the value of one variable
is less, equal or greater than the other. Pretty simple right? But then,
this problem emerged. I would really love some help, since I'm stuck and
can't figure out what I've done wrong.

PS: I'm using Anaconda and JupyterNotebook.


Please post your code as there are some smart people on this list but 
we're not mind readers :)  Also state your OS and the Python version.


--
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] python -m pip install vs pip install

2018-09-10 Thread Mats Wichmann
On 09/10/2018 09:10 AM, Alex Kleider wrote:
> In another currently active thread Mats Wichmann recommends using:
>   python -m pip install ...
> vs
>   pip install ...
> 
> The question is how to install a specific version of python itself.
> 
> I'm running Ubuntu 16.04 and have the following notes to myself as to
> how to install version 3.6 which was the one I wanted at the time:
> 
>   sudo add-apt-repository ppa:jonathonf/python-3.6
>   sudo apt-get update
>   sudo apt-get install python3.6
>   pip install --user virtualenvwrapper
>   echo "source virtualenvwrapper.sh" >> ~/.bashrc
>   source ~/.bashrc
>   mkvirtualenv --python=python3.6 p36
> 
> Should I modify these notes?
> What should I do if/when I'm looking to use the next version (3.7 and
> beyond?)
> Will things be completely different if/when I finally decide to move up
> to Ubuntu 18.04?
> 
> Thanks,
> Alex
> 

I have done it this way, assuming I don't want to replace the system
Python. This is a completely optional framework, but I've found it useful.

One time only:
$ git clone https://github.com/pyenv/pyenv.git ~/.pyenv
# set up environment variables for use by pyenv,
# as noted in pyenv readme:
$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile

Any time I want to install a Python version:
$ pyenv rehash
$ pyenv install 3.7.0

Inside a project that wants to use 3.7.0:
$ pyenv local 3.7.0

To see what is available to install:
$ pyenv install list

To simplify creating virtualenvs, there is a pyenv-virtualenv plugin
described here:
https://github.com/pyenv/pyenv-virtualenv
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python

2018-09-06 Thread Alan Gauld via Tutor
On 06/09/18 04:14, Donna Black via Tutor wrote:
> How do we save our work on python? IDLE hasn’t installed itself on my 
> computer 

Which OS are you using? That will help us
find/install IDLE.

However, you don't need IDLE to work with Python,
just a text editor.

If I assume you are using Windows then start notepad
and type the 2 lines

print("Hello world")
input("hit return to exit...")

Then save the file as hello.py

You should now be able to run that file by
double clicking it in your file manager.

Alternatively, start a CMD session
(Windows+R type cmd, hit OK) and at the
prompt type

python \the\folder\where\you\saved\the\file\hello.py

If you have problems with any of that let us know.
copy any error messages you get into your
mail message.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] "Python not recognized as a command"

2018-09-01 Thread Mats Wichmann
On 09/01/2018 04:24 PM, Marc Tompkins wrote:
> On Sat, Sep 1, 2018 at 10:40 AM, Dana O'Connor 
> wrote:
> 
>> Hi,
>> I've been trying to download and use Python 3.7 for the past few days and
>> every time I try to open it it tells me I don't have "pip" which should be
>> impossible because this version of Python is supposed to automatically come
>> with pip (?).  Additionally, whenever I open the command prompt on my
>> computer, the command "python" is not even recognized by the system even
>> though Python is downloaded onto the computer.  I cannot use Python at all
>> until I figure out this problem, so I guess my overall question is why
>> doesn't my computer acknowledge Python when it has been downloaded (and
>> redownloaded) several times on my computer?
>>

So, yeah... if this is Windows (and it nearly always is when someone has
this kind of problem):

windows is a graphical system, and it expects pretty much everything
"normal users" do to be through the gui.  Python follows along and
probably is there and working.  Can you find it by starting to type
python in the search box? the "gui for Python" is called IDLE, and you
can probably find this by starting to type its name into the search box.
 if these resolve to something, python is installed and working.

now, to go the extra step and make it available in the command shell, or
in powershell, or other place where you will type instead of click a
mouse, it needs to be added to the path, as the others have said.  there
was a checkbox for this in the python installer (perhaps in the advanced
section). you may or may not need that.

the installer will have asked you about installing Python Launcher. If
you agreed to this, the command "py" should work from the command shell,
even if "python" did not.  Try it.  the launcher goes in an
always-findable place to try to minimize the kinds of problems you are
finding. but almost no older docs or tutorials talk about it, because
it's a fairly new concept.

if you can bring up the python interpreter by typing "py", you can now
run pip to install packages. quit out of python first (in windows, ^Z
followed by Enter should do it).

ignore the instructions that say to type "pip install something"
directly into the command shell.  instead prefix that with "py -m".

So to install package foo, where your instructions said to type "pip
install foo", instead type "py -m pip install foo".

hope this gets you on the air.

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


Re: [Tutor] "Python not recognized as a command"

2018-09-01 Thread Marc Tompkins
On Sat, Sep 1, 2018 at 10:40 AM, Dana O'Connor 
wrote:

> Hi,
> I've been trying to download and use Python 3.7 for the past few days and
> every time I try to open it it tells me I don't have "pip" which should be
> impossible because this version of Python is supposed to automatically come
> with pip (?).  Additionally, whenever I open the command prompt on my
> computer, the command "python" is not even recognized by the system even
> though Python is downloaded onto the computer.  I cannot use Python at all
> until I figure out this problem, so I guess my overall question is why
> doesn't my computer acknowledge Python when it has been downloaded (and
> redownloaded) several times on my computer?
>

A bit more on Alan's point:
I believe that your question is a bit more of an operating system question
than purely a Python question; I also suspect (though I could be wrong)
that your previous experience has been with iOS or Android, and that you're
relatively unfamiliar with older desktop operating systems.
In iOS and Android, programs are packaged in such a way (and the package
installer is configured in such a way) that "downloading" and "installing"
are practically the same thing.  Apple OSx is nearly as seamless, and the
various Linux distros have been trying to move in this direction as well.
Even Windows - with "Universal" apps in Windows 8 and 10 - has been moving
in this direction.

But traditional "desktop"-side Windows, and traditional Windows programs
such as Python, still leave many details to the the user, and so the
process involves a few steps:
-  You download the installer.  This is actually a combination package: a
compressed archive of the actual program you want, wrapped up with a
program that knows how to unpack the archive, distribute its contents to
the appropriate locations, and register its various bits with the operating
system.
-  Once you've downloaded the installer, you run it, and it does its
magic.  It may prompt you to make some choices about where to put things.
-  Now that you've installed the program (Python in this case), you can run
it.  BUT - when you type a command at the prompt, the operating system
needs to know where to find the program file to fulfill your request.
That's where the PATH comes in - it's a list of locations where the OS can
look for, e.g. "python.exe" when you type "python" at the prompt.
-  PATH is a system variable, and it should be set by the installer when
you run it.  But the installer is a program, and sometimes programs fail.
So it's possible that you'd need to fix that; it's easy to do, but we need
more info first.

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


Re: [Tutor] "Python not recognized as a command"

2018-09-01 Thread Alan Gauld via Tutor
On 01/09/18 18:40, Dana O'Connor wrote:

> I've been trying to download and use Python 3.7 for the past few days 

How exactly did you download it (from which site and in which format?)
And how did you then install it?

> every time I try to open it it tells me I don't have "pip" 

That seems unlikely, I've never seen an OS give a warning
about pip when trying to open Python.

Can you tell us:
1) The OS you use - Linux? MacOSX? Windows? Something else?
2) The exact command you type (and from where)
3) The exact error message you get not a summary.

> the command "python" is not even recognized by the system even

Again the exact command used and the exact error
message please.

> doesn't my computer acknowledge Python when it has been downloaded (and
> redownloaded) several times on my computer?

It mat be that although you downloaded it you didn't
install it? Or maybe the installer didn't set a PATH
value properly?

But we need much more specific information to
do anything other than guess.



The US education system is a perpetual mystery to me.
Can you explain, just for my curiosity:

> Allegheny College, Class of 2019

I thought "class of" was the year you graduated from
high school but clearly that can't be true here.
So what does "class of 2019" refer to?

> Beta Chi Tutor,

I've seen references to Beta Chi before but have
no idea what it is, or how you would tutor it?
Can you explain what it is? (I probably should
just google it!)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python Memory Allocation -- deep learning

2018-07-30 Thread Steven D'Aprano
On Tue, Jul 31, 2018 at 02:58:56AM +1000, Steven D'Aprano wrote:

> The *only* thing you have seen which is a language feature is this rule:
> 
> - if two objects, a and b, have the same ID *at the same time*, then 
>   "a is b" will be true;
> 
> - if "a is b" is false, then a and b must have different IDs.

Sorry, I forgot to mention that for both of those, the reverse applies 
as well. Perhaps a better way to put it is this:

- if "a is b", then a and b must have the same ID, and vice versa.

- if "a is not b", then a and b must have different IDs, and vice versa.



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


Re: [Tutor] Python Memory Allocation -- deep learning

2018-07-30 Thread Steven D'Aprano
On Mon, Jul 30, 2018 at 09:21:01AM -0600, Mats Wichmann wrote:

> (id does not necessarily mean memory location, by the way)

id() *never* means memory location in Python. id() *always* returns an 
opaque integer ID number which has no promised meaning except to be 
unique while the object is alive.

The interpreter has to generate an ID somehow. In Jython and IronPython, 
the interpreter keeps a counter, and IDs are allocated as consecutive 
numbers 1, 2, 3, 4, ... etc. In CPython, the object's memory address is 
used to generate the ID, but the ID does not mean "memory address". If 
the ID happens to match the memory address, that's an accident, not a 
feature of the language.


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


Re: [Tutor] Python Memory Allocation -- deep learning

2018-07-30 Thread Max Zettlmeißl via Tutor
On Mon, Jul 30, 2018 at 3:20 PM, Sunil Tech  wrote:
> Python memory allocation is varying in all these use cases. Please help me
> understand.

CPython is interning small integers and small strings as a form of optimisation.

"The current implementation keeps an array of integer objects for all
integers between -5 and 256, when you create an int in that range you
actually just get back a reference to the existing object."

For integers see https://docs.python.org/2/c-api/int.html for Python 2
or https://docs.python.org/3/c-api/long.html for Python 3.

For strings see https://hg.python.org/cpython/file/3.5/Objects/codeobject.c#l51
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Memory Allocation -- deep learning

2018-07-30 Thread Steven D'Aprano
On Mon, Jul 30, 2018 at 06:50:59PM +0530, Sunil Tech wrote:
> Hi Team,
> 
> I am investigating how the memory allocation happens in Python

You cannot investigate memory allocation in Python code, because the 
Python execution model does not give you direct access to memory.

What you can investigate is:

- when the particular interpreter you are using creates a new
  object, or re-uses an existing object;

- when the particular interpreter you are using re-uses an 
  object ID;

- the *approximate* size of an object in bytes.


Your example #1:

> >>> a = 10
> >>> b = 10
> >>> c = 10
> >>> id(a), id(b), id(c)
> (140621897573616, 140621897573616, 140621897573616)

tells you that the particular interpreter you are using happens to 
re-use the int object 10. This is a version-specific, 
interpreter-specific implementation detail, not a language feature.


Your example #2:

> >>> x = 500
> >>> y = 500
> >>> id(x)
> 4338740848
> >>> id(y)
> 4338741040

shows us that the particular interpreter you are using happens to *not* 
re-use the int object 500, but create a new object each time it is 
required. Again, this is not a language feature.


Your example #3:

> >>> s1 = 'hello'
> >>> s2 = 'hello'
> >>> id(s1), id(s2)
> (4454725888, 4454725888)

tells us that the particular interpreter you are using happens to re-use 
the string object "hello", rather than create two different string 
objects.

Again, this is an implementation feature, not a language feature. 
Another interpreter, or a different version, might behave differently.


> >>> s3 = 'hello, world!'
> >>> s4 = 'hello, world!'
> >>> id(s3), id(s4)
> (4454721608, 4454721664)

And this tells us that the particular interpreter you are using 
*doesn't* re-use the string object "hello, world!" in this context. 

*Everything* you have seen in these examples, with one exception, are 
implementation-specific and depend on the interpreter and the version 
you use, and could change without notice.

The *only* thing you have seen which is a language feature is this rule:

- if two objects, a and b, have the same ID *at the same time*, then 
  "a is b" will be true;

- if "a is b" is false, then a and b must have different IDs.


In practice, most interpreters will follow rules something like this:

- small integers up to some convenient limit, like 20 or 100 or 256, 
  will be cached and re-used;

- integers larger than that will be created as needed;

- small strings that look like identifiers may be cached and re-used;

- large strings and those containing punctuation or spaces probably 
  won't be cached and re-used;

- the interpreter has the right and the ability to change these 
  rules any time it likes.


For example:

py> x = 1.5
py> y = 1.5
py> x is y  # the float object *is not* re-used
False
py> x = 1.5; y = 1.5
py> x is y  # the float object *is* re-used
True



> Python memory allocation is varying in all these use cases.

Nothing in any of those examples shows you anything about memory 
allocation. It only shows you the existence of objects,



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


Re: [Tutor] Python Memory Allocation -- deep learning

2018-07-30 Thread Mats Wichmann
On 07/30/2018 07:20 AM, Sunil Tech wrote:
> Hi Team,
> 
> I am investigating how the memory allocation happens in Python

There are several things going on here, but the main thing to know is:
but Python language _implementations_ optimize when they can and think
it makes sense. So don't draw too many conclusions from this
experiment... The python.org Python only creates one copy of small
integer objects, I think I've read somewhere the range is -5 to 256.
Strings get some kind of the same treatement - short strings may get
entries in the bytecode generated (.pyc files) allowing references to be
to the same id (id does not necessarily mean memory location, by the way)

Pretty much, don't count on this behavior.  Other Pythons may not do the
same things.

There is some control over whether strings are interned, see sys.intern()



> For Eg:
> *Case 1:*
> 
 a = 10
 b = 10
 c = 10
 id(a), id(b), id(c)
> (140621897573616, 140621897573616, 140621897573616)
 a += 1
 id(a)
> 140621897573592
> 
> 
> *Case 2:*
> 
 x = 500
 y = 500
 id(x)
> 4338740848
 id(y)
> 4338741040
> 
> 
> *Case 3:*
> 
 s1 = 'hello'
 s2 = 'hello'
 id(s1), id(s2)
> (4454725888, 4454725888)
 s1 == s2
> True
 s1 is s2
> True
 s3 = 'hello, world!'
 s4 = 'hello, world!'
 id(s3), id(s4)
> (4454721608, 4454721664)
 s3 == s4
> True
 s3 is s4
> False
> 
> Python memory allocation is varying in all these use cases. Please help me
> understand.
> 
> Thanks,
> Sunil. G
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

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


Re: [Tutor] Python Memory Allocation -- deep learning

2018-07-30 Thread Joel Goldstick
On Mon, Jul 30, 2018 at 9:20 AM, Sunil Tech  wrote:
> Hi Team,
>
> I am investigating how the memory allocation happens in Python
> For Eg:
> *Case 1:*
>
 a = 10
 b = 10
 c = 10
 id(a), id(b), id(c)
> (140621897573616, 140621897573616, 140621897573616)
 a += 1
 id(a)
> 140621897573592
>
>
> *Case 2:*
>
 x = 500
 y = 500
 id(x)
> 4338740848
 id(y)
> 4338741040
>
>
> *Case 3:*
>
 s1 = 'hello'
 s2 = 'hello'
 id(s1), id(s2)
> (4454725888, 4454725888)
 s1 == s2
> True
 s1 is s2
> True
 s3 = 'hello, world!'
 s4 = 'hello, world!'
 id(s3), id(s4)
> (4454721608, 4454721664)
 s3 == s4
> True
 s3 is s4
> False
>
> Python memory allocation is varying in all these use cases. Please help me
> understand.
>
> Thanks,
> Sunil. G
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

An id is not guaranteed to be a memory address.  In the cases you
cited, your version of python caches small integers, and apparently
small strings because its convenient and efficient to do so.  Other
implementations of python may take a different approach.   I think it
would be unwise to ever assume that a value is cached in your day to
day programming

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Question

2018-05-16 Thread Alan Gauld via Tutor
On 15/05/18 22:26, Mahamed Ahmed wrote:
> Please I would like you to help me solve the problem above 

We see no problem. this is a text only list so if you included
a binary attachment the server will have stripped it off for
security reasons.

Please repost the text of the problem description and any code
using plain text not HTML (since HTML will lose the code formatting)

> I also want to know how to sign up and get a online tutor for 
> this python course

We will comment on your code and answer questions but we
don't do one on one mentoring. Also we don't know your course.
But if you post any questions here we will do our best to
assist you.

> Here is what is supposed to be done:
> The prime numbers and their code has already been given but> what is need to 
> be done is making the lines and correcting > it in a
organized way.

One of the first things you learn about programming is that
the more clearly you can explain the problem (even to yourself)
the easier it is to find an answer in code. Avoid vague and woolly
descriptions.

What exactly does "making the lines" and "correcting it in an
organized way" mean?
What do the lines look like?
What is organized about it?
How is it "corrected"?

English may not be your first language and if that is the case
try explaining it in your language first before translating
into English (or even into Python). The important step is
getting the requirement absolutely clear in your own head.

> If you run the code above, 

We can't see the code.

> just need to make the small lines and writing Line1,Line2,...
> at the left side of the list

So what does "make the small lines mean? How small?
What should they contain?

> Hope you understand what the problem is

Sorry, but without the original problem statement or
code and with only your description to go on it is impossible
to know what you need.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python Question

2018-05-16 Thread Mats Wichmann
On 05/15/2018 03:26 PM, Mahamed Ahmed wrote:
> Hello,
> 
> Please I would like you to help me solve the problem above which is related 
> to loops and prime numbers so please get back to me, I also want to know how 
> to sign up and get a online tutor for this python course
> 
> Here is what is supposed to be done:
> The prime numbers and their code has already been given but what is need to 
> be done is making the lines and correcting it in a organized way
> If you run the code above, you’ll see the result then will just need to make 
> the small lines and writing Line1,Line2,Line3,Line4 and Line 5 at the left 
> side of the list
> 
> Hope you understand what the problem is about and  would love to hear about 
> you

I am afraid there is no code or description.  If you sent it as a link
to an image, it did not survive through email.

If you can paste the code into a new message, people here will be happy
to comment on it - that's the way this (volunteer) effort works, by the
way: we don't want to solve your homework problems for you, but if you
show what you have done and what the question or error is, people are
happy to help with that.

As far as finding a personal tutor for a Python course, that's a
different problem and I'm afraid we can't help with that. There are
people providing that kind of service (for a fee, I'm sure), should be
able to find through some internet searching.

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


Re: [Tutor] Python C extension - which method?

2018-05-07 Thread Michael C
Sorry I don't understand your suggestion.

Use "ctypes.CDLL" and "ctypes.WinDLL"

this works,
mydll = cdll.LoadLibrary('test.dll')
print(mydll.sum(3,2))

and this doens't
mydll = cdll('test.dll')
print(mydll.sum(3,2))

What's the syntax of what you suggested?

Thanks

On Mon, May 7, 2018 at 3:15 AM, eryk sun  wrote:

> On Sun, May 6, 2018 at 12:49 AM, Brad M  wrote:
> > If I may ask, what's the difference between these two?
> >
> > 1)
> > import ctypes
> > hello = ctypes.WinDLL('hello', use_last_error=True)
> >
> > 2)
> > from ctypes import cdll
> > hello = cdll.LoadLibrary('hello.dll')
>
> Use ctypes.CDLL and ctypes.WinDLL instead of cdll.LoadLibrary and
> windll.LoadLibrary. The latter is more typing for no benefit and
> prevents using the constructor arguments: handle, mode (POSIX),
> use_errno, and use_last_error (Windows). You need the latter two
> options if the library requires C errno or Windows GetLastError(), in
> which case you should use ctypes.get_errno() or
> ctypes.get_last_error() to get the error values after a C function
> call.
>
> > Both of them can return "1980" from  this:
> >
> > hello.c
> >
> > #include 
> >
> > __declspec(dllexport) int say_something()
> > {
> > return 1980;
> > }
>
> CDLL is the cdecl calling convention, and WinDLL is stdcall. There is
> no difference in 64-bit Windows (x64 ABI). In 32-bit Windows (x86
> ABI), cdecl has the caller clean the stack (i.e. pop arguments), and
> stdcall has the callee (the called function) clean the stack. cdecl
> allows functions with a variable number of arguments, such as the CRT
> printf function. In MSVC, cdecl is the default convention if you don't
> declare a function as __stdcall. A library can export functions with
> varying calling conventions, so in general you may need to mix CDLL
> and WinDLL.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   6   7   8   9   10   >