Re: [Tutor] Need help,please!

2018-11-27 Thread Alan Gauld via Tutor
On 27/11/2018 21:04, Kamina Kamtarin wrote:
> A De/Coder. Think back to 3rd grade when you passed notes to friends in
> class. We can't let the teacher see what we're writing so we used a code.
> A=1, B=2, C=3, etc. Your job is to create a program which does the
> following:
> 
>1. Presents the user with a menu choice: encode or decode
>2. Depending on what they chose you will either encode letters into
>numbers (seperated by dashes) or decode a series of numbers (separated by
>dashes) into letters.
>3. For example:
>   - "How are you?" would encode as "8-15-23 1-18-5 25-15-21?"
>   - "8-15-23 1-18-5 25-15-21" would decode as "How are you?"

Look at the builtin ord() and chr() functions.

For example ord('A') -> 65 and ord('a') -> 97

Similarly chr(97) -> 'a' and chr(65) -> 'A'

Now a little bit of arithmetic should get you to/from 1.
How you handle upper/lower case issues is up to you, but if
they aren't important then the string upper() and lower()
methods may help too.

I don't know what you do with punctuation, you didn't say
but you should be able to get the core done using the above.

-- 
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] need help generating table of contents

2018-08-28 Thread Albert-Jan Roskam
From: Tutor  on behalf of 
Peter Otten <__pete...@web.de>
Sent: Monday, August 27, 2018 6:43 PM
To: tutor@python.org
Subject: Re: [Tutor] need help generating table of contents
  

Albert-Jan Roskam wrote:

> 
> From: Tutor  on behalf
> of Peter Otten <__pete...@web.de> Sent: Friday, August 24, 2018 3:55 PM
> To: tutor@python.org
> 
>> The following reshuffle of your code seems to work:
>> 
>> print('\r\n** Table of contents\r\n')
>> pattern = '/Title \((.+?)\).+?/Page ([0-9]+)(?:\s+/Count ([0-9]+))?'
>> 
>> def process(triples, limit=None, indent=0):
>> for index, (title, page, count) in enumerate(triples, 1):
>> title = indent * 4 * ' ' + title
>> print(title.ljust(79, ".") + page.zfill(2))
>> if count:
>> process(triples, limit=int(count), indent=indent+1)
>> if limit is not None and limit == index:
>>  break
>> 
>> process(iter(re.findall(pattern, toc, re.DOTALL)))
> 
> Hi Peter, Cameron,
> 
> Thanks for your replies! The code above indeeed works as intended, but: I
> don't really understand *why*. I would assign a name to the following line
> "if limit is not None and limit == index", what would be the most
> descriptive name? I often use "is_*" names for boolean variables. Would
> "is_deepest_nesting_level" be a good name?



> No, it's not necessarily the deepest level. Every subsection eventually ends 
> at this point; so you might call it reached_end_of_current_section
> 
> Or just 'limit' ;) 

LOL. Ok, now I get it :-)

> The None is only there for the outermost level where no /Count is provided. 
> In this case the loop is exhausted.
> 
> If you find it is easier to understand you can calculate the outer count aka 
> limit as the number of matches - sum of counts:
> 



>> Also, I don't understand why iter() is required here, and why finditer()
> >is not an alternative.

>finditer() would actually work -- I didn't use it because I wanted to make 
> as few changes as possible to your code. What does not work is a list like 
>the result of findall(). This is because the inner for loops (i. e. the ones 
>in the nested calls of process) are supposed to continue the iteration 
>instead of restarting it. A simple example to illustrate the difference:

Ah, the triples cannot be unpacked inside the "for" line of the loop. This 
works:
def process(triples, limit=None, indent=0):
 for index, triple in enumerate(triples, 1):
 title, page, count = triple.groups()  # unpack it here
 title = indent * 4 * ' ' + title
 print(title.ljust(79, ".") + page.zfill(2))
 if count:
 process(triples, limit=int(count), indent=indent+1)
 if limit is not None and limit == index:
 break

process(re.finditer(pattern, toc, re.DOTALL))


If I don't do this, I get this error:
  File "Q:/toc/toc.py", line 64, in 
process(re.finditer(pattern, toc, re.DOTALL))
  File "Q:/Ctoc/toc.py", line 56, in process
for index, (title, page, count) in enumerate(triples, 1):
TypeError: '_sre.SRE_Match' object is not iterable

Process finished with exit code 1


Thanks again Peter! Very insightful!

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


Re: [Tutor] need help generating table of contents

2018-08-27 Thread Peter Otten
Albert-Jan Roskam wrote:

> 
> From: Tutor  on behalf
> of Peter Otten <__pete...@web.de> Sent: Friday, August 24, 2018 3:55 PM
> To: tutor@python.org
> 
>> The following reshuffle of your code seems to work:
>> 
>> print('\r\n** Table of contents\r\n')
>> pattern = '/Title \((.+?)\).+?/Page ([0-9]+)(?:\s+/Count ([0-9]+))?'
>> 
>> def process(triples, limit=None, indent=0):
>> for index, (title, page, count) in enumerate(triples, 1):
>> title = indent * 4 * ' ' + title
>> print(title.ljust(79, ".") + page.zfill(2))
>> if count:
>> process(triples, limit=int(count), indent=indent+1)
>> if limit is not None and limit == index:
>>  break
>> 
>> process(iter(re.findall(pattern, toc, re.DOTALL)))
> 
> Hi Peter, Cameron,
> 
> Thanks for your replies! The code above indeeed works as intended, but: I
> don't really understand *why*. I would assign a name to the following line
> "if limit is not None and limit == index", what would be the most
> descriptive name? I often use "is_*" names for boolean variables. Would
> "is_deepest_nesting_level" be a good name?

No, it's not necessarily the deepest level. Every subsection eventually ends 
at this point; so you might call it

reached_end_of_current_section

Or just 'limit' ;) 

The None is only there for the outermost level where no /Count is provided. 
In this case the loop is exhausted.

If you find it is easier to understand you can calculate the outer count aka 
limit as the number of matches - sum of counts:

def process(triples, section_length, indent=0):
for index, (title, page, count) in enumerate(triples, 1):
title = indent * 4 * ' ' + title
print(title.ljust(79, ".") + page.zfill(2))
if count:
process(triples, section_length=int(count), indent=indent+1)
if section_length == index:
break

triples = re.findall(pattern, toc, re.DOTALL)
toplevel_section_length = (
len(triples)
- sum(int(c or 0) for t, p, c in triples)
)
process(iter(triples), toplevel_section_length)

Just for fun here's one last variant that does away with the break -- and 
thus the naming issue -- completely:

def process(triples, limit=None, indent=0):
for title, page, count in itertools.islice(triples, limit):
title = indent * 4 * ' ' + title
print(title.ljust(79, ".") + page.zfill(2))
if count:
process(triples, limit=int(count), indent=indent+1)

Note that islice(items, None) does the right thing:

>>> list(islice("abc", None))
['a', 'b', 'c']


> Also, I don't understand why iter() is required here, and why finditer()
> is not an alternative.

finditer() would actually work -- I didn't use it because I wanted to make 
as few changes as possible to your code. What does not work is a list like 
the result of findall(). This is because the inner for loops (i. e. the ones 
in the nested calls of process) are supposed to continue the iteration 
instead of restarting it. A simple example to illustrate the difference:

 >>> s = "abcdefg"
>>> for k in range(3):
... print("===", k, "===")
... for i, v in enumerate(s):
... print(v)
... if i == 2: break
... 
=== 0 ===
a
b
c
=== 1 ===
a
b
c
=== 2 ===
a
b
c
>>> s = iter("abcdefg")
>>> for k in range(3):
... print("===", k, "===")
... for i, v in enumerate(s):
... print(v)
... if i == 2: break
... 
=== 0 ===
a
b
c
=== 1 ===
d
e
f
=== 2 ===
g




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


Re: [Tutor] need help generating table of contents

2018-08-27 Thread Albert-Jan Roskam


From: Tutor  on behalf of 
Peter Otten <__pete...@web.de>
Sent: Friday, August 24, 2018 3:55 PM
To: tutor@python.org

> The following reshuffle of your code seems to work:
> 
> print('\r\n** Table of contents\r\n')
> pattern = '/Title \((.+?)\).+?/Page ([0-9]+)(?:\s+/Count ([0-9]+))?'
> 
> def process(triples, limit=None, indent=0):
>     for index, (title, page, count) in enumerate(triples, 1):
>     title = indent * 4 * ' ' + title
>     print(title.ljust(79, ".") + page.zfill(2))
>     if count:
>     process(triples, limit=int(count), indent=indent+1)
>     if limit is not None and limit == index:
>     break
> 
> process(iter(re.findall(pattern, toc, re.DOTALL)))

Hi Peter, Cameron,

Thanks for your replies! The code above indeeed works as intended, but: I don't 
really understand *why*.
I would assign a name to the following line "if limit is not None and limit == 
index", what would be the most descriptive name? I often use "is_*" names for 
boolean variables. Would "is_deepest_nesting_level" be a good name?

Also, I don't understand why iter() is required here, and why finditer() is not 
an alternative.

I wrote the bookmarks file myself, and the code above is part of a shell script 
that compiles a large .pdf, with openoffice commandline calls, ghostscript, 
git, pdftk and python. The human-readable toc and the pdf bookmarks will always 
be consistent if I only need to edit one file.

Thanks again!

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


Re: [Tutor] need help generating table of contents

2018-08-25 Thread Cameron Simpson

On 24Aug2018 17:55, Peter Otten <__pete...@web.de> wrote:

Albert-Jan Roskam wrote:

I have Ghostscript files with a table of contents (toc) and I would like

to use this info to generate a human-readable toc. The problem is: I can't
get the (nested) hierarchy right.


import re

toc = """\
[ /PageMode /UseOutlines
  /Page 1
  /View [/XYZ null null 0]
  /DOCVIEW pdfmark
[ /Title (Title page)
  /Page 1
  /View [/XYZ null null 0]
  /OUT pdfmark
[ /Title (Document information)
  /Page 2
  /View [/XYZ null null 0]
  /OUT pdfmark

[...]

What is the best approach to do this?


The best approach is probably to use some tool/library that understands
postscript.


Just to this: I disagree. IIRC, there's no such thing as '/Title' etc in 
PostScript - these will all be PostScript functions defined by whatever made 
the document.  So a generic tool won't have any way to extract semantics like 
titles from a document.


The OP presumably has the specific output of a particular tool with this nice 
well structured postscript, so he needs to write his/her own special parser.


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


Re: [Tutor] need help generating table of contents

2018-08-24 Thread Peter Otten
Albert-Jan Roskam wrote:

> Hello,
> 
> I have Ghostscript files with a table of contents (toc) and I would like 
to use this info to generate a human-readable toc. The problem is: I can't 
get the (nested) hierarchy right.
> 
> import re
> 
> toc = """\
> [ /PageMode /UseOutlines
>   /Page 1
>   /View [/XYZ null null 0]
>   /DOCVIEW pdfmark
> [ /Title (Title page)
>   /Page 1
>   /View [/XYZ null null 0]
>   /OUT pdfmark
> [ /Title (Document information)
>   /Page 2
>   /View [/XYZ null null 0]
>   /OUT pdfmark
> [ /Title (Blah)
>   /Page 3
>   /View [/XYZ null null 0]
>   /OUT pdfmark
> [ /Title (Appendix)
>   /Page 16
>   /Count 4
>   /View [/XYZ null null 0]
>   /OUT pdfmark
> [ /Title (Sub1)
>   /Page 17
>   /Count 4
>   /OUT pdfmark
> [ /Title (Subsub1)
>   /Page 17
>   /OUT pdfmark
> [ /Title (Subsub2)
>   /Page 18
>   /OUT pdfmark
> [ /Title (Subsub3)
>   /Page 29
>   /OUT pdfmark
> [ /Title (Subsub4)
>   /Page 37
>   /OUT pdfmark
> [ /Title (Sub2)
>   /Page 40
>   /OUT pdfmark
> [ /Title (Sub3)
>   /Page 49
>   /OUT pdfmark
> [ /Title (Sub4)
>   /Page 56
>   /OUT pdfmark
> """
> print('\r\n** Table of contents\r\n')
> pattern = '/Title \((.+?)\).+?/Page ([0-9]+)(?:\s+/Count ([0-9]+))?'
> indent = 0
> start = True
> for title, page, count in re.findall(pattern, toc, re.DOTALL):
> title = (indent * ' ') + title
> count = int(count or 0)
> print(title.ljust(79, ".") + page.zfill(2))
> if count:
> count -= 1
> start = True
> if count and start:
> indent += 2
> start = False
> if not count and not start:
> indent -= 2
> start = True
> 
> This generates the following TOC, with subsub2 to subsub4 dedented one 
level too much:

> What is the best approach to do this?
 
The best approach is probably to use some tool/library that understands 
postscript. However, your immediate problem is that when there is more than 
one level of indentation you only keep track of the "count" of the innermost 
level. You can either use a list of counts or use recursion and rely on the 
stack to remember the counts of the outer levels.

The following reshuffle of your code seems to work:

print('\r\n** Table of contents\r\n')
pattern = '/Title \((.+?)\).+?/Page ([0-9]+)(?:\s+/Count ([0-9]+))?'

def process(triples, limit=None, indent=0):
for index, (title, page, count) in enumerate(triples, 1):
title = indent * 4 * ' ' + title
print(title.ljust(79, ".") + page.zfill(2))
if count:
process(triples, limit=int(count), indent=indent+1)
if limit is not None and limit == index:
break

process(iter(re.findall(pattern, toc, re.DOTALL)))



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


Re: [Tutor] Need help in learning Python

2018-08-13 Thread Wallis Short
I am also from a Linux background and I second exactly what James and David
said.

To learn Ubuntu, I would recommend installing Windows Subsystem for Linux
onto your existing Windows 10 setup  and then get the Ubuntu (or SUSE and
Debian) from the Microsoft store and install. It does have a few
limitations (especially on the GUI) but again which proper Linux Sysadmin
uses the GUI :)
Its quite simple to install as you add it via the "Windows Features" and
click on "Windows Subsystem for Linux"
This is an easy way to have Linux at your beck and call just by invoking
the OS by typing a command into the run command cmd

Unless of course you don't mind dual booting your laptop or have another
laptop/PC close by :)

Cheers

*Wallis Short*   Senior Network Engineer



Metro Fibre Networx (Pty) Ltd
www.metrofibre.co.za

298 Witch-Hazel Ave, Highveld, Centurion, Gauteng, 0157 South Africa



On 12 August 2018 at 18:51, Mats Wichmann  wrote:

>
> > Start with checking that pip is there (or installing it if not)
> > Then do PyGae
> > Then do Matplotlib
>
> For this, please note that the pip "command" is not in the same
> directory on Windows as the python it is associated with.  If you went
> through the steps to have Python in your PATH, and that works, then add
> another entry that is just the same but appends the \Scripts comoponent;
> OR where your instructions tell you to "pip install foo" at a command
> prompt do instead "python -m pip install foo"  I believe the latter is
> now the recommended way anyway, because it ensures the pip matches the
> python in case you have more than one copy installed on your system.
>
>
> For your other questions, you could instead of making  dual-boot setup,
> do some initial experiments with running a Linux virtual environment.
>
> Here's one possibility which will give you a ton of Python stuff already
> set up:
>
> https://labs.fedoraproject.org/python-classroom/download/index.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] Need help in learning Python

2018-08-12 Thread Carlos Monge
Thank you all. I will start in small steps. First Pygame and Ubuntu. I will
add any errors I get.

On Sun, Aug 12, 2018 at 11:51 AM, Mats Wichmann  wrote:

>
> > Start with checking that pip is there (or installing it if not)
> > Then do PyGae
> > Then do Matplotlib
>
> For this, please note that the pip "command" is not in the same
> directory on Windows as the python it is associated with.  If you went
> through the steps to have Python in your PATH, and that works, then add
> another entry that is just the same but appends the \Scripts comoponent;
> OR where your instructions tell you to "pip install foo" at a command
> prompt do instead "python -m pip install foo"  I believe the latter is
> now the recommended way anyway, because it ensures the pip matches the
> python in case you have more than one copy installed on your system.
>
>
> For your other questions, you could instead of making  dual-boot setup,
> do some initial experiments with running a Linux virtual environment.
>
> Here's one possibility which will give you a ton of Python stuff already
> set up:
>
> https://labs.fedoraproject.org/python-classroom/download/index.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] Need help in learning Python

2018-08-12 Thread Mats Wichmann


> Start with checking that pip is there (or installing it if not)
> Then do PyGae
> Then do Matplotlib

For this, please note that the pip "command" is not in the same
directory on Windows as the python it is associated with.  If you went
through the steps to have Python in your PATH, and that works, then add
another entry that is just the same but appends the \Scripts comoponent;
OR where your instructions tell you to "pip install foo" at a command
prompt do instead "python -m pip install foo"  I believe the latter is
now the recommended way anyway, because it ensures the pip matches the
python in case you have more than one copy installed on your system.


For your other questions, you could instead of making  dual-boot setup,
do some initial experiments with running a Linux virtual environment.

Here's one possibility which will give you a ton of Python stuff already
set up:

https://labs.fedoraproject.org/python-classroom/download/index.html

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


Re: [Tutor] Need help in learning Python

2018-08-12 Thread David Rock

> On Aug 11, 2018, at 20:34, James Gledhill via Tutor  wrote:
> 
> I know this is a python focused mail group, but you asked about Linux so I'll 
> answer. :-)
> I would strongly recommend that you skip Kali Linux for the next little 
> while. Every tool available on Kali can be obtained on Ubuntu. Kali is not 
> beginner friendly, and while the community is great, honestly it's not the 
> most beginner friendly either. If you don't feel comfortable installing the 
> tools you need for your course on Ubuntu, Kali is going to give you a 
> splitting headache. Stick with Ubuntu, learn python, install the tools as you 
> need them and you will learn so much more.
> 

I will second that, and add if you really NEED Kali, it’s possible to run it as 
a Live image (eg, off a USB stick); you don’t need to install it to use it.
https://docs.kali.org/downloading/kali-linux-live-usb-install

Doing it this way, you get better flexibility with having Kali without 
[potentially] destroying what’s currently on your system through trying to set 
up a multi-boot environment.

Bite of smaller chunks instead of trying to learn everything at once and you 
will be a lot happier.


— 
David Rock
da...@graniteweb.com




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


Re: [Tutor] Need help in learning Python

2018-08-12 Thread James Gledhill via Tutor
I know this is a python focused mail group, but you asked about Linux so I'll 
answer. :-)
I would strongly recommend that you skip Kali Linux for the next little while. 
Every tool available on Kali can be obtained on Ubuntu. Kali is not beginner 
friendly, and while the community is great, honestly it's not the most beginner 
friendly either. If you don't feel comfortable installing the tools you need 
for your course on Ubuntu, Kali is going to give you a splitting headache. 
Stick with Ubuntu, learn python, install the tools as you need them and you 
will learn so much more.

Trust me, it took me years to learn that lesson. :-|

 Original Message 
On Aug 11, 2018, 12:48 PM, Carlos Monge wrote:

> I bought two books to help me learn Python. "Python Crash Course" and
> "Python for Informatics". I have done all of the basic lessons in "Python
> Crash Course", but it has two additional sections to help instill what I
> have learned To do those sections I need to install Pygame and make sure I
> have 'pip' as well as Matplotlib. I have followed the directions in the
> book but can't get anything to download so I can use it.
> For the "Python for Informatics" book I need to have files from the
> internet load where I have Python so I can manipulate them, but I can't
> seem to get that to work.
>
> Also, I would like to install Ubuntu on a second drive with Python,
> Idle, C language and its compiler so I can also learn Linux. On the Linux
> drive, I need to install Kali Linux for a class on Cyber Security.
> I know this is a lot to ask, but I don't need it all at once. I would
> appreciate help from someone with experience in downloading all of these
> things onto a windows computer with a second drive for Ubuntu and all of
> the other software.
> Any help is appreciated, and if I find someone with the needed
> expertise, I will happily subscribe on the Python-Tutor Info Page/
> ___
> 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] Need help in learning Python

2018-08-11 Thread Alan Gauld via Tutor
On 11/08/18 18:48, Carlos Monge wrote:

> have learned To do those sections I need to install Pygame and make sure I
> have 'pip' as well as Matplotlib. 

If you are using a recent Python (v3.4+) then pip should
already be installed. PyGame comes with a Windows installer
that should set everything up for you.

Matplotlib I don;t know about.

I suggest you work on each one individually.
Let us know what you try and what results you get.
Tell us your OS and Python versions and cut n paste
any error messages into your mails.

Don;t attempt a second install until the first one succeeds.

Start with checking that pip is there (or installing it if not)
Then do PyGae
Then do Matplotlib


>  Also, I would like to install Ubuntu on a second drive with Python,
> Idle, C language and its compiler so I can also learn Linux. On the Linux
> drive, I need to install Kali Linux for a class on Cyber Security.

Do you want Ubuntu or Kali - they are separate distros and
you can't have both at the same time. Since you need Kali
for your course I'd suggest going straight to it.

As for Python packages on Linux you should find that your
distribution has some kind of package manager or software
manager for installing new apps. You should find almost
all the Python libraries and tools are available there
and you can install them that way. It tends to be easier
than using pip etc.

>  Any help is appreciated, and if I find someone with the needed
> expertise, I will happily subscribe on the Python-Tutor Info Page/

That's not how it works. The whole group acts as a virtual
tutor. You post questions here and whoever is available/qualified
jumps in with the answer. That often means you get multiple
(possible different) answers to your question, but the best
will usually become apparent quite quickly.


-- 
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] Need help combining elements of a list of lists

2018-07-11 Thread Jim

On 07/10/2018 11:03 PM, Mats Wichmann wrote:

On 07/10/2018 09:09 PM, Steven D'Aprano wrote:

On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote:


Say I have a list like ltrs and I want to print out all the possible 3
letter combinations. I want to combine letters from each inner list but
not combine any letters within the inner list itself. So ACF and ADF
would be ok but ABC would not.

I can lay it out manually and see the pattern, I cannot figure out how
to do it programically. Just in case this looks like homework it is not.
It's a small test case I devised to try to figure it out so I can apply
it to a bigger real world problem I am working on.

ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]


If you know that there are just three sublists, then you can do this:

for a in ltrs[0]:
 for b in ltrs[1]:
 for c in ltrs[2]:
 print(a + b + c)

I trust that's easy enough to understand.

But here's a more general technique, where you don't need to know up
front how many nested lists there are:


from itertools import product  # short for "Cartesian Product"
for s in product(*ltrs):
 print(''.join(s))


This is one of those cases where: if it's homework, getting the nested
loops right is almost certainly the way to go.  If it isn't, then
itertools (that is, "using an available library solution") is almost
certainly the way to go :)

If the eventual case is not just "letters", and a list of combined lists
is the eventual goal, then the concise stanza is:

prods = list(product(*ltrs))

print(prods) then gives you:

[('a', 'c', 'f'), ('a', 'c', 'g'), ('a', 'c', 'h'), ('a', 'c', 'i'),
('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'),
('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'),
('b', 'c', 'f'), ('b', 'c', 'g'), ('b', 'c', 'h'), ('b', 'c', 'i'),
('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'),
('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i')]

if you want them concatenated, then of course join is the way to do that.





Steven & Mats thanks for your replies.

It is more that just letters. I was reading Al Sweigart's book Cracking 
Codes with Python. I got to the chapter on substitution cyphers and 
wondered if his program could solve the daily Crypto Quips in the 
newspaper. Turns out it did not do a very good job because the quips 
were to short.


It did produce a dictionary where the keys are the letters of the 
alphabet and the items are a list of possible letters to substitute. If 
a key has no possible letters it is ignored, if a key has only one 
possible letter it considered a solution and plugged into the cypher. 
the keys with multiple possible letters are ones I am interested in.


I know you cannot brute force a substitution cypher but maybe I could 
loop over and combine the possible substitution letters and crack it 
that way. That's why I made up the letter problem, I wanted to see how 
to do it on a simple data set before attempting much more complex one.


It looks like the library solution is the way for me to try.

Regards,  Jim





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


Re: [Tutor] Need help combining elements of a list of lists

2018-07-11 Thread Jim

On 07/10/2018 10:09 PM, David Rock wrote:



On Jul 10, 2018, at 22:04, David Rock  wrote:


On Jul 10, 2018, at 21:46, Jim  wrote:

ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]


A fairly straightforward way is to use nested loops:


for l in ltrs[0]:

...   for j in ltrs[1]:
... for k in ltrs[2]:
...   print l,j,k



Sorry, let’s try to make that a little cleaner-looking

for x in ltrs[0]:
   for y in ltrs[1]:
 for z in ltrs[2]:
   print x,y,z



Seeing it in front of me it does look straight forward, I was having 
difficulty visualizing how to solve it.


thanks, Jim


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


Re: [Tutor] Need help combining elements of a list of lists

2018-07-10 Thread Mats Wichmann
On 07/10/2018 09:09 PM, Steven D'Aprano wrote:
> On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote:
> 
>> Say I have a list like ltrs and I want to print out all the possible 3 
>> letter combinations. I want to combine letters from each inner list but 
>> not combine any letters within the inner list itself. So ACF and ADF 
>> would be ok but ABC would not.
>>
>> I can lay it out manually and see the pattern, I cannot figure out how 
>> to do it programically. Just in case this looks like homework it is not. 
>> It's a small test case I devised to try to figure it out so I can apply 
>> it to a bigger real world problem I am working on.
>>
>> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]
> 
> If you know that there are just three sublists, then you can do this:
> 
> for a in ltrs[0]:
> for b in ltrs[1]:
> for c in ltrs[2]:
> print(a + b + c)
> 
> I trust that's easy enough to understand.
> 
> But here's a more general technique, where you don't need to know up 
> front how many nested lists there are:
> 
> 
> from itertools import product  # short for "Cartesian Product"
> for s in product(*ltrs):
> print(''.join(s))

This is one of those cases where: if it's homework, getting the nested
loops right is almost certainly the way to go.  If it isn't, then
itertools (that is, "using an available library solution") is almost
certainly the way to go :)

If the eventual case is not just "letters", and a list of combined lists
is the eventual goal, then the concise stanza is:

prods = list(product(*ltrs))

print(prods) then gives you:

[('a', 'c', 'f'), ('a', 'c', 'g'), ('a', 'c', 'h'), ('a', 'c', 'i'),
('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'),
('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'),
('b', 'c', 'f'), ('b', 'c', 'g'), ('b', 'c', 'h'), ('b', 'c', 'i'),
('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'),
('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i')]

if you want them concatenated, then of course join is the way to do that.






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


Re: [Tutor] Need help combining elements of a list of lists

2018-07-10 Thread David Rock

> On Jul 10, 2018, at 22:04, David Rock  wrote:
> 
>> On Jul 10, 2018, at 21:46, Jim  wrote:
>> 
>> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]
> 
> A fairly straightforward way is to use nested loops:
> 
 for l in ltrs[0]:
> ...   for j in ltrs[1]:
> ... for k in ltrs[2]:
> ...   print l,j,k
> 

Sorry, let’s try to make that a little cleaner-looking

for x in ltrs[0]:
  for y in ltrs[1]:
for z in ltrs[2]:
  print x,y,z


— 
David Rock
da...@graniteweb.com




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


Re: [Tutor] Need help combining elements of a list of lists

2018-07-10 Thread Steven D'Aprano
On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote:

> Say I have a list like ltrs and I want to print out all the possible 3 
> letter combinations. I want to combine letters from each inner list but 
> not combine any letters within the inner list itself. So ACF and ADF 
> would be ok but ABC would not.
> 
> I can lay it out manually and see the pattern, I cannot figure out how 
> to do it programically. Just in case this looks like homework it is not. 
> It's a small test case I devised to try to figure it out so I can apply 
> it to a bigger real world problem I am working on.
> 
> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]

If you know that there are just three sublists, then you can do this:

for a in ltrs[0]:
for b in ltrs[1]:
for c in ltrs[2]:
print(a + b + c)

I trust that's easy enough to understand.

But here's a more general technique, where you don't need to know up 
front how many nested lists there are:


from itertools import product  # short for "Cartesian Product"
for s in product(*ltrs):
print(''.join(s))


The *ltrs syntax might be a bit mysterious: it is called "sequence 
unpacking", and tells the interpreter to use each item from ltrs as a 
separate argument:

product(*ltrs)
=> product(ltrs[0], ltrs[1], ltrs[2])


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


Re: [Tutor] Need help combining elements of a list of lists

2018-07-10 Thread David Rock

> On Jul 10, 2018, at 21:46, Jim  wrote:
> 
> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]

A fairly straightforward way is to use nested loops:

>>> for l in ltrs[0]:
...   for j in ltrs[1]:
... for k in ltrs[2]:
...   print l,j,k

A C F
A C G
A C H
A C I
A D F
A D G
A D H
A D I
A E F
A E G
A E H
A E I
B C F
B C G
B C H
B C I
B D F
B D G
B D H
B D I
B E F
B E G
B E H
B E I


Not the most elegant, but probably the easiest to follow.

— 
David Rock
da...@graniteweb.com




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


Re: [Tutor] Need help with a login system

2018-06-09 Thread Steven D'Aprano
On Sat, Jun 09, 2018 at 02:39:48PM +0200, Casper Rasmussen wrote:
> So I am trying to make a simple login system just for fun and found this
> video that has helped me a lot but there is a line I am not really sure how
> works.
> Screenshot at the bottom

Unless you edit your code with Photoshop, don't use screenshots to send 
pictures of code. Send the code itself. Just copy and paste it.

Not only are binary attachments like images, videos, sound files etc 
deleted by the mailing list, but screen shots make it hard for the 
visually impaired and blind to contribute to the discussion.

They also make it impossible for the recipients to work with the posted 
code, since it isn't text that can be copied and tested and edited, just 
pixels.


> The line I don't understand is:
> 
> user = {}
> 
> I understand the how list works but this list I can't figure out.

That's because it isn't a list.

https://docs.python.org/3/tutorial/datastructures.html#dictionaries



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


Re: [Tutor] Need help with a virtual environment mess

2018-05-07 Thread Jim

On 05/07/2018 12:02 PM, Mats Wichmann wrote:

On 05/07/2018 10:16 AM, Jim wrote:


My understanding of VE's, based on some feedback from here, is you
install install the python you want on the system then use it to install
your VE. Then you install what ever you need to the VE. In my case I had
a working VE based on python 3.5 then I received an upgrade to the
python version 3.6 I had installed. After that I had problems with the
3.5 VE that had been working.


yes, this happens.

the default behavior for virtualenv is to make links when creating the
VE, which saves copying things but is vulnerable to breakage if the
Python it's linking to receives major changes.  In the case of a
distribution upgrading the Python version, a VE constructed against the
old version will break if the links are version-specific.  Looking at
one virtualenv I have, {VEPATH}/lib/python3.6 is full of such symlinks,
e.g.:

lrwxrwxrwx.  1 mats mats26 Aug 17  2017 re.py ->
/usr/lib64/python3.6/re.py


Virtualenvs are cheap to recreate, so one approach is to just throw away
the old one and make a new one.


My problem is right now the default python3 for my system is also 
affected. If I type python3 I will see python version 3.5.2 and I cannot 
import tkinter there either.



you can also give virtualenv an option (--always-copy) to cause the
created virtualenv to be more self-contained, at a cost of some space
and tiem.

There are plenty of tools for managing python versions and virtualenv.
The python community changed directions a little bit recently, 'venv' is
now the recommended approach:

https://docs.python.org/3/library/venv.html


That is what I used to setup my VE's.


pyenv can manage different Python versions if you're interested in that.



I am going to see if I can find some log file that would give me a clue 
about what happened during the update.


Regards,  Jim


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


Re: [Tutor] Need help with a virtual environment mess

2018-05-07 Thread Mats Wichmann
On 05/07/2018 10:16 AM, Jim wrote:

> My understanding of VE's, based on some feedback from here, is you
> install install the python you want on the system then use it to install
> your VE. Then you install what ever you need to the VE. In my case I had
> a working VE based on python 3.5 then I received an upgrade to the
> python version 3.6 I had installed. After that I had problems with the
> 3.5 VE that had been working.

yes, this happens.

the default behavior for virtualenv is to make links when creating the
VE, which saves copying things but is vulnerable to breakage if the
Python it's linking to receives major changes.  In the case of a
distribution upgrading the Python version, a VE constructed against the
old version will break if the links are version-specific.  Looking at
one virtualenv I have, {VEPATH}/lib/python3.6 is full of such symlinks,
e.g.:

lrwxrwxrwx.  1 mats mats26 Aug 17  2017 re.py ->
/usr/lib64/python3.6/re.py


Virtualenvs are cheap to recreate, so one approach is to just throw away
the old one and make a new one.

you can also give virtualenv an option (--always-copy) to cause the
created virtualenv to be more self-contained, at a cost of some space
and tiem.

There are plenty of tools for managing python versions and virtualenv.
The python community changed directions a little bit recently, 'venv' is
now the recommended approach:

https://docs.python.org/3/library/venv.html

pyenv can manage different Python versions if you're interested in that.

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


Re: [Tutor] Need help with a virtual environment mess

2018-05-07 Thread Jim

On 05/06/2018 05:16 PM, boB Stepp wrote:

On Sun, May 6, 2018 at 11:05 AM, Jim  wrote:

In a prior thread you guys helped me fix a problem with pip after I upgraded
an installed version of python 3.6 on my Mint 18 system. Pip would not run
in my python 3.6 virtual environment. The fix was to use synaptic to install
python3-distutils. I thought everything was ok until I tried to run a old
script from a different VE using python 3.5 which could not import tkinter.

I have 4 versions of python on this system:
system Python2 = 2.7.12 (default)
system Python3 = 3.5.2 (default)
a VE called env = 3.5.2
a Ve called env36 = 3.6.5

This is the error I get trying to import tkinter in env, I also get the same
error if I try to import it in system python3.

jfb@jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate
(env) jfb@jims-mint18 ~ $ python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.

import tkinter as tk

Traceback (most recent call last):
   File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in 
 import _tkinter
ImportError: No module named '_tkinter'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
   File "", line 1, in 
   File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in 
 raise ImportError(str(msg) + ', please install the python3-tk package')
ImportError: No module named '_tkinter', please install the python3-tk
package




If I go to synaptic and install the python3-tk it installs version 3.6.5 of
the package and I can still not import tkinter in env with python 3.5.2, but
I can in env36 with python 3.6.5.



As I have not yet tried to play around with virtual environments, I
may be about to do more harm than help, but I will plow ahead anyway!
~(:>))

My primitive understanding of installing Python versions that are
different from the system Python version into a virtual environment,
is that you have to install all dependencies you need from within that
virtual environment you created.  If I am correct about this then your
error messages suggest you need to install the tkinter stuff from
within that virtual environment using that virtual environment's pip.
Hopefully I am too far off from the truth here, but in any event, I
hope this helps you in your problem!



My understanding of VE's, based on some feedback from here, is you 
install install the python you want on the system then use it to install 
your VE. Then you install what ever you need to the VE. In my case I had 
a working VE based on python 3.5 then I received an upgrade to the 
python version 3.6 I had installed. After that I had problems with the 
3.5 VE that had been working.


Regards,  Jim

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


Re: [Tutor] Need help with a virtual environment mess

2018-05-06 Thread boB Stepp
On Sun, May 6, 2018 at 11:05 AM, Jim  wrote:
> In a prior thread you guys helped me fix a problem with pip after I upgraded
> an installed version of python 3.6 on my Mint 18 system. Pip would not run
> in my python 3.6 virtual environment. The fix was to use synaptic to install
> python3-distutils. I thought everything was ok until I tried to run a old
> script from a different VE using python 3.5 which could not import tkinter.
>
> I have 4 versions of python on this system:
> system Python2 = 2.7.12 (default)
> system Python3 = 3.5.2 (default)
> a VE called env = 3.5.2
> a Ve called env36 = 3.6.5
>
> This is the error I get trying to import tkinter in env, I also get the same
> error if I try to import it in system python3.
>
> jfb@jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate
> (env) jfb@jims-mint18 ~ $ python
> Python 3.5.2 (default, Nov 23 2017, 16:37:01)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more information.
 import tkinter as tk
> Traceback (most recent call last):
>   File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in 
> import _tkinter
> ImportError: No module named '_tkinter'
>
> During handling of the above exception, another exception occurred:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in 
> raise ImportError(str(msg) + ', please install the python3-tk package')
> ImportError: No module named '_tkinter', please install the python3-tk
> package

>
> If I go to synaptic and install the python3-tk it installs version 3.6.5 of
> the package and I can still not import tkinter in env with python 3.5.2, but
> I can in env36 with python 3.6.5.
>

As I have not yet tried to play around with virtual environments, I
may be about to do more harm than help, but I will plow ahead anyway!
~(:>))

My primitive understanding of installing Python versions that are
different from the system Python version into a virtual environment,
is that you have to install all dependencies you need from within that
virtual environment you created.  If I am correct about this then your
error messages suggest you need to install the tkinter stuff from
within that virtual environment using that virtual environment's pip.
Hopefully I am too far off from the truth here, but in any event, I
hope this helps you in your problem!

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


Re: [Tutor] Need help with FileNotFoundError

2018-04-26 Thread Jim

On 04/26/2018 03:27 PM, Danny Yoo wrote:

copy('~/Documents/Courses/ModernBootcamp/story.txt',
'~/Documents/Courses/ModernBootcamp/story_copy.txt')



Hi Jim,

You may need to use os.path.expanduser, as "tilde expansion" isn't
something that's done automatically.

This is referenced in the docs when they say: "Unlike a unix shell, Python
does not do any automatic path expansions. Functions such as expanduser()
and expandvars() can be invoked explicitly when an application desires
shell-like path expansion. (See also the glob module.)"

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

Try adding a call to os.path.expanduser()
https://docs.python.org/3/library/os.path.html#os.path.expanduser on that
tilde-prefixed path string.

Hope this helps!


Danny,

Thanks for pointing me in the right direction. I had tried replacing the 
~ with home/jfb/... now I realize it should have been /home/jfb/... 
Working now.


Thanks,  Jim


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


Re: [Tutor] Need help with FileNotFoundError

2018-04-26 Thread Danny Yoo
> copy('~/Documents/Courses/ModernBootcamp/story.txt',
> '~/Documents/Courses/ModernBootcamp/story_copy.txt')


Hi Jim,

You may need to use os.path.expanduser, as "tilde expansion" isn't
something that's done automatically.

This is referenced in the docs when they say: "Unlike a unix shell, Python
does not do any automatic path expansions. Functions such as expanduser()
and expandvars() can be invoked explicitly when an application desires
shell-like path expansion. (See also the glob module.)"

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

Try adding a call to os.path.expanduser()
https://docs.python.org/3/library/os.path.html#os.path.expanduser on that
tilde-prefixed path string.

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


Re: [Tutor] Need help please

2018-04-16 Thread Alan Gauld via Tutor
On 16/04/18 03:30, Sandra Sherif via Tutor wrote:
> Dear Python Tutor,
> 
> I am in desperate need for help with programming on python. I am new to using 
> python and I’m trying to write a program called “turtle tag”. I’m trying to 
> do these things in the program: 
> a. Asks how many turtles are playing tag
> b. Creates a turtle, assigns it a random color, and assigns it a random 
> starting
> position in the graphical window
> c. Randomly assigns one of the turtles to be “it”, and marking that turtle in 
> some
> way (like making it a special color no other turtle is allowed to be)
> d. Figures out which turtle is the closest to the turtle that is “it”
> e. Moves the turtle that is it to a point where it is touching the closest 
> other turtle
> 
> Can you please show me how it should be written please? Thank you so much.

When writing almost any program it helps to divide it
into chunks that you know how to do. You can then build
each chunk separate and gradually combine them to form
the final complete program.

Your problem has already been divided into chunks: a-e.
So which bits of that can you do? And which bits puzzle you?

a) Do you know how to get a number from a user?

b1) Can you create a turtle?
b2) Can you choose a random color value?
b3) Can you set a turtles color?
b4) Can you choose a random starting position?
b5) Can you set a turtles position?

c1) Can you create several turtles?
c2) Can you store them in a list?
c3) Can you choose a random list element?
c4) can you store a reference to a list element?
c5) Can you choose a color that no other turtle can take?
(This may mean changing the way b2 works)

d1) Can you work out the distance between two turtles?
d2) Can you repeat that for each turtle in your list?

e) Can you move a turtle to a new location?

For each item that you know how to do write a small
function (do you know how to write functions?) named
after the action it performs.
For example:
getNumber(),
createTurtle(),
getRandomColor(),
setColor(turtle, color) etc...

Test each function. Remember that functions that
get a value will need to have that value stored
in a variable.

Write another function that uses these function to
complete each major step (a-e) above.
eg initializeTurtle() could cover steps a and b.

For the steps you don't know how to do, or those that
don't work, come back here for help.

Show us your code plus any error messages(in full)

Hint: It may make life easier if you forget about the
random aspects for now and get it working with fixed
values - easier to debug... Once it works with fixed
values introduce randomness bit by bit - say colors
first then position. Divide and conquer is the key.

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] Need help fixing some code for a project

2017-11-27 Thread Alan Gauld via Tutor
On 27/11/17 01:57, John Cocks wrote:
> The task is broken down into three sections.

What exactly do you want help with?
Do you not understand part of the problem?
Do you not know how to code some part?
Are you getting an error? If so show us the full error text.

WE are not mind readers, you need to tell us what
you want to know.

As for the code below, I've added a few remarks...

> #Task: Create the empty data structure
> grocery_item = {}
> 
> grocery_history = []
> 
> #Variable used to check if the while loop condition is met
> stop = 'go'
> 
> while stop == 'go' :

This would read better if stop were a boolean variable

stop = False
while not stop:
...


> #Accept input of the name of the grocery item purchased.
> item_name = "Item name:\n"

Your comment says "accept input" but you are not accepting
input, you are just assigning a string to a variable.
Do you know how to read input from a user?


> #Accept input of the quantitiy of the grocery item purchased.
> quantity = "Quantity purchased:\n"
> #Accept input of the cost of the grocery item input (this is a per-item
> cost).
> cost = "Price per item:\n"
> #Create a dictionary entry which contains the name, number and price
> entered by the user.
> grocery_item = {'name': item_name, 'number': int(quantity), 'price':
> float(cost)}  -- errors usually occur here because of "quantity
> purchased:\n line
> #Add the grocery_item to the grocery_history list using the append
> function
> grocery_history.append(grocery_item)
> #Accept input from the user asking if they have finished entering
> grocery items.
> print("Would you like to enter another item?\n Type 'c' for continue or
> 'q' to quit:\n")

If you were reading input how would you exit the while loop above?
You need to test for that situation and take the appropriate action.

> # Define variable to hold grand total called 'grand_total'
> grand_total = 0

Its traditional to put ALL the variable definitions at the top
of your code so you know where to find them easily.

> #Define a 'for' loop.
> for grocery_item in grocery_history:

Its probbablyt not a good idea to use the same variable
name for the loop as you did in the input code above.
In this case it won't bite you but it could get
confusing. I'd suggest maybe just use 'item' instead?


>   #Calculate the total cost for the grocery_item.
>   item_total = number * price

You don't have variables called 'number' or 'price'
but you do have dictionary keys in grocery_item.
So you really need:

item_total = grocery_item['number'] * grocery_item['price']

>   #Add the item_total to the grand_total
>   item_total = grand_total

You are not adding you are assigning. And in fact
you are wiping out your total by replacing it with 0!

>   #Output the information for the grocery item to match this example:
>   #2 apple @ $1.49 ea $2.98
>   print('number', 'name', 'price', 'cost')

Her you just print the key strings not the actuial values.
Again you need to use the keys to access the item.

>   #Set the item_total equal to 0
>   item_total = 0
> #Print the grand total
> print(grand_total)


HTH, but, if you have more specific queries, come back to
us with more detail.

-- 
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] Need Help with install of Python!

2017-09-22 Thread George Fischhof
2017-09-20 2:18 GMT+02:00 Alan Gauld via Tutor :

> On 19/09/17 21:13, Larry Staley wrote:
> > Hello I am very new to Python just having installed Python Version 2.7
> onto
> > my windows 8.1 laptop.  I thought the install was successful and was
> > entering information for my first assignment when I received an
> unexpected
> > error.
>
> Where did you get your vesion of Python?
> If it was the standard distribution from python.org or
> activestate.com then it does not include any of the SciPy
> packages(*) and you need to install them separately.
>
> If you expect to be using mamny of these types of package
> you are best fetching a distribution  that includes them
> all, for example, Anaconda or Enthought
>
> (*)Pandas is part of the SciPy suite of third party add-ons.
>
> > I executed a Sheets command using an earlier generated getSheetNames
> > function that successfully was entered by me.
>
> When you define a function the code inside is not
> executed merely compiled into a function object
> ready for execution.
>
> > However, when I ran the Sheets command I received the following:
>
> Its only when you call the function that the code inside
> gets executed.
>
> > def getSheetNames(excelfile):
> > from pandas import ExcelFile
>
> Its normal in Python to put all imports at the top of
> the file rather than inside any functions. In this
> case you try to import pandas everytime you call
> the function and while its not a big overhead it
> mounts up if you were calling this inside a
> repeating loop.
>
> And if the import was outside the function you would
> pick up the import error earlier.
>
>  excelfile=r:"C:\Users\Larry
>  sheets=getSheetNames
> > (excelfile);sheets
>
> I'm not sure what you are doing with that
> final ;sheets. I assuyme trying to evaluate the result of the function?
>
> It would be normal to just print it:
>
> >>> print getSheetNames(excelFile)
>
> or, if you need to store the result:
>
> >>> sheets=getSheetNames(excelfile)
> >>> sheets
>
> Combining commands on a single line doesn't save
> much typing and makes debugging harder.
>
> > I have in addition included the actual Python I executed and received the
> > message.  It is attached in the file.
>
> attachments often get rejected by the mailer,
> if its not a huge file(>100 lines) just paste
> it into the email.
>
> Always include the full error trace too.
>
> > If I need to install Pandas, please indicate clearly how I do using my
> > current ver 2.7 python install.
>
> The easiest way is just to grab one of the
> all-inclusive Python distros mentioned above.
>
> --
> 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
>




Hi Larry,

If You just installed Python 2.7, maybe it would be a good idea to replace
it with Python 3.6. It will not solve Your problem, but support of Pyhon 2
will be finished in 2020, and that time You will have to learn Python 3
anyway. So it is better to start with it if You have no any special
requirement to use Python 2.
(Python 3 is more modern, and is the future)
;-)


@tutors
Hi Tutors,

I think we should encourage people new to Python to use Python 3 instaed of
Python 2 as this is the future. ;-)


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


Re: [Tutor] Need Help with install of Python!

2017-09-19 Thread Alan Gauld via Tutor
On 19/09/17 21:13, Larry Staley wrote:
> Hello I am very new to Python just having installed Python Version 2.7 onto
> my windows 8.1 laptop.  I thought the install was successful and was
> entering information for my first assignment when I received an unexpected
> error.

Where did you get your vesion of Python?
If it was the standard distribution from python.org or
activestate.com then it does not include any of the SciPy
packages(*) and you need to install them separately.

If you expect to be using mamny of these types of package
you are best fetching a distribution  that includes them
all, for example, Anaconda or Enthought

(*)Pandas is part of the SciPy suite of third party add-ons.

> I executed a Sheets command using an earlier generated getSheetNames
> function that successfully was entered by me.

When you define a function the code inside is not
executed merely compiled into a function object
ready for execution.

> However, when I ran the Sheets command I received the following:

Its only when you call the function that the code inside
gets executed.

> def getSheetNames(excelfile):
> from pandas import ExcelFile

Its normal in Python to put all imports at the top of
the file rather than inside any functions. In this
case you try to import pandas everytime you call
the function and while its not a big overhead it
mounts up if you were calling this inside a
repeating loop.

And if the import was outside the function you would
pick up the import error earlier.

 excelfile=r:"C:\Users\Larry
 sheets=getSheetNames
> (excelfile);sheets

I'm not sure what you are doing with that
final ;sheets. I assuyme trying to evaluate the result of the function?

It would be normal to just print it:

>>> print getSheetNames(excelFile)

or, if you need to store the result:

>>> sheets=getSheetNames(excelfile)
>>> sheets

Combining commands on a single line doesn't save
much typing and makes debugging harder.

> I have in addition included the actual Python I executed and received the
> message.  It is attached in the file.

attachments often get rejected by the mailer,
if its not a huge file(>100 lines) just paste
it into the email.

Always include the full error trace too.

> If I need to install Pandas, please indicate clearly how I do using my
> current ver 2.7 python install.

The easiest way is just to grab one of the
all-inclusive Python distros mentioned above.

-- 
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] Need help with code

2017-04-19 Thread Joel Goldstick
You most likely have no file named words.txt in the directory from
which you are running your code.

On Mon, Apr 17, 2017 at 10:12 PM, Tyler Seacrist  wrote:
> Hello,
>
>
> How do I avoid this error message everytime I utilize wordlist = 
> open("words.text") ?
>
 wordlist = open("words.txt")
> Traceback (most recent call last):
>   File "", line 1, in 
> wordlist = open("words.txt")
> FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'
 def calculate_abecedarian():
> total_count = 0
> for word in wordlist:
> if is_abecedarian(word):
> print (word)
> total_count += 1
> return total_count
>
> or
>
 if __name__ == '__main__':
> fin = open('words.txt', 'r')
> print (no_contain(fin))
>
>
> Traceback (most recent call last):
>   File "", line 2, in 
> fin = open('words.txt', 'r')
> FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
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] Need help with code

2017-04-19 Thread Alan Gauld via Tutor
On 18/04/17 03:12, Tyler Seacrist wrote:

> How do I avoid this error message everytime I utilize wordlist = 
> open("words.text") ?
> 
 wordlist = open("words.txt")
> Traceback (most recent call last):
>   File "", line 1, in 
> wordlist = open("words.txt")
> FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'

You need to tell Python where the file lives. It is evidently not
in the same folder where you run the program(*) so you need to
provide the path.

(*)You can determine which folder python considers its home folder by
including this code in your program;

import os
print( os.getcwd() )  # get Current Working Directory

and you can see its contents with

print( os.listdir() )

So you need to provide the path. If you are using
Windows you should put an 'r' in front of the path,
like so:

fin = open( r"C:\Path\to\words.txt" )

or use forward slashes:

fin = open( "C:/Path/to/words.txt" )

Either technique will avoid python interpreting the '\'
as an escape character.

-- 
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] Need help with code

2017-04-17 Thread Danny Yoo
On Mon, Apr 17, 2017 at 12:00 AM, Alan Gauld via Tutor  wrote:
> On 16/04/17 18:26, Tyler Seacrist wrote:
>
>> I need to draw a stack diagram for print_n
>> called with s = 'Hello' and n=2 and am unsure of how to do so.


Are you referring to this?

http://www.greenteapress.com/thinkpython/html/thinkpython004.html#toc33
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with code

2017-04-17 Thread Alan Gauld via Tutor
On 16/04/17 18:26, Tyler Seacrist wrote:

> I need to draw a stack diagram for print_n 
> called with s = 'Hello' and n=2 and am unsure of how to do so.

Me too.

What is print_n?

Which stack?
One in your program or the interpreters internal stack?

We need a lot more detail.

-- 
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] Need help with one problem.

2017-02-15 Thread Steven D'Aprano
On Wed, Feb 15, 2017 at 01:00:30PM -0500, Adam Howlett wrote:

> Write an if-else statement that assigns 20 to the variable y if the 
> variable x is greater than 100. Otherwise, it should assign 0 to the 
> variable y.
> 
> Is there an easy way to solve this problem?

Yes. What have you tried?


Hint: here's a similar problem.

"Write an if-else statement that assigns "Hello" to the variable q if 
the variable p is equal to 11. Otherwise it should assign "Goodbye" to 
the variable q."

And here's the answer:

if p == 11:
q = "Hello"
else:
q = "Goodbye"


Can you see the pattern? Can you follow that same pattern for your own 
question?


(Hint: use > for "greater than".)


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


Re: [Tutor] Need help with one problem.

2017-02-15 Thread Alan Gauld via Tutor
On 15/02/17 18:00, Adam Howlett wrote:
> Write an if-else statement that 
> assigns 20 to the variable y if the variable x is greater than 100. 
> Otherwise, it should assign 0 to the variable y.
> 
> Is there an easy way to solve this problem?

Yes, just do what it says.

Maybe if I reword the problem slightly it will
be easier to see?

if the variable x is greater than 100,
assign 20 to the variable y,
else
assign 0 to the variable y.

Does that help?

-- 
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] Need help

2016-10-13 Thread Ryan Smith
On Wednesday, October 12, 2016, Alan Gauld via Tutor 
wrote:

> On 12/10/16 09:03, niraj pandey wrote:
>
> > Can you pls guide how to print this screen (Attached here) content in
> > printer ?
>
> As we already pointed out this is a text list so attachments
> are usually stripped off...
>
> However, printing from Tkinter is not easy. The simplest way is usually
> to create an HTML file and use the OS to print that via a browser (many
> browsers have a print command line option). It is possible to convert
> your screen into a graphics file and print that, but the results can be
> a bit unpredictable.
>
> Alan 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] Need help

2016-10-12 Thread Alan Gauld via Tutor
On 12/10/16 09:03, niraj pandey wrote:

> Can you pls guide how to print this screen (Attached here) content in
> printer ?

As we already pointed out this is a text list so attachments
are usually stripped off...

However, printing from Tkinter is not easy. The simplest way is usually
to create an HTML file and use the OS to print that via a browser (many
browsers have a print command line option). It is possible to convert
your screen into a graphics file and print that, but the results can be
a bit unpredictable.

Alan G.

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


Re: [Tutor] Need help

2016-10-12 Thread niraj pandey
Hi ,

I need one more help related to printer.

Can you pls guide how to print this screen (Attached here) content in
printer ?

Thanks
Niraj

On Tue, Oct 4, 2016 at 12:21 PM, niraj pandey 
wrote:

> Ok I got it from the solution you provided on your previous mail.
>
> Thanks again
>
> Thanks
> Niraj
>
> On Tue, Oct 4, 2016 at 12:05 PM, niraj pandey 
> wrote:
>
>> Attaching two snapshots here.
>>
>> In first snapshot (1.png) I have the label windows without the values and
>> in second window (2.png) every label have some value.
>> I want to put these values in front of every label. I have already stored
>> these values in a variable.
>>
>> Thanks
>> Niraj
>>
>> On Mon, Oct 3, 2016 at 10:02 PM, niraj pandey > > wrote:
>>
>>> Hello Alan ,
>>>
>>> I am using python 2.7.10 and using RHEL6
>>>
>>> Thanks
>>>
>>>
>>> On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor 
>>> wrote:
>>>
 On 03/10/16 10:54, niraj pandey wrote:

 > I want to add every lebels value here (ie fetch from DB and display in
 > front of every lebel or I had store every lable value in variable and
 > display here).

 You need to tell us which OS, Python version and GUI
 toolkit you are using.

 > [image: Inline image 1]

 This is a text list so images usually get stripped off.
 If absolutely necessary to send an image use a link to an
 image gallery somewhere.

 But at least try to explain what you are trying to show us.

 > Is there any function which I can use for this (like we have
 entry.get to
 > get the value similar any function to put the value)

 Assuming you are using Tkinter there is an insert() method.
 To put text at the end of the entry use

 import tkinter as tk
 myText = "Hello world"
 top = tk.Tk()

 myEntry = tk.Entry(top)
 myEntry.pack()
 myEntry.insert(tk.END,mytext)

 top.mainloop()


 However a common alternative is to use a StringVar and associate it with
 the Entry so that changes in the StringVar are automatically
 shown in the Entry and changes in the Entrey are reflected to the
 StringVar. Most Tkinter tutorials will show that under StringVar.

 Of course if you are not using Tkinter most of that will be useless!


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

>>>
>>>
>>>
>>> --
>>> Success occurs when opportunity and preparation meet
>>>
>>
>>
>>
>> --
>> Success occurs when opportunity and preparation meet
>>
>
>
>
> --
> Success occurs when opportunity and preparation meet
>



-- 
Success occurs when opportunity and preparation meet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help

2016-10-04 Thread niraj pandey
Ok I got it from the solution you provided on your previous mail.

Thanks again

Thanks
Niraj

On Tue, Oct 4, 2016 at 12:05 PM, niraj pandey 
wrote:

> Attaching two snapshots here.
>
> In first snapshot (1.png) I have the label windows without the values and
> in second window (2.png) every label have some value.
> I want to put these values in front of every label. I have already stored
> these values in a variable.
>
> Thanks
> Niraj
>
> On Mon, Oct 3, 2016 at 10:02 PM, niraj pandey 
> wrote:
>
>> Hello Alan ,
>>
>> I am using python 2.7.10 and using RHEL6
>>
>> Thanks
>>
>>
>> On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor 
>> wrote:
>>
>>> On 03/10/16 10:54, niraj pandey wrote:
>>>
>>> > I want to add every lebels value here (ie fetch from DB and display in
>>> > front of every lebel or I had store every lable value in variable and
>>> > display here).
>>>
>>> You need to tell us which OS, Python version and GUI
>>> toolkit you are using.
>>>
>>> > [image: Inline image 1]
>>>
>>> This is a text list so images usually get stripped off.
>>> If absolutely necessary to send an image use a link to an
>>> image gallery somewhere.
>>>
>>> But at least try to explain what you are trying to show us.
>>>
>>> > Is there any function which I can use for this (like we have entry.get
>>> to
>>> > get the value similar any function to put the value)
>>>
>>> Assuming you are using Tkinter there is an insert() method.
>>> To put text at the end of the entry use
>>>
>>> import tkinter as tk
>>> myText = "Hello world"
>>> top = tk.Tk()
>>>
>>> myEntry = tk.Entry(top)
>>> myEntry.pack()
>>> myEntry.insert(tk.END,mytext)
>>>
>>> top.mainloop()
>>>
>>>
>>> However a common alternative is to use a StringVar and associate it with
>>> the Entry so that changes in the StringVar are automatically
>>> shown in the Entry and changes in the Entrey are reflected to the
>>> StringVar. Most Tkinter tutorials will show that under StringVar.
>>>
>>> Of course if you are not using Tkinter most of that will be useless!
>>>
>>>
>>> --
>>> 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
>>>
>>
>>
>>
>> --
>> Success occurs when opportunity and preparation meet
>>
>
>
>
> --
> Success occurs when opportunity and preparation meet
>



-- 
Success occurs when opportunity and preparation meet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help

2016-10-04 Thread niraj pandey
Attaching two snapshots here.

In first snapshot (1.png) I have the label windows without the values and
in second window (2.png) every label have some value.
I want to put these values in front of every label. I have already stored
these values in a variable.

Thanks
Niraj

On Mon, Oct 3, 2016 at 10:02 PM, niraj pandey 
wrote:

> Hello Alan ,
>
> I am using python 2.7.10 and using RHEL6
>
> Thanks
>
>
> On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor 
> wrote:
>
>> On 03/10/16 10:54, niraj pandey wrote:
>>
>> > I want to add every lebels value here (ie fetch from DB and display in
>> > front of every lebel or I had store every lable value in variable and
>> > display here).
>>
>> You need to tell us which OS, Python version and GUI
>> toolkit you are using.
>>
>> > [image: Inline image 1]
>>
>> This is a text list so images usually get stripped off.
>> If absolutely necessary to send an image use a link to an
>> image gallery somewhere.
>>
>> But at least try to explain what you are trying to show us.
>>
>> > Is there any function which I can use for this (like we have entry.get
>> to
>> > get the value similar any function to put the value)
>>
>> Assuming you are using Tkinter there is an insert() method.
>> To put text at the end of the entry use
>>
>> import tkinter as tk
>> myText = "Hello world"
>> top = tk.Tk()
>>
>> myEntry = tk.Entry(top)
>> myEntry.pack()
>> myEntry.insert(tk.END,mytext)
>>
>> top.mainloop()
>>
>>
>> However a common alternative is to use a StringVar and associate it with
>> the Entry so that changes in the StringVar are automatically
>> shown in the Entry and changes in the Entrey are reflected to the
>> StringVar. Most Tkinter tutorials will show that under StringVar.
>>
>> Of course if you are not using Tkinter most of that will be useless!
>>
>>
>> --
>> 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
>>
>
>
>
> --
> Success occurs when opportunity and preparation meet
>



-- 
Success occurs when opportunity and preparation meet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help

2016-10-03 Thread niraj pandey
Hello Alan ,

I am using python 2.7.10 and using RHEL6

Thanks


On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor 
wrote:

> On 03/10/16 10:54, niraj pandey wrote:
>
> > I want to add every lebels value here (ie fetch from DB and display in
> > front of every lebel or I had store every lable value in variable and
> > display here).
>
> You need to tell us which OS, Python version and GUI
> toolkit you are using.
>
> > [image: Inline image 1]
>
> This is a text list so images usually get stripped off.
> If absolutely necessary to send an image use a link to an
> image gallery somewhere.
>
> But at least try to explain what you are trying to show us.
>
> > Is there any function which I can use for this (like we have entry.get to
> > get the value similar any function to put the value)
>
> Assuming you are using Tkinter there is an insert() method.
> To put text at the end of the entry use
>
> import tkinter as tk
> myText = "Hello world"
> top = tk.Tk()
>
> myEntry = tk.Entry(top)
> myEntry.pack()
> myEntry.insert(tk.END,mytext)
>
> top.mainloop()
>
>
> However a common alternative is to use a StringVar and associate it with
> the Entry so that changes in the StringVar are automatically
> shown in the Entry and changes in the Entrey are reflected to the
> StringVar. Most Tkinter tutorials will show that under StringVar.
>
> Of course if you are not using Tkinter most of that will be useless!
>
>
> --
> 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
>



-- 
Success occurs when opportunity and preparation meet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help

2016-10-03 Thread Alan Gauld via Tutor
On 03/10/16 10:54, niraj pandey wrote:

> I want to add every lebels value here (ie fetch from DB and display in
> front of every lebel or I had store every lable value in variable and
> display here).

You need to tell us which OS, Python version and GUI
toolkit you are using.

> [image: Inline image 1]

This is a text list so images usually get stripped off.
If absolutely necessary to send an image use a link to an
image gallery somewhere.

But at least try to explain what you are trying to show us.

> Is there any function which I can use for this (like we have entry.get to
> get the value similar any function to put the value)

Assuming you are using Tkinter there is an insert() method.
To put text at the end of the entry use

import tkinter as tk
myText = "Hello world"
top = tk.Tk()

myEntry = tk.Entry(top)
myEntry.pack()
myEntry.insert(tk.END,mytext)

top.mainloop()


However a common alternative is to use a StringVar and associate it with
the Entry so that changes in the StringVar are automatically
shown in the Entry and changes in the Entrey are reflected to the
StringVar. Most Tkinter tutorials will show that under StringVar.

Of course if you are not using Tkinter most of that will be useless!


-- 
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] Need help

2016-09-28 Thread niraj pandey
Ignore this I have done it.

Thanks
Niraj

On Wed, Sep 28, 2016 at 12:30 PM, niraj pandey 
wrote:

> Found the solution for this .
>
> entry_option = ['Flat_No','Mains Unit','DG Unit','Month']
>
>  r = 0
>   entry = {}
>   label = {}
>   for item in entry_option:
>   lb = Label(bg = 'orange', text=item, relief=RIDGE,width=30)
>   lb.grid(row=r,column=0)
>   label[item] = lb
>   e = Entry(relief=SUNKEN,width=30)
>   e.grid(row=r,column=1)
>   entry[item] = e
>   r=r+1
>
> But now how to pass these values as an argument for this function  ?
>
> command=lambda: database.data(E1.get(), E2.get(), E3.get(), E4.get())
>
> Thanks
> Niraj
>
> On Wed, Sep 28, 2016 at 10:52 AM, niraj pandey  > wrote:
>
>> Hi,
>>
>> I am new in python. Could you guys please help me to short this code ?
>>
>> Want to write this iteration (Yellow one) using loop.
>>
>> r = 0
>> L1 = Label(bg = 'orange', text="Flat_No", relief=RIDGE,width=30)
>> L1.grid(row=0,column=0)
>> E1 = Entry(relief=SUNKEN,width=30)
>> E1.grid(row=0,column=1)
>> L2 = Label(bg = 'orange', text="Mains Unit", relief=RIDGE,width=30)
>> L2.grid(row=1,column=0)
>> E2 = Entry(relief=SUNKEN,width=30)
>> E2.grid(row=1,column=1)
>> L3 = Label(bg = 'orange', text="DG Unit", relief=RIDGE,width=30)
>> L3.grid(row=2,column=0)
>> E3 = Entry(relief=SUNKEN,width=30)
>> E3.grid(row=2,column=1)
>> L4 = Label(bg = 'orange', text="Month", relief=RIDGE,width=30)
>> L4.grid(row=3,column=0)
>> E4 = Entry(relief=SUNKEN,width=30)
>> E4.grid(row=3,column=1)
>>
>>
>> MyButton1 = Button(top, text="Submit", width=10, bg='red',
>> command=lambda: database.data(E1.get(), E2.get(), E3.get(), E4.get()))
>> MyButton1.grid(row=8, column=1)
>>
>> The output should be like this :
>>
>> [image: Inline image 1]
>>
>> Thanks
>> Niraj
>> --
>> Success occurs when opportunity and preparation meet
>>
>
>
>
> --
> Success occurs when opportunity and preparation meet
>



-- 
Success occurs when opportunity and preparation meet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help

2016-09-28 Thread niraj pandey
Thanks Peter for the help.

Best Regards
Niraj



On Wed, Sep 28, 2016 at 2:47 PM, Peter Otten <__pete...@web.de> wrote:

> niraj pandey wrote:
>
> > Found the solution for this.
>
> You can further simplifiy it with enumerate()
> > entry_option = ['Flat_No','Mains Unit','DG Unit','Month']
>
> > entry = {}
> > label = {}
>   for r, item in enumerate(entry_option):
> > lb = Label(bg = 'orange', text=item, relief=RIDGE,width=30)
> > lb.grid(row=r,column=0)
> > label[item] = lb
> > e = Entry(relief=SUNKEN,width=30)
> > e.grid(row=r,column=1)
> > entry[item] = e
> >
> > But now how to pass these values as an argument for this function  ?
> >
> > command=lambda: database.data(E1.get(), E2.get(), E3.get(), E4.get())
>
> Well, you saved the Entry instances in a dict, so you can retrieve them:
>
> command=lambda: database.data(*[entry[k].get() for k in entry_option])
>
> If you use a list instead of or in addition to the dict
>
> entries = []
> for ...: # your loop from above
>...
>entries.append(e)
>
> the lambda becomes
>
> command=lambda: database.data(*[e.get() for e in entries])
>
> If you have not come across it before: the * operator unpacks the list, so
>
> args = ["a", "b"]
> f(*args)
>
> is equivalent to calling f with all items in the list,
>
> f(args[0], args[1])
>
> in the above example.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Success occurs when opportunity and preparation meet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help

2016-09-28 Thread Peter Otten
niraj pandey wrote:

> Found the solution for this.

You can further simplifiy it with enumerate()
> entry_option = ['Flat_No','Mains Unit','DG Unit','Month']

> entry = {}
> label = {}
  for r, item in enumerate(entry_option):
> lb = Label(bg = 'orange', text=item, relief=RIDGE,width=30)
> lb.grid(row=r,column=0)
> label[item] = lb
> e = Entry(relief=SUNKEN,width=30)
> e.grid(row=r,column=1)
> entry[item] = e
> 
> But now how to pass these values as an argument for this function  ?
> 
> command=lambda: database.data(E1.get(), E2.get(), E3.get(), E4.get())

Well, you saved the Entry instances in a dict, so you can retrieve them:

command=lambda: database.data(*[entry[k].get() for k in entry_option]) 

If you use a list instead of or in addition to the dict

entries = []
for ...: # your loop from above
   ...
   entries.append(e)

the lambda becomes

command=lambda: database.data(*[e.get() for e in entries])

If you have not come across it before: the * operator unpacks the list, so

args = ["a", "b"]
f(*args)

is equivalent to calling f with all items in the list,

f(args[0], args[1])

in the above example.

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


Re: [Tutor] Need help

2016-09-28 Thread niraj pandey
Found the solution for this .

entry_option = ['Flat_No','Mains Unit','DG Unit','Month']

 r = 0
  entry = {}
  label = {}
  for item in entry_option:
  lb = Label(bg = 'orange', text=item, relief=RIDGE,width=30)
  lb.grid(row=r,column=0)
  label[item] = lb
  e = Entry(relief=SUNKEN,width=30)
  e.grid(row=r,column=1)
  entry[item] = e
  r=r+1

But now how to pass these values as an argument for this function  ?

command=lambda: database.data(E1.get(), E2.get(), E3.get(), E4.get())

Thanks
Niraj

On Wed, Sep 28, 2016 at 10:52 AM, niraj pandey 
wrote:

> Hi,
>
> I am new in python. Could you guys please help me to short this code ?
>
> Want to write this iteration (Yellow one) using loop.
>
> r = 0
> L1 = Label(bg = 'orange', text="Flat_No", relief=RIDGE,width=30)
> L1.grid(row=0,column=0)
> E1 = Entry(relief=SUNKEN,width=30)
> E1.grid(row=0,column=1)
> L2 = Label(bg = 'orange', text="Mains Unit", relief=RIDGE,width=30)
> L2.grid(row=1,column=0)
> E2 = Entry(relief=SUNKEN,width=30)
> E2.grid(row=1,column=1)
> L3 = Label(bg = 'orange', text="DG Unit", relief=RIDGE,width=30)
> L3.grid(row=2,column=0)
> E3 = Entry(relief=SUNKEN,width=30)
> E3.grid(row=2,column=1)
> L4 = Label(bg = 'orange', text="Month", relief=RIDGE,width=30)
> L4.grid(row=3,column=0)
> E4 = Entry(relief=SUNKEN,width=30)
> E4.grid(row=3,column=1)
>
>
> MyButton1 = Button(top, text="Submit", width=10, bg='red', command=lambda:
> database.data(E1.get(), E2.get(), E3.get(), E4.get()))
> MyButton1.grid(row=8, column=1)
>
> The output should be like this :
>
> [image: Inline image 1]
>
> Thanks
> Niraj
> --
> Success occurs when opportunity and preparation meet
>



-- 
Success occurs when opportunity and preparation meet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help

2016-08-11 Thread Michael Selik
On Thu, Aug 11, 2016 at 1:15 PM Pallab Amway  wrote:

> expected an indented block
>

if-statements must have an indented block of code. For example:
```
if age < 12:
print('You are a child')
```
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help

2016-08-11 Thread boB Stepp
On Aug 11, 2016 12:15 PM, "Pallab Amway"  wrote:
>
> Respected sir
>
>  Myself pallab kumar seal from India I am using
python2.7
> in my window 7 but while  I am using python to compile my program I am
> getting following  error
>
> Programe1
>
> age = 21
>
> if age < 12:
>
> print( "You ' re still a child!" )
>
> elif age < 18:
>
> print( "You are a teenager!" )
>
> elif age < 30:
>
> print( "You ' re pretty young!" )
>
> elif age < 50:
>
> print( "Wisening up, are we?" )
>
> else:
>
> print( "Aren ' t the years weighing heavy?" )
>
> answer
>
>
> expected an indented block
>

Do you understand how Python uses consistent indentation to delineate
blocks of code?  If not, then you need to research this.

Also, you say you're using Python 2.7.  Python 2.x uses print *statements*
=> no parentheses, while Python 3.x uses print *functions*.  Something else
to read up on.

Hope this gives you enough hints to work through your current problems!

And I hope sending from my phone results in a plain text format!

boB

P.S.:. Do you have a good book or online tutorial to use?  If not, there
are plenty of such resources online.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with socket / fuzzer not sure the while loop condition is wrong

2016-07-21 Thread Alan Gauld via Tutor
On 21/07/16 12:50, la Y wrote:
> need help with socket / fuzzer 


UI've no idea what fuzzer means but...

> not sure the while loop condition is wrong

> def fuzzer():
> #fuzzer
> #user attack coordinates and junk
> currentEta = datetime.datetime.now()
> targetIP = raw_input("hello what is the target IP destinaition address: ")
> socketPort = int(raw_input("what port number : "))
> 
> while ( socketPort < 4 ) and (socketPort <= 65535):
> socketPort = int(socketPort)

This makes no sense at all.

The socketPort is already an int because you make it so
on the raw_input line.

If it is <4 it will also be less than 65535 so the "and"
test is superfluous.

And if it is <4 the while loop will run forever because
you never change the value of socketPort.

if
x = int(n)
then
int(x) == x

is always true

I've no idea what the loop is intended to do so I can't
comment on whether you need to just delete it or whether
you need to modify it somehow.


-- 
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] Need help with audio manipulation

2016-02-11 Thread Alan Gauld
On 11/02/16 18:03, Swift, Robert wrote:
> I was wondering how to write a code that would take a recorded audio and
> place these values into a numpy array? I have written various codes that
> can record and playback sound and work properly. I need the recorded audio
> to be accessed from a numpy array so I can process the sound and manipulate
> it to play back the inverse of the array for a noise cancelling affect. Any
> ideas would be great.

There are numerous audio processing toolkits available,
some work with SciPy, others are independent.

There is a useful page here:

wiki.python.org/moin/PythonInMusic

You may find useful pointers there.

As a subject its a bit off topic for this list which is
about the standard library and language.

-- 
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] Need help with two similar test cases that I have written. One works and the other fails

2016-02-07 Thread Anubhav Yadav
> > Be careful.  Now you have a test that always succeeds.
>
> No, I'm wrong.  Sorry about that: I misread the numerical range.
>

This is the first time I am ever writing unit tests, and I am glad I am
doing it.

Thanks a lot for all your help!.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-07 Thread Danny Yoo
On Feb 7, 2016 8:38 AM, "Danny Yoo"  wrote:
>
> :
> >
> > def test_red_temperature_simulation(self):
> > """
> > Method to test the red_temperature_simulation method
> > """
> > for i in range(100):
> > test_value = red_temperature_simulation()
> > self.assertTrue((test_value < 100.0) or (test_value >
103.0),
> > msg="Test failed for {}".format(test_value))
> >
> > And now everything works the way it should.
> >
>
> Be careful.  Now you have a test that always succeeds.

No, I'm wrong.  Sorry about that: I misread the numerical range.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-07 Thread Danny Yoo
:
>
> def test_red_temperature_simulation(self):
> """
> Method to test the red_temperature_simulation method
> """
> for i in range(100):
> test_value = red_temperature_simulation()
> self.assertTrue((test_value < 100.0) or (test_value > 103.0),
> msg="Test failed for {}".format(test_value))
>
> And now everything works the way it should.
>

Be careful.  Now you have a test that always succeeds.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-07 Thread Anubhav Yadav
> > when my program is in the yellow state, it should generate the numbers
> > from 100.0-100.5
> > and 102.5-103.0
>
> The "and" is a bit misleading as you want to allow values that are in the
> first *or* the second intrval. When you spell that in Python it becomes
>
> temperature = yellow_temperature_simulation()
> self.assertTrue(
> (100.0 <= temperature < 100.5)
> or (102.5 <= temperature < 103.0))
>
>
I agree, That's the mistake I made. I fixed it as follows:

def test_red_temperature_simulation(self):
"""
Method to test the red_temperature_simulation method
"""
for i in range(100):
test_value = red_temperature_simulation()
self.assertTrue((test_value < 100.0) or (test_value > 103.0),
msg="Test failed for {}".format(test_value))

And now everything works the way it should.

Thanks for all your help :)

-- 
Regards,
Anubhav Yadav
KPIT Technologies,
Pune.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-07 Thread Peter Otten
Anubhav Yadav wrote:

>> Hi Anubhav,
>>
>> Ah!  The assert functions are meant to be used as statements, not as
>> composable expressions.  If you're familiar with the idea of side
>> effects, then you need to understand that you should be calling the
>> assert functions just for their side effects, not for their return value.
>>
>> If you want to test two conditions, do them as  separate statements.  By
>> trying to compose them with 'and', the code actually means something
>> different due to boolean logic short circuiting.
>>
>> If you have questions, please feel free to ask.  Good luck!
>>
> 
> Hi,
> 
> Thanks a lot for replying back. I should do something like this right?
> truth_value = yellow_temperature_simulation() <= 100.5 and
> yellow_temperature_simulation() >= 100.0
> self.assertTrue(truth_value)
> 
> I just want to confirm if I get the concept right?

No, you want to check all constrainsts for one value. The way you write it 
above you check if one value is below 100.5 and another is above 100.0.

In your previous post you state

> when my program is in the yellow state, it should generate the numbers
> from 100.0-100.5
> and 102.5-103.0

The "and" is a bit misleading as you want to allow values that are in the 
first *or* the second intrval. When you spell that in Python it becomes 

temperature = yellow_temperature_simulation()
self.assertTrue(
(100.0 <= temperature < 100.5) 
or (102.5 <= temperature < 103.0))

The extra parentheses aren't required.
If you don't want half-open intervals replace < with <=.

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


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-07 Thread Anubhav Yadav
> Hi Anubhav,
>
> Ah!  The assert functions are meant to be used as statements, not as
> composable expressions.  If you're familiar with the idea of side effects,
> then you need to understand that you should be calling the assert functions
> just for their side effects, not for their return value.
>
> If you want to test two conditions, do them as  separate statements.  By
> trying to compose them with 'and', the code actually means something
> different due to boolean logic short circuiting.
>
> If you have questions, please feel free to ask.  Good luck!
>

Hi,

Thanks a lot for replying back. I should do something like this right?
truth_value = yellow_temperature_simulation() <= 100.5 and
yellow_temperature_simulation() >= 100.0
self.assertTrue(truth_value)

I just want to confirm if I get the concept right?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-06 Thread boB Stepp
On Sat, Feb 6, 2016 at 3:54 PM, boB Stepp  wrote:
> On Sat, Feb 6, 2016 at 10:07 AM, Anubhav Yadav  wrote:

Just read Danny's reply after sending mine, which means that the
answer to my question:

> If my understanding is indeed correct, then I will leave it to you to
> figure out which logic operator ("and" or "or") makes sense here!
> ~(:>))

must be neither one!  Thanks, Danny!

However, I do believe (Until proven otherwise.) my first point is still valid.

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


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-06 Thread boB Stepp
On Sat, Feb 6, 2016 at 10:07 AM, Anubhav Yadav  wrote:


> class TestCase(unittest.TestCase):
> def test_red_temperature_simulation(self):
> """
> Method to test the red_temperature_simulation method
> """
> for i in range(10):
> self.assertLess(red_temperature_simulation(), 100.0) and \
> self.assertGreater(red_temperature_simulation(), 103.0)

Is this really what you want (And similarly in your other test
method.)?  If I am reading things correctly, you are calling
red_temperature_simulation *twice*, which will *usually* give you two
*separate* values, which you then attempt to compare.  Shouldn't you
first do:

for i in range(10):
value_to_test = red_temperature_simulation()
(self.assertLess(value_to_test, 100.0) 
self.assertGreater(value_to_test, 103.0))
?

If my understanding is indeed correct, then I will leave it to you to
figure out which logic operator ("and" or "or") makes sense here!
~(:>))



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


Re: [Tutor] Need help with two similar test cases that I have written. One works and the other fails

2016-02-06 Thread Danny Yoo
On Feb 6, 2016 12:31 PM, "Anubhav Yadav"  wrote:
>
> Hello Everyone,
>
> I am trying to write a simple program that generated random numbers based
> on some rules.
> when my program is in the yellow state, it should generate the numbers
> from 100.0-100.5
> and 102.5-103.0. When my program is in the red state, it should generate
> numbers in the range
> less than 99.9 and greater than 103.1.
>
> I have written two very simple functions, and two unittest.TestCase test
> cases to test the two functions. I somehow feel that both my test cases
> doesn't make any sense, yet one of it passes perfectly and other one does
> not pass.

Hi Anubhav,

Ah!  The assert functions are meant to be used as statements, not as
composable expressions.  If you're familiar with the idea of side effects,
then you need to understand that you should be calling the assert functions
just for their side effects, not for their return value.

If you want to test two conditions, do them as  separate statements.  By
trying to compose them with 'and', the code actually means something
different due to boolean logic short circuiting.

If you have questions, please feel free to ask.  Good luck!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need Help

2016-01-25 Thread Mark Lawrence

On 25/01/2016 16:09, Parinay Mahakur wrote:

Hello Tutors,

I need a program that should enable me to read values from a large number
of ASCII files and then I have to plot desired values - In this file
headings for all columns are also given. The link for the file is -

http://jsoc.stanford.edu/SUM75/D780005879/S0/hmi.rdVfitsf_fd15.2171.015.355.0.-67.5.-20.0.fit.out


Start here https://docs.python.org/3/tutorial/index.html as we don't 
write code for you.


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

Mark Lawrence

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


Re: [Tutor] Need Help

2016-01-25 Thread Alan Gauld
On 25/01/16 16:09, Parinay Mahakur wrote:

> I need a program that should enable me to read values from a large number
> of ASCII files and then I have to plot desired values

Have you considered a spreadsheet like Excel?
You could write a couple of macros to read the files
and to generate the plots.

If you want to do it in Python then we need a lot more
details, and some visibility of the code you've written
so far.


-- 
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] Need help with python

2015-09-14 Thread Alan Gauld

On 15/09/15 00:25, Laura Creighton wrote:

The gmane.org reference is here:

gmane.comp.python.testing.general
I am not getting anything sensible out of this.


Works for me, but admittedly I only see one post in September.


--
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] Need help with python

2015-09-14 Thread Laura Creighton
In a message of Mon, 14 Sep 2015 19:48:01 +0100, Alan Gauld writes:
>On 14/09/15 18:02, vijayram wrote:
>> Hi,
>>
>>   I need help with python nose tests and test-suite…  can I request help 
>> with a tutor..
>
>You can try asking basic questions here, but as nose is not
>part of the standard library you might get more help on the
>python testing list:
>
>The gmane.org reference is here:
>
>gmane.comp.python.testing.general

I am not getting anything sensible out of this.
But the testing list is over here:
http://lists.idyll.org/pipermail/testing-in-python/
Though it has been unbelievably quiet this month ...

Laura

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


Re: [Tutor] Need help with python

2015-09-14 Thread Alan Gauld

On 14/09/15 18:02, vijayram wrote:

Hi,

  I need help with python nose tests and test-suite…  can I request help with a 
tutor..


You can try asking basic questions here, but as nose is not
part of the standard library you might get more help on the
python testing list:

The gmane.org reference is here:

gmane.comp.python.testing.general

--
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] Need help with python

2015-09-14 Thread Steven D'Aprano
On Mon, Sep 14, 2015 at 10:02:35AM -0700, vijayram wrote:
> Hi,
> 
>  I need help with python nose tests and test-suite…  can I request help with 
> a tutor..

Sure. Ask your questions on the mailing list, and somebody will answer.

This is a group for *public* tutoring, so that everyone can learn from 
it, not private tutoring.


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


Re: [Tutor] Need help writing code with python

2015-02-08 Thread Ben Finney
Alan Gauld  writes:

> Third,
> The attachment didn't get here. So I've no idea what your assignment
> was. Its usually better to copy the text into the mail body.

Given that the attachment was described as “my project”, I would advise
not sending it here in any form.

Copy text here if it's *small*, and *focussed*, and relevant to some
part of the discussion. If the text is “my project”, it's better not put
here at all.

I am glad the attachment was discarded, it sounds like sending it to all
recipients of this forum would have been only an annoyance.

Conner, please obtain the time to do the project unhurried; then, feel
free to come to this forum with *focussed* questions on aspects of the
Python code you are writing. We don't need to see the project.

-- 
 \  “I find the whole business of religion profoundly interesting. |
  `\ But it does mystify me that otherwise intelligent people take |
_o__)it seriously.” —Douglas Adams |
Ben Finney

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


Re: [Tutor] Need help writing code with python

2015-02-08 Thread Dave Angel

On 02/07/2015 05:36 PM, Conner Wood wrote:

I fell behind 2 weeks in my class due to surgery and have a coding project
due tonight (Saturday, Feb. 7).  I've attached my project to this email.
Please help!  Also, I'm using a Mac laptop if that helps in anyway.  Please
get back to me as soon as you can.



Welcome to Python-tutor.  This seems to be your first post.

Thanks for making it a text email.  And for mentioning your OS.  But you 
also should be specifying the Python version.


There's no attachment to your message in the mailing list.  And many 
people here can't see attachments anyway.  If your project is too big to 
include directly in your email message, you may be out of luck.


How big a project is it, and how much of it have you been able to do so 
far?  Is there some particular problem that has you stumped?


We're here to help you get past some sticking point, not to do your 
assignment for you.  I'd expect your prof would give you an extension if 
you can't get it in because of unexpected surgery.





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


Re: [Tutor] Need help writing code with python

2015-02-08 Thread Alan Gauld

On 07/02/15 22:36, Conner Wood wrote:

I fell behind 2 weeks in my class due to surgery and have a coding project
due tonight (Saturday, Feb. 7).  I've attached my project to this email.
Please help!  Also, I'm using a Mac laptop if that helps in anyway.  Please
get back to me as soon as you can.


First.
We won't do homework for you so we need to see what you have done.
You need to have made some kind of attempt. Or at least have some 
specific questions.


Second
Asking for a response on the day that the assignment is due on
a mailing list isn't going to work, it didn't get here until Sunday.
I hope you got something done on Saturday but you need to give
a mailing list a bit more notice. Email can take up to 24 hours to
reach its destination, never assume it will be quicker than that
(even if 99% of the time it is).

Third,
The attachment didn't get here. So I've no idea what your assignment 
was. Its usually better to copy the text into the mail body.


Fourth.
Please give more than the fact you've got a Mac. So have I; its an old 
iBook that runs MacOS 10.4 on a 600MHz PowerPC chip. I suspect that's 
quite different to yours. Tell us the OS version and the Python version 
you are using.


--
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] Need help writing code with python

2015-02-08 Thread Ben Finney
Conner Wood  writes:

> I fell behind 2 weeks in my class due to surgery and have a coding
> project due tonight (Saturday, Feb. 7). I've attached my project to
> this email.

My sympathies with your situation, I hope your surgery was successful
and you are in good health.

This is not a forum for doing your project; you will need to do your own
project.

Rather, this is a forum for publicly discussing much more focussed
topics. We tutor each other in learning Python and its idioms and
ecosystem.

We don't do one-on-one tutoring, and we don't do coding for you.

If you have a *small* portion of code that demonstrates some behaviour
that confuses you, we can talk you through the confusion (provided the
code can also behave the same for us, and provided we know what you
expected from that code).

If you have a large project, you'll need to do the work, or get some
largesse from the people expecting that work. It seems you have an
entirely valid reason to ask for a time extension.

Good hunting!

-- 
 \  “I knew things were changing when my Fraternity Brothers threw |
  `\   a guy out of the house for mocking me because I'm gay.” |
_o__)  —postsecret.com, 2010-01-19 |
Ben Finney

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


Re: [Tutor] Need help with find error

2015-02-04 Thread Danny Yoo
As a revision of my initial question, when we look at next_block(),
it's documented as follows:


def next_block(the_file):
"""Return the next block of data from the trivia file."""



What if there are no more blocks in the file?  What should happen then?

Let's say that we do a test, where we pass in the empty file to next_block().

##
from io import StringIO
x = next_block(StringIO(''))
##

What do you want to happen in this situation?

---

As a side note: if you have control over the data format, you might
want to consider using JSON rather than a line-based format.  If you
use JSON, this takes care of a few issues that you are working around
now.

For example, you can reuse the newline escapes rather than define your
own convention.  Also, rather than read a stream of records, where you
have to deal with the end of the file, you might just read one JSON
object that represents your whole trivia file, which will simplify
your program's logic.

See: https://docs.python.org/2/library/json.html and use your favorite
web search engine for 'json python tutorial', and you should be able
to find some useful information.  If you have questions, please feel
free to ask.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with find error

2015-02-04 Thread Danny Yoo
On Wed, Feb 4, 2015 at 1:01 AM, Андрей Пугачев
 wrote:
> Hi
> I'm learning python a few weeks and have problems with code that read text
> from txt-file
> Code doing all right, but in the end I have error
>
> Traceback (most recent call last):
>   File "trivia_challenge.py", line 81, in 
> main()
>   File "trivia_challenge.py", line 74, in main
> category, question, answers, correct, explanation, points =
> next_block(trivia_file)
>   File "trivia_challenge.py", line 37, in next_block
> points = int(next_line(the_file))
> ValueError: invalid literal for int() with base 10: ''



Your next_line() function looks a little off.  Let's take a look at it:


def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line


What do you want to happen here, when there are no more lines in the
file to read?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with find error

2015-02-04 Thread Peter Otten
Андрей Пугачев wrote:

> Hi
> I'm learning python a few weeks and have problems with code that read text
> from txt-file
> Code doing all right, but in the end I have error
> 
> Traceback (most recent call last):
>   File "trivia_challenge.py", line 81, in 
> main()
>   File "trivia_challenge.py", line 74, in main
> category, question, answers, correct, explanation, points =
> next_block(trivia_file)
>   File "trivia_challenge.py", line 37, in next_block
> points = int(next_line(the_file))
> ValueError: invalid literal for int() with base 10: ''
> 
> I see it don't like empty line, but line is not emty...
> 
> py-file http://pastebin.com/9C4guZq5
> 
> txt-file http://pastebin.com/dZVs8V9P

Put some debugging code into your script that keeps track of the line you 
are reading. For that you can modify the next_line() routine:

current_line = 0
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
global current_line

line = the_file.readline()
print("XXX CURRENT LINE", current_line, repr(line))
current_line += 1

line = line.replace("/", "\n")
return line

Then, when you run the script again, there will be a line

XXX CURRENT LINE 451 'yabba dabba doo\n'

printed right before the exception is triggered. Once you know the line 
(hint: it's not actually a line in the file) the problem should be easy to 
fix. (Come back here to ask for more hints if you cannot fix it.)

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


Re: [Tutor] Need help with find error

2015-02-04 Thread Alan Gauld

On 04/02/15 09:01, Андрей Пугачев wrote:


Code doing all right, but in the end I have error

Traceback (most recent call last):
   File "trivia_challenge.py", line 81, in 
 main()
   File "trivia_challenge.py", line 74, in main
 category, question, answers, correct, explanation, points =
next_block(trivia_file)
   File "trivia_challenge.py", line 37, in next_block
 points = int(next_line(the_file))
ValueError: invalid literal for int() with base 10: ''

I see it don't like empty line, but line is not emty...



OK, But what is it? Does it contain any spaces or letters or punctuation 
characters?


Try separating out the line and then adding a try/except like so:

try:
   line = next_line(the_file)
   points = int(line)
except ValueError:
   print "Line causing error is: \n;", repr(line)
   raise

That way you will see exactly what causes the exception.

--
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] Need help!

2014-12-13 Thread Adam Jensen
On Fri, 12 Dec 2014 07:46:05 -0500
Jagannath Ramanan  wrote:

> My name is jag. I need little bit of help understanding something. I have a
> vncserver running at the background in redhat. My client is lubuntu where
> im using python.
> 
> For some reason the communication is only possible between them is to send
> custom TCP/IP messages. Im not a hardcore developers. I can do scripts and
> i have used gtk python for front ends etc.
> 
> *The TCP /IP message length is:*
> 
> TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37
> bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes
> I have no idea how i would code something like that in python to make it
> talk to the server.

When you hear hoofbeats, think of horses not zebras.

It's possible you only need to open a TCP port in the RedHat machine's firewall:

/sbin/iptables -I INPUT 1 -p tcp -d ${ip_of_lubuntu} --dport ${port} -j ACCEPT

For experimentation and development, it might be best to select a port number 
within the range 49152–65535.

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


Re: [Tutor] Need help!

2014-12-12 Thread Cameron Simpson

On 12Dec2014 07:46, Jagannath Ramanan  wrote:

My name is jag. I need little bit of help understanding something. I have a
vncserver running at the background in redhat. My client is lubuntu where
im using python.

For some reason the communication is only possible between them is to send
custom TCP/IP messages. Im not a hardcore developers. I can do scripts and
i have used gtk python for front ends etc.

*The TCP /IP message length is:*

TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37
bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes
I have no idea how i would code something like that in python to make it
talk to the server.


I think you need to supply some more detail. The above looks like small snippet 
from a much larger document. It sounds to me like that is from a summary of 
some protocol which is slightly different over TCP from over a serial line.


When you say "the communication is only possible between them is to send custom 
TCP/IP messages", what kind of communication to you have in mind? Normally a 
VNC service on your redhat box is simply a way of presenting a virtual display 
for remote interaction. It would be unusual for that to be your only choice 
unless you have a specific task in mind.


Cheers,
Cameron Simpson 

Sometimes the only solution is to find a new problem.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help!

2014-12-12 Thread Alan Gauld

On 12/12/14 12:46, Jagannath Ramanan wrote:


vncserver running at the background in redhat. My client is lubuntu where
im using python.

For some reason the communication is only possible between them is to send
custom TCP/IP messages.


What makes you think so?
Is that something you have been told?
Is it a technical requirement of your project?
Have you tried communicating in any other way
- eg. ping, ftp, ssh, http etc/

Also does it need to be TCP/IP? Could it be UDP over IP instead?
If the messages are simple UDP can sometimes be easier to work with.


*The TCP /IP message length is:*

TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37
bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes
I have no idea how i would code something like that in python to make it
talk to the server.


It may be possible but it's well beyond the scope of learning Python
and its library. You are probably better asking on the main python
list. Assuming you really must go down this path of course.

You might want to find a copy of "Foundations of Python Network 
Programming" by Goertzen. It's probably the best reference for 
networking on Python. But even he doesn't discuss creating

bespoke packets which is what you seem to be asking about.

The other classic text is Richard Steven's book(s)
"Unix Network Programming: Sockets Networking API v.1"

It's aimed at C programmers and very low level but for what you
want it may be the best bet.

--
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] Need help!

2014-12-12 Thread Oscar Benjamin
On 12 December 2014 at 12:46, Jagannath Ramanan
 wrote:
> Dear Sir / Madam,
>
> My name is jag.

Hi Jag,

> I need little bit of help understanding something. I have a
> vncserver running at the background in redhat. My client is lubuntu where
> im using python.
>
> For some reason the communication is only possible between them is to send
> custom TCP/IP messages. Im not a hardcore developers. I can do scripts and
> i have used gtk python for front ends etc.
>
> *The TCP /IP message length is:*
>
> TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37
> bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes
> I have no idea how i would code something like that in python to make it
> talk to the server.
>
> Any any help or guidance is sincerely appreciated.
>
> Thanks in advance!!

I'm don't really understand from your description what needs to be
done so I can't offer any code that would do it.

However I see that there is a module called vncdotool on PyPI here:
https://pypi.python.org/pypi/vncdotool

Apparently that module is made to speak to VNC servers. Perhaps you
could give it a try.


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


Re: [Tutor] Need help!

2014-12-12 Thread Danny Yoo
On Dec 12, 2014 8:54 AM, "Jagannath Ramanan" 
wrote:
>
> Dear Sir / Madam,
>
> My name is jag. I need little bit of help understanding something. I have
a
> vncserver running at the background in redhat. My client is lubuntu where
> im using python.
>

This question is out of scope for a beginner tutor forum.  I don't think
many of us can help you with low level network programming.  We can point
you to resources like the Socket HOWTO at
https://docs.python.org/2/howto/sockets.html.  But what you're asking
sounds much more low level than that.

You may want to check on python-list.
https://mail.python.org/mailman/listinfo/python-list
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help to convert pdf to excel

2014-10-19 Thread Danny Yoo
On Sun, Oct 19, 2014 at 7:27 AM, AMNA MOHAMMED ALRUHEILI
 wrote:
> My name is Amna and I am totally new to python world with zero experience in
> programming. I am facing the challenge of converting data from pdf to excel.
> The data within pdf is numbers separated by space not within a table.
> I need a help to figure out a code that help me to convert these pdf to
> excel.

Can you get the original data in a format that is not PDF?  PDF is a
human-centric published format: its concerns are typographic.  It is
not intended primarily for computers to extract data.  Certainly you
can extract data from it, but it won't be structured in a way that
makes it particularly easy.

That being said: you might try an approach that gets text from a PDF:


http://stackoverflow.com/questions/25665/python-module-for-converting-pdf-to-text

and then write some processing program that takes that text and
inserts into an excel spreadsheet.  There are several libraries that
other programmers have written to write Excel documents from Python.
For example:

https://xlsxwriter.readthedocs.org/



As a side comment: this task actually does require a significant bit
of programming knowledge.  I believe it would be an unfair and
unreasonable request to ask a complete programming beginner to do this
without some basic programming training.  I would strongly recommend
taking an introductory programming class first, before trying to
tackle your PDF->Excel problem head on.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with python script

2014-08-04 Thread Joel Goldstick
On Mon, Aug 4, 2014 at 11:20 AM, P McCombs  wrote:
> Sorry, I missed copying this to the list.
>
> On Aug 4, 2014 8:13 AM, "P McCombs"  wrote:
>
>
>>
>>
>> On Jul 31, 2014 4:50 PM, "McKinley, Brett D."  wrote:
>> >
>> > I would like to see if someone can help me with a python script.  I’m
>> > trying to export a file geodatabase feature class to csv file.  This is 
>> > what
>> > I have so far:
>>
>> Does the code you attached execute successfully?
>> Are you running this as a tool,  or from the command line?
>> Be cautioned that arcpy is outside the scope of this mailing list,  but it
>> won't have much to do with your questions at first.
>
>>
>> >
>> >
>> > import arcpy
>> >
>> > import os
>> >
>> > import csv
>> >
>> > import domainvalues
>> >
>> >
>> >
>> >
>> >
>> > def export_to_csv(dataset, output, dialect):
>> >
>> > """Output the data to a CSV file"""
>> >
>> > # create the output writer
>> >
>> > out_writer = csv.writer(open(output, 'wb'), dialect=dialect)
>> >
>> > # return the list of field names and field values
>> >
>> > header, rows = domainvalues.header_and_iterator(dataset)
>> >
>> >
>> >
>> > # write the field names and values to the csv file
>> >
>> > out_writer.writerow(map(domainvalues._encodeHeader, header))
>> >
>> > for row in rows:

before you write row, you need to examine the appropriate fields to
filter out the fields you don't want, and order the rows by whichever
field determines newness.
Also, you probably want to output your header row to only include
columns you wish to write
>> >
>> > out_writer.writerow(map(domainvalues._encode, row))
>> >
>> >
>> >
>> > if __name__ == "__main__":
>> >
>> > # Get parameters
>> >
>> > dataset_name = arcpy.GetParameterAsText(0)
>> >
>> > output_file = arcpy.GetParameterAsText(1)
>> >
>> > delim = arcpy.GetParameterAsText(2).lower()
>> >
>> > dialect = 'excel'
>> >
>> > if delim == 'comma':
>> >
>> > pass
>> >
>> > else:
>> >
>> > dialect = 'excel-tab'
>> >
>> > try:
>> >
>> > export_to_csv(dataset_name, output_file, dialect)
>> >
>> > except Exception as err:
>> >
>> > arcpy.AddError('Error: {0}'.format(err))
>> >
>> >
>> >
>> >
>> >
>> > I would like for the script to export only certain fields and also
>> > export only the newest records.  As for now, it’s exporting everything.
>> >
>>
>> It is best to try to add one new feature on your own and attach the
>> result. You will get the best feedback that way.
>>
>> >
>> >
>> > Thanks
>> >
>> > Brett McKinley
>> >
>> >
>> >
>> >
>> >
>> >
>> > ___
>> > 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
>



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


Re: [Tutor] Need help with python script

2014-08-04 Thread P McCombs
Sorry, I missed copying this to the list.

On Aug 4, 2014 8:13 AM, "P McCombs"  wrote:
>
>
> On Jul 31, 2014 4:50 PM, "McKinley, Brett D."  wrote:
> >
> > I would like to see if someone can help me with a python script.  I’m
trying to export a file geodatabase feature class to csv file.  This is
what I have so far:
>
> Does the code you attached execute successfully?
> Are you running this as a tool,  or from the command line?
> Be cautioned that arcpy is outside the scope of this mailing list,  but
it won't have much to do with your questions at first.
>
> >
> >
> > import arcpy
> >
> > import os
> >
> > import csv
> >
> > import domainvalues
> >
> >
> >
> >
> >
> > def export_to_csv(dataset, output, dialect):
> >
> > """Output the data to a CSV file"""
> >
> > # create the output writer
> >
> > out_writer = csv.writer(open(output, 'wb'), dialect=dialect)
> >
> > # return the list of field names and field values
> >
> > header, rows = domainvalues.header_and_iterator(dataset)
> >
> >
> >
> > # write the field names and values to the csv file
> >
> > out_writer.writerow(map(domainvalues._encodeHeader, header))
> >
> > for row in rows:
> >
> > out_writer.writerow(map(domainvalues._encode, row))
> >
> >
> >
> > if __name__ == "__main__":
> >
> > # Get parameters
> >
> > dataset_name = arcpy.GetParameterAsText(0)
> >
> > output_file = arcpy.GetParameterAsText(1)
> >
> > delim = arcpy.GetParameterAsText(2).lower()
> >
> > dialect = 'excel'
> >
> > if delim == 'comma':
> >
> > pass
> >
> > else:
> >
> > dialect = 'excel-tab'
> >
> > try:
> >
> > export_to_csv(dataset_name, output_file, dialect)
> >
> > except Exception as err:
> >
> > arcpy.AddError('Error: {0}'.format(err))
> >
> >
> >
> >
> >
> > I would like for the script to export only certain fields and also
export only the newest records.  As for now, it’s exporting everything.
> >
>
> It is best to try to add one new feature on your own and attach the
result. You will get the best feedback that way.
>
> >
> >
> > Thanks
> >
> > Brett McKinley
> >
> >
> >
> >
> >
> >
> > ___
> > 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] need help reading the code

2014-07-07 Thread Alan Gauld

On 07/07/14 19:29, keith papa wrote:
# decimal (.) precision of 3 for float '0.333'

>>> print '{0:.3f}'.format(1.0/3)

The best way to see how this works is to try it
with different values:

>>> print('{0:.3f}'.format(1.0/3))
0.333
>>> print('{0:.5f}'.format(1.0/3))
0.3
>>> print('{0:.1f}'.format(1.0/3))
0.3
>>> print('{0:.5f}'.format(1.0/2))
0.5
>>>

Look at how many digits appear after the decimal
point in each case.


# fill with underscores (_) with the text centered
# (^) to 11 width '___hello___'

>>> print '{0:_^11}'.format('hello')

Again, try it out with different values.
The tricky thing here is that he is showing 3 different features in one 
example.

Try breaking them down into 3 different sets then
building them back up:

set width of field:

>>> print('{:11}'.format('hello'))
hello
>>> print('{:3}'.format('hello'))
hello
>>>

Hmmm, Doesn't seem to do anything...Lets add some justification

>>> print('{:<11}'.format('hello'))
hello
>>> print('{:>11}'.format('hello'))
  hello
>>> print('{:^11}'.format('hello'))
   hello

Somethings happening, but to really see what it is...

add a padding character so you see the 'spaces;:

>>> print('{:_>11}'.format('hello'))
__hello
>>> print('{:_<11}'.format('hello'))
hello__
>>> print('{:_^11}'.format('hello'))
___hello___

Which is where we came in...

Try different padding characters and change the width values.

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] need help reading the code

2014-07-07 Thread Alan Gauld

On 07/07/14 19:29, keith papa wrote:

Please post in plain text and avoid attachments if possible.
Just paste code directly into the email.

I've had to cut n paste everything to write this which is a pain...

>>> print '{0} was {1} years old when he wrote this book'.format(name, age)

>>> print 'Why is {0} playing with that python?'.format(name)

# I no that the code will give you the same output even without numbers:

Yes the numbers are not needed here but consider this example:

>>> print "{0} loves {1} but {2} hates {0}!".format('Joe', 'food', 'Anne')

Now you need the numbers because you are using the same value (0)twice.

I'll look at the other issues in separate mails.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Need help with generators....

2014-02-15 Thread Alan Gauld

On 15/02/14 13:35, Bunny Sehgal wrote:

I am doing "Building Skills in Python". In the Generator Function
example at


I assume you are talking about this one:

spins = [('red', '18'), ('black', '13'), ('red', '7'),
('red', '5'), ('black', '13'), ('red', '25'),
('red', '9'), ('black', '26'), ('black', '15'),
('black', '20'), ('black', '31'), ('red', '3')]

def countReds( aList ):
count= 0
for color,number in aList:
if color == 'black':
yield count
count= 0
else:
count += 1
yield count

gaps= [ gap for gap in countReds(spins) ]
print gaps



what i understood is as follows:>
1)First it makes count = 0
2)then it goes straight in for loop
3)Since the first color is red, it goes in else block and increment
count to 1 and stop execution.


What makes you think it stops?
It carries on to the next iteration which is black and so enters the if 
block which yields the count which will be 1.



4)Now its next method is called using list comprehension, and it resumes
its execution and yield its first value i.e. 1.Note that the yield
statement is outside the for loop.


Not quite,
Next time round it carries on from the yield so sets count back
to zero and fetches the next two tuples before hitting another
black. So this time it yields 2.

Once the tuples are exhausted it yields the final count,
which should be 1


5)Now there is no further yield statement which can stop execution of
countreds() function.So it raises StopExecution exception

But this is not what is happening. why?


Your understanding was flawed. Assuming I've pasted the correct code 
listing... But there is an explanation right under the listing on the 
page. Assuming you read it, which bit of that did you not understand?


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] need help

2014-01-11 Thread Walter Prins
Hi,


On 11 January 2014 14:52, S Tareq  wrote:

> how can i do this on python using py game:
>
>
You need to tell us more about what you've tried and where you're stuck.
Needless to say we're not a solution provision service, but we'd be happy
to help you get unstuck if you've already done some programming and have
gotten to a point where you're actually stuck.  :)

For the reference of others, I've managed to track down the full task
description here:
http://www.kirkbiekendal.cumbria.sch.uk/index.php/public-documents/school/general-information?download=339:2014-component-1-gaming-scenario-candidate-booklet

As this is therefore clearly homework that you'll be handing in, please
note we absolutely cannot provide you with concrete solutions to this
assignment.

As to your reference to PyGame -- I'd like to gently suggest that perhaps
you should not worry about PyGame if you're just starting out.  You can get
started without it and build a more basic solution first (maybe just simple
text mode) and then deal with whether you want to enhance/modify your
solution to use PyGame at some later time.

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


Re: [Tutor] need help

2014-01-11 Thread Mark Lawrence

On 11/01/2014 14:52, S Tareq wrote:

how can i do this on python using py game:



No idea as what you've sent isn't readable when you try to reply. Also I 
can't see any code so sorry but I'm not doing your homework for you :(


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


Mark Lawrence

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


Re: [Tutor] need help how to run it on python 3.3

2014-01-08 Thread Dave Angel
On Wed, 8 Jan 2014 20:54:09 + (GMT), S Tareq  
wrote:

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


This is a text newsgroup.  Html messages and attachments of any kind 
(especially binary ones) are out of place. 

Guessing that you're trying to show an error message,  I'd suggest 
copy/paste not screen shot.  And if your terminal type doesn't seem 
to support the clipboard,  tell us what you're using and somebody 
will probably have a suggestion.


--
DaveA

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


Re: [Tutor] need help how to run it on python 3.3

2014-01-08 Thread Mark Lawrence

On 08/01/2014 20:54, S Tareq wrote:


On Wednesday, 8 January 2014, 20:46, Danny Yoo 
wrote:
Hi S Tareq,

You probably want to review the "What's new in Python 3" document,
with close attention to the "Common Stumbing Blocks" section:

http://docs.python.org/3.0/whatsnew/3.0.html#common-stumbling-blocks

Have you read this document already?



Please don't attach 118kb screenshot files when you could have used cut 
and paste for the four lines that are relevant.


--
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] need help how to run it on python 3.3

2014-01-08 Thread Danny Yoo
Hi S Tareq,

If you can, next time please just copy and paste the error message as
plain text.  Please avoid screenshots unless they really are relevant
to the problem at hand.

There are good reasons why you should prefer plain text when asking
questions on a mailing list like this one.  (1) Screenshots are often
useful but resource-intensive.  (2) Screenshots are difficult to
search and index: folks who are using non-graphical email clients have
no way of helping you, and search engines become less useful when run
across our archives in the presence of non-textual content.


Anyway, the error message you're running into:

NameError: name 'raw_input' is not defined


is because Python 2's 'raw_input()' has been renamed to Python 3's 'input()'.


Again, please _closely_ read the document:

http://docs.python.org/3.0/whatsnew/3.0.html#builtins

which lists this and other backwards-incompatible changes to the language.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help how to run it on python 3.3

2014-01-08 Thread Steve Mayer
You might want to check out the '2to3' program to convert Python 2.x 
code to Python 3.x code.


The following command worked to change your code to runnable Python 3.x 
code:


   2to3 -w 



--
Steve Mayer
smaye...@me.com

On 8 Jan 2014, at 10:19, S Tareq wrote:

need help how to run it on python 3.3, or change it to python 3.3 when 
i run it says syntax error if i run it on python 2.7 it works. 



# Import statements
import random
import datetime
#Arrays to store the definitions and keywords read from the file
keywords=[];
definition=[];
correctAnswer=[];
#Counter for the wrong Answer and counter of number of definition in
correctAnswerCounter=0 
wrongAnswer=0;
counter=0;
# Taking User input for accepting the file name to be read
filename= raw_input("Enter the File Name with extension")
#Reading the file from start to the end
for line in open(filename,'r').readlines():
    if(counter%2==0):
        keywords.append(line);
        counter=counter+1;
        correctAnswer.append(0)
    else:
        definition.append(line);
        keys=[];
        keys=line.split(" ");
        counter=counter+1;
# Running two while loops to make the pattern recursive
while True:
# Starting the time for quiz and also, creating variables to make sure 
that same sequences and answers are not repeated

    a = datetime.datetime.now().replace(microsecond=0)
    prevWord=0
    prevSeq=0
    # While loop to run the code till each answer is correctly 
answered

    while correctAnswer.count(2)!=(counter/2):
        #While loop to generate an different random number from 
one the generated previously

        while True:        
            word=random.randint(0,(counter/2)-1)
            if(correctAnswer[word]!=2):
                break;
            if(prevWord==word):
                continue;
        # Displaying the new keyword each time.
        print "Please Select the number which is the correct 
definition of the word:" ,keywords[word]
        #Generating an new sequence each time different from 
previous one

        while True:
            sequences =random.randint(0,2)
            if(prevSeq==sequences):
                continue;
            else:
                break
        #Generating an new incorrect answer each time different 
from previous one

        while True:
            
incorrectAnswer=random.randint(0,len(correctAnswer)-1)

            if(incorrectAnswer==word):
                continue;
            else :
                break
        #Generating an new incorrect answer  each time different 
from previous one

        while True:
            
incorrectAnswerSecond=random.randint(0,len(correctAnswer)-1);

            if (incorrectAnswer==incorrectAnswerSecond):
                continue
            if(incorrectAnswerSecond==word):
                continue
            else:
                break
        # Displaying the options to the user based on the sequence 
number generated

        if (sequences==0):
            print "1.",definition[word]
            print "2.",definition[incorrectAnswer]
            print "3.",definition[incorrectAnswerSecond]
        elif (sequences==1):
            print "1.",definition[incorrectAnswer]
            print "2.",definition[incorrectAnswerSecond]
            print "3.",definition[word]
        elif (sequences==2):
            print "1.",definition[incorrectAnswerSecond]
            print "2.",definition[word]
            print "3.",definition[incorrectAnswer]
        #Taking the answer from user
        answer = raw_input("Enter the Correct Number between 1 to 
3")

        # Assign the seq and word to preseq and word
        prevSeq=sequences
        prevWord=word
        #Checking the answer if they are corret.
        if(0 == sequences):
            if(answer == "1"):
                print "success"
                correctAnswer[word]=correctAnswer[word]+1
                correctAnswerCounter=correctAnswerCounter+1
            else:
                print "Wrong Answer"
                print "Correct Answer: " ,definition[word]
                wrongAnswer=wrongAnswer+1;
        elif(1 == sequences):
            if(answer == "3"):
                print "success"
                correctAnswer[word]=correctAnswer[word]+1
                correctAnswerCounter=correctAnswerCounter+1
            else:
                print "Wrong Answer"
                print "Correct Answer: " ,definition[word]
                wrongAnswer=wrongAnswer+1;
        elif(2 == sequences):
            if(answer == "2"):
                print "success"
                correctAnswer[word]=correctAnswer[word]+1
                correctAnswerCounter=correctAnswerCounter+1
            else:
                print "Wrong Answer"
                print "Correct Answer: " ,definition[word]
                wrongAnswer=wrongAnswer+1
    # Stopping the time of the clock
    b = datetime.datetime.now().replace(microsecond=0)
    # displaying number of wrong answer and total quiz time
    print "Total Number o

Re: [Tutor] need help how to run it on python 3.3

2014-01-08 Thread Danny Yoo
Hi S Tareq,


You probably want to review the "What's new in Python 3" document,
with close attention to the "Common Stumbing Blocks" section:

http://docs.python.org/3.0/whatsnew/3.0.html#common-stumbling-blocks

Have you read this document already?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help how to run it on python 3.3

2014-01-08 Thread Mark Lawrence

On 08/01/2014 18:19, S Tareq wrote:

need help how to run it on python 3.3, or change it to python 3.3 when i
run it says syntax error if i run it on python 2.7 it works.




 if(counter%2==0):


Please remove those unneeded brackets, this is a Python list, not C :)


 print "Please Select the number which is the correct definition
of the word:" ,keywords[word]


Please add the needed brackets, print is a function in Python 3, not a 
statement.


--
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] Need help on Python API programmig

2013-11-16 Thread Amit Saha
Hi Sourav,

Please use "Reply all" when you reply an email so that everyone else
also gets your messages and your chances of getting better help
increases.


On Sat, Nov 16, 2013 at 3:35 PM, Sourav Biswas  wrote:
> Hi Amit,
>
> Yes I know, the question is not quite good. Currently I am trying to learn
> web API programming with Python. The ultimate goal is work with OpenStack
> API.
>
> Can you please let me know, how to start on this.
>
> Thanks for the reply and thanks in advance.
>

Sorry, I certainly didn't mean that your question was "not good". Now
that you have mentioned what specifically you are looking to learn, it
becomes slightly easier to make some suggestions. I don't have any
personal experience with OpenStack API. However, looking at [1], it
seems like you will be mostly dealing with making HTTP requests and
reading responses. There are couple of standard library modules such
as urlllib2 and httplib that may be useful to you. However, in this
case, you would certainly benefit from directly learning to use
Requests [2]. Note that however, you will need to be familiar with
Python data structures such as dictionaries and know how to work with
JSON data ( please see the 'json' standard module).

[1] http://docs.openstack.org/api/quick-start/content/
[2]http://www.python-requests.org/en/latest/

I am hoping those prove helpful.

All the best,
Amit.

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


Re: [Tutor] Need help on Python API programmig

2013-11-15 Thread Amit Saha
Hello Sourav,

On 16/11/2013 6:53 AM, "Sourav Biswas"  wrote:
>
> Hi All,
>
> This is my first post. I want to learn API programming with Python. I
have basic knowledge of Python Programming. Could you please let me know
the starting points for this programming.

Since your question is fairly vague, could you please describe what you are
trying to learn? An API is an interface. It can be an operating system
interface, a vehicle web API or simply a web API.

Some more details will be a lot of help.

Best, Amit.
>
> --
> Thanks,
> Sourav Biswas
> Hyderabad
>
> ___
> 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] need help with something

2013-09-15 Thread Steven D'Aprano
On Sat, Sep 14, 2013 at 11:17:31PM -0400, Alex Palazzo wrote:
> Hi i need help with something with python. 

And we're here to help. Would you like to tell us what you need help 
with, or shall we guess?


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


Re: [Tutor] need help with something

2013-09-15 Thread Alex Palazzo
Hi i need help with something with python. 

Alexander Palazzo
Rhode Island College '17
(401)474-1669
apalazzo_5...@email.ric.edu___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help appending data to a logfile

2013-06-30 Thread Alan Gauld

On 30/06/13 16:42, Matt D wrote:


im sorry i don't understand how to pass the file name from the open
dialog into the update method?  I'm sorry i just don't get it.   so if
the user opened file is 'handle' like this?:


OK, technically you probably donb;t want to pasws it into the metjod but 
to store it in an attribute of the object.



  def openFile(self, evt):
 with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
"*.txt*", wx.OPEN) as dlg:
if dlg.ShowModal() == wx.ID_OK:
 self.logpath = dlg.GetPath()


Now self.logpath holds a record of the full path to the log file.
(assuming dlg.getPath does return the full path, I haven't
used wxPython for a while...)


def update(self, field_values):
 with open(self.logpath, 'a')  as logfile:

>  # format the line and write to file as before

And that is all you need.
logfile is now your open logfile object referencing the file named by 
the user in the dialog. Because we opened it in a 'with' construct it 
will automatically be closed at the end of the block ready to be 
reopened next time update gets called.


And that is it. No more should be required. Provided you have permission 
to write to the file/folder then you are now logging

to the file specified by the user.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Need help appending data to a logfile

2013-06-30 Thread Alan Gauld

On 30/06/13 15:04, Matt D wrote:


that sounds ideal, but i have not found a way to pass the user selected
file into the loop that writes the data without opening another file.


Don;t pass the file pass the fgile *name*
Then inside the update method open the file(in append mode)
and write the latest update then close the file again. (Or
use the 'with' paradigm which closes the file for you)
Repeat as needed.

Part of the propblem is that you are openming the file right
at the beginning and trying to pass the open file object
around. Pass the filename and open when needed. Its slightly
more resource intensive but a lot simpler.


how would i use shutil to copy the tempory self.logfile into the user
selected file in this open fileFile()?:


The way to go is to only have one file and avoid all the
copying stuff completely.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Need help appending data to a logfile

2013-06-30 Thread Alan Gauld

On 30/06/13 04:41, Matt D wrote:


So i have a program that gets pickled data from a thread and displays
the data (9 strings) in TextCtrl fields in the UI.


The fact that it is a UI is largely irrelevant apart from the
fact that it forces an event driven architecture.


 When the pickle is
received it is processed like this:

def display_data(self,event):

...

 attrs = pickle.loads(pickled_dict)
 self.update(attrs)

attrs is passed into the update function:

  def update(self, field_values):
 #  logger code--
 self.logfile.write('\n')
 self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S",
localtime()
 for k,v in self.fields.items():
 f = field_values.get(k, None)
 if f:
 self.logfile.write('%s,'%(str(f)))
  #end logger code 


Why keep the logfile open? Why not store the logfile name
(as selected by the user) and open the file in the update
function and close it after writing?


so i have the logfile.txt formatted in a was that is very useful for
later inspection with time series analysis.



...  up near the main class constructor the log file is opened like
this:

 self.logfile = open('logfile.txt', 'a')


This is the bit I don't understand. Is there a reason you are
using a hard coded filename? That is the source of much of
your complexity. And why are you opening it so early? Why
not wait till you need to write?


it is stored in the home folder


That's a choice you make with the hard coded name. If you
allow the user to select the name (and folder) it can
be stored anywhere. The user choice can be via a GUI
or via a config file or via a startup argument.


and gets appended every time the program
is run.  Only problem is i need multiple log files


Why do you need multiple log files?
Is there one per user and you have multiple users?
Or do you need multiple files per user?
Or do you only "need" multiple files because you hardcoded
the name and then allow the user to choose their own name?


and the user needs to
be able to choose the file from the UI.


Are you saying the user needs to be able to rename
the file in the middle of processing? If so thats
an unusual requirement but there are ways of doing
it that are easier than what you seem to be doing.


 def openFile(self, evt):
 with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
"*.txt*", wx.OPEN) as dlg:
if dlg.ShowModal() == wx.ID_OK:
 path = dlg.GetPath()
 mypath = os.path.basename(path)
 uf = open(mypath, "a")
 uf.write(self.logfile)


And as we've pointed out you can't write the logfile
*object* you need to read the data and then write it out.
And to read it you need to mess with the cursor using seek()
But if you have already closed the file due to the way
you opened it with 'with' you won;t be able to seek or write.
Hence, I suspect, the error message.


I have been unable to get the logfile.txt written

> into the user opened file.

But I'd really like to understand why you believe this
is needed. Why not just get the user to specify the file
up front and then do all the logging into that.


PS. In the update function you have this:

>  self.logfile.write('\n')
>  self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S",
> localtime()

It might help if you separate out the string formatting from the file 
writing


output = ('\n')
output += ('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S",localtime()
self.logfile.write(output)

And hopefully this makes it obvious that the formatting is overly 
complex you don't need all the string conversion stuff. It can

just be:

)
output = '\n%s,' % strftime("%Y-%m-%d %H:%M:%S",localtime())
self.logfile.write(output)



HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Need help appending data to a logfile

2013-06-29 Thread Dave Angel

On 06/29/2013 09:38 PM, Steven D'Aprano wrote:
 


I haven't read this entire thread, but the bits I have read lead me to
think that Matt has tangled himself up in a total confused mess. It's
*not this hard* to write status messages to a log file, the log module
does all the work. Can anyone who has read the thread summarise what
Matt is attempting to do?



I've been trying to follow the whole thread, and some others before it. 
 But the rules/goals keep changing, and I can't summarize it in any way 
that seems rational.  There are at least 5 files in this system, some 
temporary, some growing, some with pickle stuff.  And none of them is a 
log file.  So I've been answering individual issues instead.



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


  1   2   3   4   5   >