From cs at cskk.id.au  Tue Oct  1 04:03:14 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Tue, 1 Oct 2019 18:03:14 +1000
Subject: [Tutor] print issue
In-Reply-To: <1162792864.1860056.1569899911609@mail.yahoo.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
Message-ID: <20191001080314.GA19311@cskk.homeip.net>

I will supply some commentry below, inline (the preferred style in this 
list). But your problem is hard to understand because your inserted text 
looks a bit malformed. At the least you need to leave a blank line 
between your prose and your "literal" text (the file contents, the 
programme etc).

Also, this is a plain text only list, so any special "rich" formatting 
you might be doing will have no value, and may even be the cause of what 
I see below.

If your mailer has a "plain text" mode, please use it.

So, to your problem...

On 01Oct2019 03:18, ose micah <osaosemwe at yahoo.com> wrote:
>Hello I am trying to make a dynamic print format?
>Assuming "output.txt" has contents as? ? ? 10.10.10.10/24? ? ? 10.10.20.12/24? ? ? 172.50.10.34/24? ? ? 192.168.230.10/24and "samplefile.txt"? is an empty file
>I am trying to get an output such as in file sample.txt? ? ? ? ? ? ? ?- [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [200, 'sing', 'play',?10.10.10.10/24, ?null, null, 800, 800]? ? ? ? ? ? ? ?- [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]

You can see how hard this is to read; that's how things appear at my 
end.

I'm guessing that output.txt has some subnets, each on their own line 
like this:

    10.10.10.10/24
    10.10.20.12/24
    172.50.10.34/24
    192.168.230.10/24

I'm guessing your desired output looks like this:

    - [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]
    - [200, 'sing', 'play',?10.10.10.10/24, ?null, null, 800, 800]
    - [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]
    - [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]
    - [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]
    - [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]
    - [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]
    - [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]

so an increasing counter, and 2 lines per subnet with 500 and 800 end 
values.

>here is my the main block of code.
>
>f = open("output.txt").read().count('\n')

You seem to be counting the number of lines in the file, but never using 
the value "f" afterwards.

>sys.stdout=open('samplefile.txt','a')

This is unusual; it is very uncommon to attach stdout to a different 
file. I presume you want to send the result of "print()" to this file, 
and print writes to stdout by default. I recommend you open a different 
file and use print's "file=" parameter, like this:

    with open('samplefile.txt', 'a') as output:
        ... other code here ...

and use print like this:

    print(....., file=output)

and leave stdout alone.

>with open('output.txt', 'r') as reader:

Just a remark: I would open the "append" file _after_ opening the "read" 
file. That way, if the read fails (bad filename, bad permissions, 
whatever) you never touch the append file at all.

    with open('output.txt', 'r') as reader:
        with open('samplefile.txt', 'a') as output:
            ... other code here ...

>? ? for line in reader.readlines():

Text files are themselves iterable, and return lines, so you can write 
this:

    for line in reader:

but the lines will include the ending newline. So you probably want:

    for line in reader:
        subnet = line.strip()

and to talk about "subnet" from there on.

>? ? ? ? #from __future__ import print_function

Imports from __future__ need to be the first import (and first "code" 
line) in your programme; you can't put them in the middle of the code.  
This is because they affect how Python treats the entire script.

>? ? ? ? with open ('samplefile.txt', 'a') as p:
>? ? ? ? ? ??# allow ingress port 80
>? ? ? ? ? ? print(" ? ? ? ? ? ? ? ? ? ? ? ? ?- [100, 'tcp', 'allow', ",line,?" , null, null, 500, 500]")
>? ? ? ? ? ? print(" ? ? ? ? ? ? ? ? ? ? ? ? ?- [200, 'tcp', 'allow', ",line,"? , null, null, 800, 800]")
>sys.stdout.close()

You won't need the .close either. The "with" form of open does the close 
for you; much cleaner and safer.

>But here is my current output in samplefile.txt:?
>??- [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [200, 'sing', 'play',?10.10.10.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]
[...snip...]

I'll presume these are all on separate lines...

>when I adjust change the print statement to:
>print("?? ? ? ? ? ? ? ? ? ? ? ? ?- [100, 'tcp', 'allow', " +?line +?" , null, null, 500, 500]")
>print("?? ? ? ? ? ? ? ? ? ? ? ? - [200, 'tcp', 'allow', " +?line??+" , null, null, 800, 800]")
>
>
>the print get scattered. something like this:
>?? ? ? ? ??- [100, 'tcp', 'allow', '10.10.10.10/24\n',?', null, null, 500, 500]
>? ? ? ? ??- [200, 'tcp', 'allow', '10.10.10.10/24\n',?', null, null, 800, 800]

As I remarked above, your lines contain the newline characters from the 
original file. Get the subnet string itslf as line.strip() and use 
"subnet" instead.

I also think you're printing repr(line) instead of just line because of 
the quotes and the \n in your output. Just use subnet.

You've also hardwired in the 100 and 200 values. Your target counts up 
by 100 for each output line. Set a counter variable and increment it 
after every line you print, and print the counter instead of the literal 
100 etc.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From alan.gauld at btinternet.com  Tue Oct  1 04:05:53 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Oct 2019 09:05:53 +0100
Subject: [Tutor] print issue
In-Reply-To: <1162792864.1860056.1569899911609@mail.yahoo.com>
References: <1162792864.1860056.1569899911609.ref@mail.yahoo.com>
 <1162792864.1860056.1569899911609@mail.yahoo.com>
Message-ID: <1f63e79f-eb9f-5fac-b5c9-56891cb588cf@btinternet.com>

On 01/10/2019 04:18, ose micah via Tutor wrote:
> here is my the main block of code.
> f = open("output.txt").read().count('\n')
You do a lot of work to find the number of newlines but never use it?
> sys.stdout=open('samplefile.txt','a')
> with open('output.txt', 'r') as reader:
>
> ? ? for line in reader.readlines():

You don't need the readlines() just use


for line in reader:

> ? ? ? ? #from __future__ import print_function

The future line should really be at the top of your code not inside the
loop.

> ? ? ? ? with open ('samplefile.txt', 'a') as p:

You already opened this file. Its a really bad idea to have the
same file opened for output multiple times. You are very likely to
overwrite data. As it is you never seem to use this p reference...

Personally I'd suggest you don;t use the stdout version but
write to p rather than use print statements. But that's really
just a style and convenience thing - you can keep print for
displaying to the console for debugging etc.

> ? ? ? ? ? ? # allow ingress port 80
>
> ? ? ? ? ? ? print(" ? ? ? ? ? ? ? ? ? ? ? ? ?- [100, 'tcp', 'allow', ",line,?" , null, null, 500, 500]")
> ? ? ? ? ? ? print(" ? ? ? ? ? ? ? ? ? ? ? ? ?- [200, 'tcp', 'allow', ",line,"? , null, null, 800, 800]")
>
> sys.stdout.close()
Note that at this point you no longer have a valid stdout so
you can no longer print anything. That's a risky position
in which to put yourself
> But here is my current output in samplefile.txt:?
> ??- [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [200, 'sing', 'play',?10.10.10.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]
The above is presumably what wasalready in samplefile.txt before you
started appending your data.
> (" ? ? ? ? ? - [100, 'tcp', 'allow', ", '10.10.10.10/24\n', ', null, null, 500, 500]')
>  
> (" ? ? ? ? ? - [200, 'tcp', 'allow', ", '10.10.10.10/24\n', ', null, null, 800, 800]')
> (" ? ? ? ? ? - [100, 'tcp', 'allow', ", ' 10.10.20.10/24\n', ' , null, null, 500, 500]')
> (" ? ? ? ? ? - [200, 'tcp', 'allow', ", ' 10.10.20.10/24\n', ', null, null, 800, 800]')
> (" ? ? ? ? ? - [100, 'tcp', 'allow', ", ' 172.50.10.34/24\n', ' , null, null, 500, 500]')
> (" ? ? ? ? ? - [200, 'tcp', 'allow', ", ' 172.50.10.34/24\n', ', null, null, 800, 800]')
> (" ? ? ? ? ? - [100, 'tcp', 'allow', ", ' 192.168.230.10/24\n', ' , null, null, 500, 500]')
> (" ? ? ? ? ? - [200, 'tcp', 'allow', ", ' 192.168.230.10/24\n', ', null, null, 800, 800]')
The above is the data you printed - note the parens are because you are
still using Python 2 style prints because the import future didn't work.?
Python sees your print as being a tuple of strings so that's what it prints.
>
> when I adjust change the print statement to:
> print("?? ? ? ? ? ? ? ? ? ? ? ? ?- [100, 'tcp', 'allow', " +?line +?" , null, null, 500, 500]")
> print("?? ? ? ? ? ? ? ? ? ? ? ? - [200, 'tcp', 'allow', " +?line??+" , null, null, 800, 800]")
>
>
> the print get scattered. something like this:
> ?? ? ? ? ??- [100, 'tcp', 'allow', '10.10.10.10/24\n',?', null, null, 500, 500]
> ? ? ? ? ??- [200, 'tcp', 'allow', '10.10.10.10/24\n',?', null, null, 800, 800]
>
That's almost exactly what you told it to print(with an extra coma?).
I'm not sure what you expected? I'm not sure what you mean by "scattered"?

You don't get parens this time because the string addition means Python
sees a single string inside the parens so does not treat it as a tuple.

> Please, how can I get my desired result.

I'm not clear what your desired result is but I would:


1) Put the import future at the top of the code to make print work

(or better still just use Python v3. Python v2 loses support next year
so you are playing with fire by sticking with it)

2) Stop using print and sys.stdout as your output file and convert
from using print to p.write() instead.(Just remember that you need
to add separators and newlines when using write())

3) Use format strings to control the layout and positioning of
your output, it is more consistent than counting spaces etc

-- 

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


From osaosemwe at yahoo.com  Tue Oct  1 03:38:39 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Tue, 1 Oct 2019 07:38:39 +0000 (UTC)
Subject: [Tutor] Print issue please help
References: <1404117254.1904225.1569915519693.ref@mail.yahoo.com>
Message-ID: <1404117254.1904225.1569915519693@mail.yahoo.com>

Hello please I am trying to make a dynamic print format?
Assuming "output.txt" has contents as? ? ? 10.10.10.10/24? ? ? 10.10.20.12/24? ? ? 172.50.10.34/24? ? ? 192.168.230.10/24and "samplefile.txt"? is an empty file
I am trying to get an output such as in file sample.txt? ? ? ? ? ? ? ?- [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [200, 'sing', 'play',?10.10.10.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]? here is my the main block of code.
f =?open("output.txt").read().count('\n')
sys.stdout=open('samplefile.txt','a')
with?open('output.txt',?'r')?as?reader:

? ??for?line?in?reader.readlines():

? ? ? ??#from __future__ import print_function

? ? ? ??with?open?('samplefile.txt',?'a')?as p:

? ? ? ? ? ??# allow ingress port 80

? ? ? ? ? ??print("?? ? ? ? ? ? ? ? ? ? ? ? ?- [100, 'tcp', 'allow', ",line,?" , null, null, 500, 500]")

? ? ? ? ? ??print("?? ? ? ? ? ? ? ? ? ? ? ? ?- [200, 'tcp', 'allow', ",line,"? , null, null, 800, 800]")





sys.stdout.close()

But here is my current output in samplefile.txt:?
- [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [200, 'sing', 'play',?10.10.10.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]? ? ? ? ? ? ? ?- [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]? ? ? ? ? ? ? ?- [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]



("?? ? ? ? ??- [100, 'tcp', 'allow', ", '10.10.10.10/24\n', ', null, null, 500, 500]')

("?? ? ? ? ??- [200, 'tcp', 'allow', ", '10.10.10.10/24\n', ', null, null, 800, 800]')
("?? ? ? ? ??- [100, 'tcp', 'allow', ", '?10.10.20.10/24\n', ' , null, null, 500, 500]')("?? ? ? ? ??- [200, 'tcp', 'allow', ", '?10.10.20.10/24\n', ', null, null, 800, 800]')("?? ? ? ? ??- [100, 'tcp', 'allow', ", '?172.50.10.34/24\n', ' , null, null, 500, 500]')("?? ? ? ? ??- [200, 'tcp', 'allow', ", '?172.50.10.34/24\n', ', null, null, 800, 800]')("?? ? ? ? ??- [100, 'tcp', 'allow', ", '?192.168.230.10/24\n', ' , null, null, 500, 500]')("?? ? ? ? ??- [200, 'tcp', 'allow', ", '?192.168.230.10/24\n', ', null, null, 800, 800]')

when I adjust change the print statement to:
print("?? ? ? ? ? ? ? ? ? ? ? ? ?- [100, 'tcp', 'allow', " +?line +?" , null, null, 500, 500]")
print("?? ? ? ? ? ? ? ? ? ? ? ??- [200, 'tcp', 'allow', " +?line??+" , null, null, 800, 800]")


the print get scattered. something like this:
?? ? ? ???- [100, 'tcp', 'allow', '10.10.10.10/24\n',?', null, null, 500, 500]
? ? ? ???- [200, 'tcp', 'allow', '10.10.10.10/24\n',?', null, null, 800, 800]


Please, how can I get my desired result.
Can anyone be of help to me.?
Thanks

Mike

From osaosemwe at yahoo.com  Tue Oct  1 09:37:15 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Tue, 1 Oct 2019 13:37:15 +0000 (UTC)
Subject: [Tutor] print issue
In-Reply-To: <20191001080314.GA19311@cskk.homeip.net>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
Message-ID: <673247016.2006902.1569937036192@mail.yahoo.com>

 Thank you for the suggestion. I think its best I attach the code as used from file here.I have print issue with the final print format:What I did is open the file that contains subnets, read each line from this file and make use of each subnet to append a yaml formatted line in the samplefile.txt.?Here is my desired output in the samplefile.txt:?


I pick each subnets from output.txt is:


Here is my current lines of code:?


But here is my current Undesired output which I need changed:


Can anyone help me get my desired output as shown below:



Thanks
Mike

From adamdickenson50252 at gmail.com  Tue Oct  1 18:24:59 2019
From: adamdickenson50252 at gmail.com (Adam Dickenson)
Date: Tue, 1 Oct 2019 18:24:59 -0400
Subject: [Tutor] I need help fast
Message-ID: <CAFubxoUM5SHac6P1sVJbHmtYqdyEO7dkV0Pb19jcQrW6YpZ=Rw@mail.gmail.com>

Hello,

Attached are what I need help on. I cannot get them started and they are
due at 11PM tonight. Can someone help?

Thanks,
Adam J. Dickenson
Tompkins County Fire Department Webmaster
Tompkins County Department of Emergency Response
92 Brown Road, Ithaca NY 14850
<https://maps.google.com/?q=92+Brown+Road,+Ithaca+NY+14850+%0D%0A+%0D%0A+607&entry=gmail&source=g>
607-591-5956 <(607)%20591-5956> - Mobile
607-266-8035 <(607)%20266-8035> - Fax
Note: All Faxes will go to Lauren Dickenson.
adamdickenson50252 at gmail.com
http://tompkinsfireems.org/
-------------- next part --------------

'''
    to run tests on mac: python3 -m doctest car_speed.py -v
    to run tests on Win: python -m doctest car_speed.py -v
'''

def car_speed(distance_of_skid):
    '''
    Calculate the speed in MPH of a car that skidded
    d feet on dry concrete when the brakes were applied

    args:
        distance_of_skid (float): the distance of the skid in feet

    returns:
        an estimate of the speed the car was going when the brakes were applied (float)

    formula:
        speed in MPH equals the square root of (24 * d)

    examples/doctest:

    the car didn't skid at all
    >>> round(car_speed(0), 2)
    0.0

    the car skid 1 foot
    >>> round(car_speed(1), 2)
    4.9

    the car skid 10 feet
    >>> round(car_speed(10), 2)
    15.49

    the car skid 33.33 feet
    >>> round(car_speed(33.33), 2)
    28.28

    the car skid 12345 feet
    >>> round(car_speed(12345), 2)
    544.32

    '''
    # TO DO: Add your code here
    
    return
-------------- next part --------------

'''
    to run tests on mac: python3 -m doctest cost_of_running_lightbulb.py -v
    to run tests on Win: python -m doctest cost_of_running_lightbulb.py -v
'''

def cost_of_running_lightbulb(cents_per_kw_hour, bulb_wattage, hours_on):
    '''
    Calculate the cost of running a lightbulb using the formula
    wattage x hours used divided by 1000 x cost per kWh in cents

    args:
        cents_per_kw_hour (float): the cost in cents per kilowatt hour
        bulb_wattage (float): the wattage of the bulb
        hours_on (float): the number of hours the bulb was on

    returns:
        the cost of running the lighbulb in dollars

    examples/doctests:

    1 penny per kw hour, 60 watt bulb, zero hours on
    >>> round(cost_of_running_lightbulb(1, 60, 0), 2)
    0.0

    $0.10 per kw hour, 100 watt bulb, 1 hour on
    >>> round(cost_of_running_lightbulb(10, 100, 1), 2)
    0.01

    $0.10 per kw hour, 100 watt bulb, 100 hours on
    >>> round(cost_of_running_lightbulb(10, 100, 100), 2)
    1.0

    $0.15 per kw hour, 60 watt bulb, 25 hours on
    >>> round(cost_of_running_lightbulb(15, 60, 25), 2)
    0.1

    $11.76 per kw hour, 127 watt bulb, 56789 hours on
    >>> round(cost_of_running_lightbulb(1176, 127, 56789), 2)
    6.13

    '''
    # TO DO: Add you code here
print(60 * 1 / 1000 * 0.01)
return
-------------- next part --------------
'''
    to run tests on mac: python3 -m doctest triathlon.py -v
    to run tests on Win: python -m doctest triathlon.py -v
'''

def triathlon(hours_cycling, hours_running, hours_swimming):
    '''
    Calculate the number of pounds lost from doing a triathlon
    based on the number of hours spent at each exercise

    given constants:
        200 calories are burned for each 1 hour of cycling
        475 calories are burned for each 1 hour of running
        275 calories are burned for each 1 hour of swimming

        a person looses 1 pound of body weight for each 3500 calories burned

    args:
        hours_cycling (float): the hours spent cycling
        hours_running (float): the hours spent running
        hours_swimming (foat): the hours spent swimming

    returns:
        the number of pounds lost after the triathlon (float)

    examples/doctests:

    no cycling, running, or swimming
    >>> round(triathlon(0, 0, 0), 2)
    0.0

    1 hour cycling, no running or swimming
    >>> round(triathlon(1, 0, 0), 2)
    0.06

    no cycling, 1 hour running, no swimming
    >>> round(triathlon(0, 1, 0), 2)
    0.14

    no cycling, no running, 1 hour swimming
    >>> round(triathlon(0, 0, 1), 2)
    0.08

    5.5 hours cycling, 3.12 hours running, 2.22 hours swimming
    >>> round(triathlon(5.5, 3.12, 2.22), 2)
    0.91

    '''
    # TO DO: Add your code here


    return

From cs at cskk.id.au  Tue Oct  1 18:37:04 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Wed, 2 Oct 2019 08:37:04 +1000
Subject: [Tutor] print issue
In-Reply-To: <673247016.2006902.1569937036192@mail.yahoo.com>
References: <673247016.2006902.1569937036192@mail.yahoo.com>
Message-ID: <20191001223704.GA46408@cskk.homeip.net>

On 01Oct2019 13:37, ose micah <osaosemwe at yahoo.com> wrote:
> Thank you for the suggestion. I think its best I attach the code as used from file here.I have print issue with the final print format:What I did is open the file that contains subnets, read each line from this file and make use of each subnet to append a yaml formatted line in the samplefile.txt.?Here is my desired output in the samplefile.txt:?

Mike,

1: Please DO NOT CC the list owner and bounce addresses. Send to the 
list itself (tutor at python.org).

2: As mentioned earlier, this is a text only list. That means no 
attachments.

Instead, inline your text in the message (as you did originally, but 
with a little more care: blank lines between prose and code/output, and 
indent the code/output).

Your attachments are images. These have various downsides:

- the list software drops them completely; I got to see them only 
  because of the personal copy you sent me.

- we can't cut/paste text from images

- the visually impaired cannot even view them, or have trouble viewing 
  them depending on the degree of impairment; inline text works for 
  everyone

Please reply to this, sending to the list, with inline text.

One thing I omitted from my previous response was:

Write a tiny tiny script containing just the print function with 
hardwired values. Fiddle with that until you get the output you want.  
Then put that version back into your main programme.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From mats at wichmann.us  Tue Oct  1 18:39:53 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 1 Oct 2019 16:39:53 -0600
Subject: [Tutor] I need help fast
In-Reply-To: <CAFubxoUM5SHac6P1sVJbHmtYqdyEO7dkV0Pb19jcQrW6YpZ=Rw@mail.gmail.com>
References: <CAFubxoUM5SHac6P1sVJbHmtYqdyEO7dkV0Pb19jcQrW6YpZ=Rw@mail.gmail.com>
Message-ID: <a6384176-16b9-6785-8cca-5e213b84de9b@wichmann.us>

On 10/1/19 4:24 PM, Adam Dickenson wrote:
> Hello,
> 
> Attached are what I need help on. I cannot get them started and they are
> due at 11PM tonight. Can someone help?

No.  The mailing list does not preserve attachments, so nobody saw them.

It's far better to describe the problem, and what you've tried.  Often 
the act of explaining a problem to someone else (even a "faceless" 
malining list!) will help bring you some clarity anyway, so it's rarely 
wasted effort.




From mats at wichmann.us  Tue Oct  1 18:43:19 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 1 Oct 2019 16:43:19 -0600
Subject: [Tutor] I need help fast
In-Reply-To: <a6384176-16b9-6785-8cca-5e213b84de9b@wichmann.us>
References: <CAFubxoUM5SHac6P1sVJbHmtYqdyEO7dkV0Pb19jcQrW6YpZ=Rw@mail.gmail.com>
 <a6384176-16b9-6785-8cca-5e213b84de9b@wichmann.us>
Message-ID: <c39e0a67-1ae8-a59b-a290-e0cc4eca9b4e@wichmann.us>

On 10/1/19 4:39 PM, Mats Wichmann wrote:
> On 10/1/19 4:24 PM, Adam Dickenson wrote:
>> Hello,
>>
>> Attached are what I need help on. I cannot get them started and they are
>> due at 11PM tonight. Can someone help?
> 
> No.? The mailing list does not preserve attachments, so nobody saw them.


Hmmm, looks like these came through, although they didn't land here - I 
can see there are three files if I look elsewhere. So ignore that 
comment (usually they are indeed dropped).

From cs at cskk.id.au  Tue Oct  1 19:26:48 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Wed, 2 Oct 2019 09:26:48 +1000
Subject: [Tutor] I need help fast
In-Reply-To: <CAFubxoUM5SHac6P1sVJbHmtYqdyEO7dkV0Pb19jcQrW6YpZ=Rw@mail.gmail.com>
References: <CAFubxoUM5SHac6P1sVJbHmtYqdyEO7dkV0Pb19jcQrW6YpZ=Rw@mail.gmail.com>
Message-ID: <20191001232648.GA24767@cskk.homeip.net>

On 01Oct2019 18:24, Adam Dickenson <adamdickenson50252 at gmail.com> wrote:
>Attached are what I need help on.

This is a text only list. Attachments should be dropped. (They seem to 
have come through, so you're lucky, but we _strongly_ prefer inline 
code).

>I cannot get them started and they are
>due at 11PM tonight. Can someone help?

We don't know when 11PM is for you. You'll just have to hope you're 
lucky with who is looking at the list in your time window.

I'm going to assume "cannot get them started" means you don't know where 
to begin implementing the code, not "I cannot invoke Python".

So, let's look at these scripts. Comments below the script (we use the 
inline style in this list: replies below the relevant quote from the 
preceeding message, ideally trimming excess quoteed stuff to just the 
necessary stuff needed for context; like a conversation in a novel).

>'''
>    to run tests on mac: python3 -m doctest car_speed.py -v
>    to run tests on Win: python -m doctest car_speed.py -v
>'''
>
>def car_speed(distance_of_skid):
>    '''
>    Calculate the speed in MPH of a car that skidded
>    d feet on dry concrete when the brakes were applied
>
>    args:
>        distance_of_skid (float): the distance of the skid in feet
>
>    returns:
>        an estimate of the speed the car was going when the brakes were applied (float)
>
>    formula:
>        speed in MPH equals the square root of (24 * d)
>
>    examples/doctest:
>
>    the car didn't skid at all
>    >>> round(car_speed(0), 2)
>    0.0
>
>    the car skid 1 foot
>    >>> round(car_speed(1), 2)
>    4.9
>
>    the car skid 10 feet
>    >>> round(car_speed(10), 2)
>    15.49
>
>    the car skid 33.33 feet
>    >>> round(car_speed(33.33), 2)
>    28.28
>
>    the car skid 12345 feet
>    >>> round(car_speed(12345), 2)
>    544.32
>
>    '''
>    # TO DO: Add your code here
>
>    return

So, you need to write code to implement this calculation in Python and 
return the result. So the "return" line needs to read "return 
inferred_speed", and we'll define an "inferred_speed" variable. Which we 
need to compute.

Fortunately the docstring above provides the formula they want you to 
use: "speed in MPH equals the square root of (24 * d)". Which saves me 
having to look up arcane stuff like how many feet make a mile, etc, 
living as I do in the SI world (kilometres, metres, etc).

So: you have the distance supplied to you: it is the function parameter 
"distance_of_skid" at the top of the function; they want to use this in 
the formula as "d".

You do need a square root function, but Python ships with one in its 
"math" module. It is described here:

    https://docs.python.org/3/library/math.html#math.sqrt

To access it put this at the start of your Python script:

    from math import sqrt

So now you could write:

    inferred_speed = sqrt(24 * distance_of_skid)

to implement that formula.

Leaving out the docstring, your whole programme would look like this 
(totally untested):

    from math import sqrt

    def car_speed(distance_of_skid):
        inferred_speed = sqrt(24 * distance_of_skid)
        return inferred_speed

You should be able to approach the other questions in a similar manner.

Note that while I dropped the docstring in the above text for clarity, 
you do want it in your actual script because their instructions for 
testing the script look like this:

    to run tests on mac: python3 -m doctest car_speed.py -v
    to run tests on Win: python -m doctest car_speed.py -v

That invokes Python's "doctest" module against your script, which finds 
special parts of the function's docstring such as this:

    >>> round(car_speed(1), 2)
    4.9

and recognises them as tests (because they look like Python's 
interactive prompt). So doctest will run:

    round(car_speed(1), 2)

and compares the result against "4.9", which is what should come from 
your function (after the rounding). This will let you easily test your 
programme against the assortment of examples in the docstring.

Finally: DO NOT forget the indenting. It is critical in Python and 
indicates what pieces of code are part of some structure. So:

    def car_speed(distance_of_skid):
        inferred_speed = sqrt(24 * distance_of_skid)
        return inferred_speed

defines a larger structure (the "car_speed" function) and the two lines:

        inferred_speed = sqrt(24 * distance_of_skid)
        return inferred_speed

are part of that function _because_ they are indented underneath it.

Have a go at the other functions and see how they go.

You can return to this list (by replying to my message), but do so 
_with_ your attempts and an explaination of what's wrong with them. We 
don't do homework, but we will assist with understanding.

Ah, I see you've made an attempt at the cost_of_running_lightbulb 
function. Ok:

>def cost_of_running_lightbulb(cents_per_kw_hour, bulb_wattage, hours_on):
>    '''
>    Calculate the cost of running a lightbulb using the formula
>    wattage x hours used divided by 1000 x cost per kWh in cents
>
>    args:
>        cents_per_kw_hour (float): the cost in cents per kilowatt hour
>        bulb_wattage (float): the wattage of the bulb
>        hours_on (float): the number of hours the bulb was on
>
>    returns:
>        the cost of running the lighbulb in dollars
[...]
>    # TO DO: Add you code here
>print(60 * 1 / 1000 * 0.01)
>return

The first thing to notice here is that your code is not indented. Indent 
it the same as the comment "# TODO..." to make the code part of the 
function.

The next thing is: 60 * 1 / 1000 * 0.01 is a constant expression: it 
will always produce the same answer. You need to replace various terms 
in that expression with the parameters from the function header: 
cents_per_kw_hour, bulb_wattage, hours_on. Also, you can drop the "* 1", 
multiplying by 1 changes nothing, so you can simplify things.

They're provided the formula: write it out in Python using those 
parameters.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From cs at cskk.id.au  Tue Oct  1 19:37:39 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Wed, 2 Oct 2019 09:37:39 +1000
Subject: [Tutor] NumPy Generates ValueError: Some errors were detected !
 Line #9 (got 42 columns instead of 1)
In-Reply-To: <CAMPXz=pQ-F1cbHh_=4V9WgCCC0hLdeKV-AmD6v_Md9KPOMbs7w@mail.gmail.com>
References: <CAMPXz=pQ-F1cbHh_=4V9WgCCC0hLdeKV-AmD6v_Md9KPOMbs7w@mail.gmail.com>
Message-ID: <20191001233739.GA12787@cskk.homeip.net>

On 29Sep2019 10:44, David <bouncingcats at gmail.com> wrote:
>On Sun, 29 Sep 2019 at 02:36, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
>> Thank you for your reply. There are, in fact, hidden characters in 
>> the input file (cat -A ...):
>>
>> > ^IRMSD TABLE$
>> > ^I__________$
>> > $
>> > _____________________________________________________________________$
>> >      |      |      |           |         |                 |$
>> > Rank | Sub- | Run  | Binding   | Cluster | Reference       | Grep$
>> >      | Rank |      | Energy    | RMSD    | RMSD            | Pattern$
>> > _____|______|______|___________|_________|_________________|___________$
>> >    1      1      8       -7.23      0.00     93.07 RANKING$
>> >    1      2      9       -6.79      1.39     92.64 RANKING$
>> >    2      1     16       -7.18      0.00     93.19 RANKING$
[...]
>Depending on the problem you are having, it can be helpful
>to check for non-visible characters that might upset your
>parser, so thanks for letting us know that you did this 'cat -A'.
>
>But I wonder why you say "There are, in fact, hidden characters in the
>input file".
>
>Are you aware that '^I' is how 'cat -A' represents a tab
>character, and that '$' is how it represents a newline character?

Well, "end of line". But I'm being overly picky.

>I don't think either of these will cause you any trouble in
>this case. And I don't see any other hidden characters.

Except that there is indeed whitespace in his display above, and it 
isn't TAB characters. I suspect some weirdness with his initial 
cut/paste.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From alan.gauld at btinternet.com  Wed Oct  2 04:58:20 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Oct 2019 09:58:20 +0100
Subject: [Tutor] I need help fast
In-Reply-To: <20191001232648.GA24767@cskk.homeip.net>
References: <CAFubxoUM5SHac6P1sVJbHmtYqdyEO7dkV0Pb19jcQrW6YpZ=Rw@mail.gmail.com>
 <20191001232648.GA24767@cskk.homeip.net>
Message-ID: <f4badbf7-ff62-3a16-3e61-39ffd657af95@btinternet.com>

On 02/10/2019 00:26, Cameron Simpson wrote:
> This is a text only list. Attachments should be dropped. (They seem to 

It lets text only attachments through (usually!)

These were all python code so made it. But HTML usually gets dropped
(for fear of embedded Javascript code, presumably).

The rules are all a bit arcane so we recommend not using attachments.

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


From alan.gauld at btinternet.com  Wed Oct  2 12:38:58 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Oct 2019 17:38:58 +0100
Subject: [Tutor] print issue
In-Reply-To: <1461408383.2614096.1570030235654@mail.yahoo.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
Message-ID: <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>

On 02/10/2019 16:30, ose micah wrote:
>
>
> Thank you for the suggestion. I hope the format below is OK?


Seems Ok to me.

> ?
> ? ? ????????????- [100, 'sing', 'play',?10.10.10.10/24,??null, null,
> 500, 500]
> ? ????????????? - [200, 'sing', 'play',?10.10.10.10/24, ?null, null,
> 800, 800]
> ????????????? ? - [300, 'sing', 'play',?10.10.20.10/24,??null, null,
> 500, 500]
> ? ????????????? - [400, 'sing', 'play',?10.10.20.10/24,??null, null,
> 800, 800]


Notice you increment the first entry here but in your code you always
use 100/200.

You need to create a variable and increment it by 100 each time.

???????????
>
> I pick each subnets from "output.txt" is:
> ??
> ? ? ? 10.10.10.10/24
> ? ? ? 10.10.20.12/24
> ? ? ? 172.50.10.34/24
> ? ? ? 192.168.230.10/24
>
> Here is my current line of code which need modification:
> ? ? ??

We have already given you several suggestions, I will incorporate them
below: I will assume that for some reason you need to use Python v2...
with open('output.txt', 'r') as reader: counter = 100 fmtString = "%11s-
[%d, 'tcp', 'allow', %s, null, null, %d, %d]\n" for line in reader:
address = line.strip() with open ('samplefile.txt', 'w') as p:
p.write(fmtString % (" ", counter, address, 500,500)) counter +=100
p.write(fmtString % (" ", counter, address, 800,800)) counter += 100
Note that I changed the file mode to 'w' to create a new file each time
rather than keep appending since it seems likely that is what you really
want. If I'm mistaken change it back to 'a'... The code is untested so
may need tweaking but should be close.

-- 

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


From alan.gauld at btinternet.com  Wed Oct  2 13:49:10 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Oct 2019 18:49:10 +0100
Subject: [Tutor] print issue
In-Reply-To: <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
Message-ID: <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>

On 02/10/2019 17:38, Alan Gauld via Tutor wrote:
>
> We have already given you several suggestions, I will incorporate them
> below: I will assume that for some reason you need to use Python v2...

Not sure why the formatting got messed up, I'll try again!

with open('output.txt', 'r') as reader: counter = 100 fmtString =
"%11s-[%d, 'tcp', 'allow', %s, null, null, %d, %d]\n" with open
('samplefile.txt', 'w') as p: for line in reader: address = line.strip()
p.write(fmtString % (" ", counter, address, 500,500)) counter +=100
p.write(fmtString % (" ", counter, address, 800,800)) counter +=100

I cheated slightly and moved the second 'open()' line up a bit too... :-)

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


From mats at wichmann.us  Wed Oct  2 13:57:10 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 2 Oct 2019 11:57:10 -0600
Subject: [Tutor] print issue
In-Reply-To: <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>
Message-ID: <03cfcc2b-7587-2e76-4991-f93193ff435d@wichmann.us>

On 10/2/19 11:49 AM, Alan Gauld via Tutor wrote:
> On 02/10/2019 17:38, Alan Gauld via Tutor wrote:
>>
>> We have already given you several suggestions, I will incorporate them
>> below: I will assume that for some reason you need to use Python v2...
> 
> Not sure why the formatting got messed up, I'll try again!
> 
> with open('output.txt', 'r') as reader: counter = 100 fmtString =
> "%11s-[%d, 'tcp', 'allow', %s, null, null, %d, %d]\n" with open
> ('samplefile.txt', 'w') as p: for line in reader: address = line.strip()
> p.write(fmtString % (" ", counter, address, 500,500)) counter +=100
> p.write(fmtString % (" ", counter, address, 800,800)) counter +=100
> 
> I cheated slightly and moved the second 'open()' line up a bit too... :-)
> 

also note - there was a mention somewhere of seeking yaml-style output.

there is a yaml module which can help with the emitting part without 
having to worry about the formatting yourself (actually, to be honest, 
there are actually *many* yaml modules.  pyyaml is, I believe, the most 
popular - at least it's the one used by some very popular Python 
packages like django, docker compose, the kubernetes Python client, etc)





From alan.gauld at btinternet.com  Wed Oct  2 14:03:41 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Oct 2019 19:03:41 +0100
Subject: [Tutor] print issue
In-Reply-To: <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>
Message-ID: <03d52771-1759-521a-c7a1-23b1a51f70b9@btinternet.com>

On 02/10/2019 18:49, Alan Gauld via Tutor wrote:
> On 02/10/2019 17:38, Alan Gauld via Tutor wrote:
>> We have already given you several suggestions, I will incorporate them
>> below: I will assume that for some reason you need to use Python v2...
> Not sure why the formatting got messed up, I'll try again!
>
> with open('output.txt', 'r') as reader: counter = 100 fmtString =
> "%11s-[%d, 'tcp', 'allow', %s, null, null, %d, %d]\n" with open

OK, Something must be screwed up in my settings.
I'll try again once I figure out what's messed up..


-- 

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


From alan.gauld at btinternet.com  Wed Oct  2 18:38:33 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Oct 2019 23:38:33 +0100
Subject: [Tutor] print issue
In-Reply-To: <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>
Message-ID: <111e4f58-b72a-ea11-15f2-6cf79f2b261f@btinternet.com>

On 02/10/2019 18:49, Alan Gauld via Tutor wrote:

> Not sure why the formatting got messed up, I'll try again!

And again...

with open('output.txt', 'r') as reader:     counter = 100
    fmtString ="%11s-[%d, 'tcp', 'allow', %s, null, null, %d, %d]\n"
    with open('samplefile.txt', 'w') as p:
        for line in reader:
            address = line.strip()
            p.write(fmtString % (" ", counter, address, 500,500))
            counter +=100
            p.write(fmtString % (" ", counter, address, 800,800))
            counter +=100


Hopefully this comes through OK...


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


From osaosemwe at yahoo.com  Wed Oct  2 11:30:35 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Wed, 2 Oct 2019 15:30:35 +0000 (UTC)
Subject: [Tutor] print issue
In-Reply-To: <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
Message-ID: <1461408383.2614096.1570030235654@mail.yahoo.com>



Thank you for the suggestion. I hope the format below is OK?
Please have a look at this issue, I need solving.?


>From the opened file "output.txt" that contains subnets each of which I need in creating a rule, I wrote a program that read each line from this file and make use of each subnet to append a yaml formatted line in the samplefile.txt.?
Here is my desired output in the "samplefile.txt":

?
? ? ????????????- [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]
? ????????????? - [200, 'sing', 'play',?10.10.10.10/24, ?null, null, 800, 800]
????????????? ? - [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]
? ????????????? - [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]
????????????? ? - [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]
? ????????????? - [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]
? ????????????? - [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]
? ????????????? - [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]
????????????

I pick each subnets from "output.txt" is:
??
? ? ? 10.10.10.10/24
? ? ? 10.10.20.12/24
? ? ? 172.50.10.34/24
? ? ? 192.168.230.10/24

Here is my current line of code which need modification:
? ? ??
? ? ??

? f = open("output.txt").read().count('\n')? # file that contains subnets
? sys.stdout=open('samplefile.txt','a') .? ? #where I want the configured subnets dumped
? with open('output.txt', 'r') as reader:??
? ? for line in reader.readlines():
? ? ? ? with open ('samplefile.txt', 'a') as p:
? ? ? ? ? ? # allow ip to play port 500
? ? ? ? ? ? print(" ? ? ? ? ? - [100, 'tcp', 'allow', ", line, ", null, null, 500, 500]")
?? ? ? ? ? # allow ip to sing port 800
? ? ? ? ? ? print(" ? ? ? ? ? - [200, 'tcp', 'allow', ", line, " , null, null, 800, 800]")

Here is my current output in the "samplefile.txt"- Which is undesired
? ?(" ? ? ? ? ? - [100, 'tcp', 'allow', ", '10.10.10.10/24\n', ', null, null, 500, 500]')? ?(" ? ? ? ? ? - [200, 'tcp', 'sing', ", '10.10.10.10/24\n', ', null, null, 800, 800]')? ?(" ? ? ? ? ? - [100, 'tcp', 'allow', ", ' 10.10.20.10/24\n', ' , null, null, 500, 500]')? ?(" ? ? ? ? ? - [200, 'tcp', 'allow', ", ' 10.10.20.10/24\n', ', null, null, 800, 800]')? ?(" ? ? ? ? ? - [100, 'tcp', 'allow', ", ' 172.50.10.34/24\n', ' , null, null, 500, 500]')? ?(" ? ? ? ? ? - [200, 'tcp', 'allow', ", ' 172.50.10.34/24\n', ', null, null, 800, 800]')? ?(" ? ? ? ? ? - [100, 'tcp', 'allow', ", ' 192.168.230.10/24\n', ' , null, null, 500, 500]')? ?(" ? ? ? ? ? - [200, 'tcp', 'allow', ", ' 192.168.230.10/24\n', ', null, null, 800, 800]')


Please how can I change my code to get my desired output as:??? ?? ? ? ?????????????????- [100, 'sing', 'play',?10.10.10.10/24,??null, null, 500, 500]
? ????????????? - [200, 'sing', 'play',?10.10.10.10/24, ?null, null, 800, 800]
????????????? ? - [300, 'sing', 'play',?10.10.20.10/24,??null, null, 500, 500]
? ????????????? - [400, 'sing', 'play',?10.10.20.10/24,??null, null, 800, 800]
????????????? ? - [500, 'sing', 'play',?172.50.10.34/24,??null, null, 500, 500]
? ????????????? - [600, 'sing', 'play',?172.50.10.34/24,??null, null, 800, 800]
? ????????????? - [700, 'sing', 'play',?192.168.230.10/24,??null, null, 500, 500]
? ????????????? - [800, 'sing', 'play',?192.168.230.10/24,??null, null, 800, 800]
? ? ? ? ? ??

Thanks
Mike.

On Tuesday, October 1, 2019, 12:50:32 PM EDT, Alan Gauld <alan.gauld at btinternet.com> wrote: 



> Thank you for the suggestion. I think its best I attach the code



The Python Tutor mailing list, in common with most technical lists,
is a text only service. As such non text attachments are usually stripped
out by the server for security reasons. You are best either posting code
inline within the message (if less than, say 100 lines) or on a pastebin
and sending a link.

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



From osaosemwe at yahoo.com  Wed Oct  2 14:43:47 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Wed, 2 Oct 2019 18:43:47 +0000 (UTC)
Subject: [Tutor] print issue
In-Reply-To: <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
Message-ID: <182617636.2758926.1570041827090@mail.yahoo.com>

 
Hello Alan,?Thank you A lot. You are a time saver. it works better with "a" as the function or a is to append. "w" overwrites the previous line.?
The line of codes works good.?
Thanks
Ose Micah.?

    On Wednesday, October 2, 2019, 12:39:00 PM EDT, Alan Gauld <alan.gauld at btinternet.com> wrote:  
 
 On 02/10/2019 16:30, ose micah wrote:
>
>
> Thank you for the suggestion. I hope the format below is OK?


Seems Ok to me.

> ?
> ? ? ????????????- [100, 'sing', 'play',?10.10.10.10/24,??null, null,
> 500, 500]
> ? ????????????? - [200, 'sing', 'play',?10.10.10.10/24, ?null, null,
> 800, 800]
> ????????????? ? - [300, 'sing', 'play',?10.10.20.10/24,??null, null,
> 500, 500]
> ? ????????????? - [400, 'sing', 'play',?10.10.20.10/24,??null, null,
> 800, 800]


Notice you increment the first entry here but in your code you always
use 100/200.

You need to create a variable and increment it by 100 each time.

???????????
>
> I pick each subnets from "output.txt" is:
> ??
> ? ? ? 10.10.10.10/24
> ? ? ? 10.10.20.12/24
> ? ? ? 172.50.10.34/24
> ? ? ? 192.168.230.10/24
>
> Here is my current line of code which need modification:
> ? ? ??

We have already given you several suggestions, I will incorporate them
below: I will assume that for some reason you need to use Python v2...
with open('output.txt', 'r') as reader: counter = 100 fmtString = "%11s-
[%d, 'tcp', 'allow', %s, null, null, %d, %d]\n" for line in reader:
address = line.strip() with open ('samplefile.txt', 'w') as p:
p.write(fmtString % (" ", counter, address, 500,500)) counter +=100
p.write(fmtString % (" ", counter, address, 800,800)) counter += 100
Note that I changed the file mode to 'w' to create a new file each time
rather than keep appending since it seems likely that is what you really
want. If I'm mistaken change it back to 'a'... The code is untested so
may need tweaking but should be close.

-- 

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

  

From rgrant at posteo.net  Wed Oct  2 11:37:58 2019
From: rgrant at posteo.net (Ricardo Grant)
Date: Wed, 2 Oct 2019 11:37:58 -0400
Subject: [Tutor] Run Time Analysis With Python
Message-ID: <0612e76f-17a0-3bac-3eac-da934d8a866e@posteo.net>

I am trying to learn more about performance analysis using python. I 
made a small script to extract titles and uri's from Firefox's bookmark 
JSON dump. Here is the script:

#!/usr/bin/python3

import json

bookmarks = json.load(open('/home/ricardo/bookmarks-2019-08-20.json'))

def descend(dict):
     if 'children' in dict:
         for child in dict['children']:
             if 'uri' in child:
                 print('{} {}'.format(child['title'], child['uri']))
             else:
                 descend(child)

and the profiling information

          103 function calls (92 primitive calls) in 0.000 seconds

    Ordered by: standard name

    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
         1    0.000    0.000    0.000    0.000 <string>:1(<module>)
      12/1    0.000    0.000    0.000    0.000 bookmarks.py:8(descend)
         1    0.000    0.000    0.000    0.000 {built-in method 
builtins.exec}
        44    0.000    0.000    0.000    0.000 {built-in method 
builtins.print}
         1    0.000    0.000    0.000    0.000 {method 'disable' of 
'_lsprof.Profiler' objects}
        44    0.000    0.000    0.000    0.000 {method 'format' of 'str' 
objects}

Due to it's recursive nature and my limited understanding of big O 
analysis, I can't really find the steps to define a function that 
describes the performance of this script. I would appreciate some hints 
or even an explanation. Can you explain the profiling information as well?

I am also curious about my implementation. Does this code suffice, or is 
there other ways to recurse into dictionaries?

From alan.gauld at btinternet.com  Wed Oct  2 18:51:29 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Oct 2019 23:51:29 +0100
Subject: [Tutor] print issue
In-Reply-To: <111e4f58-b72a-ea11-15f2-6cf79f2b261f@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <2b9fb773-9b33-364c-7eeb-617103e1e258@btinternet.com>
 <111e4f58-b72a-ea11-15f2-6cf79f2b261f@btinternet.com>
Message-ID: <1137c3fd-5062-a7fb-f870-6f8b9a0121bc@btinternet.com>

On 02/10/2019 23:38, Alan Gauld via Tutor wrote:

Almost...

with open('output.txt', 'r') as reader:
      counter = 100
      fmtString ="%11s-[%d, 'tcp', 'allow', %s, null, null, %d, %d]\n"
      with open('samplefile.txt', 'w') as p:
         for line in reader:
             address = line.strip()
             p.write(fmtString % (" ", counter, address, 500,500))
             counter +=100
             p.write(fmtString % (" ", counter, address, 800,800))
             counter +=100

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


From mats at wichmann.us  Wed Oct  2 22:21:47 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 2 Oct 2019 20:21:47 -0600
Subject: [Tutor] Run Time Analysis With Python
In-Reply-To: <0612e76f-17a0-3bac-3eac-da934d8a866e@posteo.net>
References: <0612e76f-17a0-3bac-3eac-da934d8a866e@posteo.net>
Message-ID: <0ab811c6-00f1-04c6-3a0a-836d36234196@wichmann.us>

On 10/2/19 9:37 AM, Ricardo Grant wrote:
> I am trying to learn more about performance analysis using python. I 
> made a small script to extract titles and uri's from Firefox's bookmark 
> JSON dump. Here is the script:
> 
> #!/usr/bin/python3
> 
> import json
> 
> bookmarks = json.load(open('/home/ricardo/bookmarks-2019-08-20.json'))
> 
> def descend(dict):
>  ??? if 'children' in dict:
>  ??????? for child in dict['children']:
>  ??????????? if 'uri' in child:
>  ??????????????? print('{} {}'.format(child['title'], child['uri']))
>  ??????????? else:
>  ??????????????? descend(child)
> 
> and the profiling information
> 
>  ???????? 103 function calls (92 primitive calls) in 0.000 seconds
> 
>  ?? Ordered by: standard name
> 
>  ?? ncalls? tottime? percall? cumtime? percall filename:lineno(function)
>  ??????? 1??? 0.000??? 0.000??? 0.000??? 0.000 <string>:1(<module>)
>  ???? 12/1??? 0.000??? 0.000??? 0.000??? 0.000 bookmarks.py:8(descend)
>  ??????? 1??? 0.000??? 0.000??? 0.000??? 0.000 {built-in method 
> builtins.exec}
>  ?????? 44??? 0.000??? 0.000??? 0.000??? 0.000 {built-in method 
> builtins.print}
>  ??????? 1??? 0.000??? 0.000??? 0.000??? 0.000 {method 'disable' of 
> '_lsprof.Profiler' objects}
>  ?????? 44??? 0.000??? 0.000??? 0.000??? 0.000 {method 'format' of 'str' 
> objects}
> 
> Due to it's recursive nature and my limited understanding of big O 
> analysis, I can't really find the steps to define a function that 
> describes the performance of this script. I would appreciate some hints 
> or even an explanation. Can you explain the profiling information as well?

what's to describe?  as a result of running this (and note you have not 
sent us a complete program) the builtins print and format have been 
called 44 times. probably that's right, but you could have gleaned the 
same information by counting keys in bookmarks. exciting.

what are you trying to determing from your analysis? how are you calling 
the profiling?

> I am also curious about my implementation. Does this code suffice, or is 
> there other ways to recurse into dictionaries?

there's a joke cartoon making the rounds of the internet just now which 
describes how when computer science students are about to graduate with 
an advanced degree they're taken into a dark room and told to never ever 
use recursion again, it was only a trick to torment them during their 
learning (I'm paraphrasing, but that's the gist).  you are recursing. 
are you sure you need to?  while it has its uses, iteration is usually a 
sufficient (and better) way to walk through a collection like a dictionary.

This is not meant to be critical, just some questions...


From alan.gauld at btinternet.com  Wed Oct  2 19:45:03 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Oct 2019 00:45:03 +0100
Subject: [Tutor] Run Time Analysis With Python
In-Reply-To: <0612e76f-17a0-3bac-3eac-da934d8a866e@posteo.net>
References: <0612e76f-17a0-3bac-3eac-da934d8a866e@posteo.net>
Message-ID: <a28f8479-5a5a-56fd-1037-9f0b3b3663d7@btinternet.com>

On 02/10/2019 16:37, Ricardo Grant wrote:

> bookmarks = json.load(open('/home/ricardo/bookmarks-2019-08-20.json'))
> 
> def descend(dict):
>      if 'children' in dict:
>          for child in dict['children']:
>              if 'uri' in child:
>                  print('{} {}'.format(child['title'], child['uri']))
>              else:
>                  descend(child)
> 
> and the profiling information
> 
>           103 function calls (92 primitive calls) in 0.000 seconds
> 
>     Ordered by: standard name
> 
>     ncalls  tottime  percall  cumtime  percall filename:lineno(function)
>          1    0.000    0.000    0.000    0.000 <string>:1(<module>)
>       12/1    0.000    0.000    0.000    0.000 bookmarks.py:8(descend)

> Due to it's recursive nature and my limited understanding of big O 
> analysis, I can't really find the steps to define a function that 
> describes the performance of this script. 

I'm not sure what you mean by that last statement.
The biggest problem in reading the profile data is that your script
is too fast for any of the timings to be meaningful. There may
be options you can use to control granularity - its years since
I used the optimiser!

> I am also curious about my implementation. Does this code suffice, or is 
> there other ways to recurse into dictionaries?
You don't ever need the recursion, although it is the cleanest
and simplest technique if you can be sure you won;t break the
recursion limit. You can always use a loop although its often
a lot messier.


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


From __peter__ at web.de  Thu Oct  3 03:48:18 2019
From: __peter__ at web.de (Peter Otten)
Date: Thu, 03 Oct 2019 09:48:18 +0200
Subject: [Tutor] [OT] Tutor no longer mirrored to Gmane?
Message-ID: <qn4942$3tup$1@blaine.gmane.org>

It looks like no messages appear in the gmane pseudo-newsgroup.
Is this something that can be fixed?


From david at lowryduda.com  Thu Oct  3 08:57:00 2019
From: david at lowryduda.com (David Lowry-Duda)
Date: Thu, 3 Oct 2019 08:57:00 -0400
Subject: [Tutor] [OT] Tutor no longer mirrored to Gmane?
In-Reply-To: <qn4942$3tup$1@blaine.gmane.org>
References: <qn4942$3tup$1@blaine.gmane.org>
Message-ID: <20191003125700.GA3261@icerm-dld>

Interesting. It has been my impression that gmane stopped archiving in 
2016.

> It looks like no messages appear in the gmane pseudo-newsgroup.

Are you suggesting that messages stopped appearing *recently*, or are 
you asking more broadly about archives? The tutor list is archived at

https://mail.python.org/pipermail/tutor/

- DLD

From mats at wichmann.us  Thu Oct  3 09:33:17 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Thu, 3 Oct 2019 07:33:17 -0600
Subject: [Tutor] [OT] Tutor no longer mirrored to Gmane?
In-Reply-To: <20191003125700.GA3261@icerm-dld>
References: <qn4942$3tup$1@blaine.gmane.org> <20191003125700.GA3261@icerm-dld>
Message-ID: <04154e00-5fb2-bd4a-dae1-43b71fe434a1@wichmann.us>

On 10/3/19 6:57 AM, David Lowry-Duda wrote:
> Interesting. It has been my impression that gmane stopped archiving in
> 2016.
> 
>> It looks like no messages appear in the gmane pseudo-newsgroup.
> 
> Are you suggesting that messages stopped appearing *recently*, or are
> you asking more broadly about archives? The tutor list is archived at
> 
> https://mail.python.org/pipermail/tutor/

at least the two external locations listed in the listinfo page have 
stopped collecting, possibly a result of the bulk 
unsubscribe/resubscribe event(s) that took place a while back.

gmane itself went through all kinds of problems and I hadn't heard that 
it was even working in its new state.

From alan.gauld at btinternet.com  Thu Oct  3 09:57:01 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Oct 2019 14:57:01 +0100
Subject: [Tutor] [OT] Tutor no longer mirrored to Gmane?
In-Reply-To: <20191003125700.GA3261@icerm-dld>
References: <qn4942$3tup$1@blaine.gmane.org> <20191003125700.GA3261@icerm-dld>
Message-ID: <3f6cc498-f195-7efa-5b91-cb2d5ce08a34@btinternet.com>

On 03/10/2019 13:57, David Lowry-Duda wrote:
> Interesting. It has been my impression that gmane stopped archiving in 
> 2016.

It stopped being maintained but those archives that still existed
continued working. Unfortunately the mass unsubscription has
effectively removed Python tutor from that list of services!


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


From alan.gauld at btinternet.com  Thu Oct  3 04:29:14 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Oct 2019 09:29:14 +0100
Subject: [Tutor] [OT] Tutor no longer mirrored to Gmane?
In-Reply-To: <qn4942$3tup$1@blaine.gmane.org>
References: <qn4942$3tup$1@blaine.gmane.org>
Message-ID: <e41b458b-0b6a-4ef8-6819-ce372ee0244d@btinternet.com>

On 03/10/2019 08:48, Peter Otten wrote:
> It looks like no messages appear in the gmane pseudo-newsgroup.
> Is this something that can be fixed?

I don't think so. When  everyone on the list was unsubscribed
that included the gmane list. But gmane is no longer maintained
so there is nobody to contact to get it resubscribed. At least
nobody that I could find. If anyone else knows who to contact
then let me know and I'll see what can be done.

I used gmane as my main feed and miss it!


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


From osaosemwe at yahoo.com  Thu Oct  3 17:02:54 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Thu, 3 Oct 2019 21:02:54 +0000 (UTC)
Subject: [Tutor] print issue
In-Reply-To: <5d04817d-f84c-09fe-2373-3b5a54eeb413@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <182617636.2758926.1570041827090@mail.yahoo.com>
 <5d04817d-f84c-09fe-2373-3b5a54eeb413@btinternet.com>
Message-ID: <608230864.3396203.1570136574576@mail.yahoo.com>

 Hello Alan,?
I am here again. I checked the code it pans out, w will write over the previous code while a will append new lines... well it depends on the final usage.
I am trying to copy only subnets from a website to the screen
 #!/usr/bin/env pythonimport requestsimport sysimport fileinput
ip_ranges = requests.get('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips').json()cloudfront_ips = [item['ip_prefix'] for item in ip_ranges if item == "CLOUDFRONT_GLOBAL_IP_LIST"]ec2_ips = [item['ip_prefix'] for item in ip_ranges if item == "CLOUDFRONT_REGIONAL_EDGE_IP_LIST"]
cloudfront_ips_more_edge=[]
for ip in cloudfront_ips:? ? if ip not in ec2_ips:? ? ? ? cloudfront_ips_more_edge.append(ip)
for ip in ec2_ips:? ? if ip not in cloudfront_ips:? ? ? ? cloudfront_ips_more_edge.append(ip)

for ip in cloudfront_ips_more_edge: print(str(ip))


such that output would be like
52.94.22.0/2452.94.17.0/2452.95.154.0/2352.95.212.0/2254.239.0.240/2854.239.54.0/2352.119.224.0/21....
I dont know why I am not able to get the code working.
please can you help out. Thanks.
Ose M.?

    On Wednesday, October 2, 2019, 06:35:16 PM EDT, Alan Gauld <alan.gauld at btinternet.com> wrote:  
 
 On 02/10/2019 19:43, ose micah wrote:
> 
> Hello Alan,?
> Thank you A lot. You are a time saver. it works better with "a" as the
> function or a is to append. "w" overwrites the previous line.?
> 

Only if you have the open() inside the loop.

In my second post I moved the second open outside the for loop so the
writes all go into the same file in order.

The problem with append is that if you rerun the script without
first deleting the file you will wind up creating two copies
of the data inside. The second appended after the first!


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

  

From garylarose at outlook.com  Thu Oct  3 18:57:52 2019
From: garylarose at outlook.com (Gary LaRose)
Date: Thu, 3 Oct 2019 22:57:52 +0000
Subject: [Tutor] python: extracting nested json object from multiple files,
 write to separate text files
Message-ID: <DM5PR1201MB0026032DD34BC17AD675C1F7D79F0@DM5PR1201MB0026.namprd12.prod.outlook.com>

Thank you for you guidance.
I am attempting to extract nested json object in multiple json files and write to individual text files.
I have been able to get a non-nested element ['text'] from the json files and write to text files using:

import os, json
import glob

filelist = glob.glob('./*.json')

for fname in filelist:
     FI = open(fname, 'r', encoding = 'UTF-8')
     FO = open(fname.replace('json', 'txt'), 'w', encoding = 'UTF-8')
     json_object = json.load(FI)
     FO.write(json_object['text'])

FI.close()
FO.close()

I have set the working directory to the folder that contains the json files.
Below is example json file. For each file (2,900), I need to extract 'entities' and write to a separate text file:

{'author': 'Reuters Editorial',
'crawled': '2018-02-02T12:58:39.000+02:00',
'entities': {'locations': [{'name': 'sweden', 'sentiment': 'none'},
                            {'name': 'sweden', 'sentiment': 'none'},
                            {'name': 'gothenburg', 'sentiment': 'none'}],
              'organizations': [{'name': 'reuters', 'sentiment': 'negative'},
                                {'name': 'skanska ab', 'sentiment': 'negative'},
                                {'name': 'eikon', 'sentiment': 'none'}],
              'persons': [{'name': 'anna ringstrom', 'sentiment': 'none'}]},
'external_links': ['http://thomsonreuters.com/en/about-us/trust-principles.html'],
'highlightText': '',
'highlightTitle': '',
'language': 'english',
'locations': [],
'ord_in_thread': 0,
'organizations': [],
'persons': [],
'published': '2018-02-01T15:02:00.000+02:00',
'text': 'Feb 1 (Reuters) - Skanska Ab:\n'
         '* SKANSKA DIVEST OFFICE BUILDINGS IN GOTHENBURG, SWEDEN, FOR ABOUT '
         'SEK 1 BILLION Source text for Eikon: Further company coverage: '
         '(Reporting By Anna Ringstrom)\n'
         ' ',
'thread': {'country': 'US',
            'domain_rank': 408,
            'main_image': 'https://s4.reutersmedia.net/resources_v2/images/rcom-default.png',
            'participants_count': 1,
            'performance_score': 0,
            'published': '2018-02-01T15:02:00.000+02:00',
            'replies_count': 0,
            'section_title': 'Archive News &amp; Video for Thursday, 01 Feb '
                             '2018 | Reuters.com',
            'site': 'reuters.com',
            'site_full': 'www.reuters.com',
            'site_section': 'http://www.reuters.com/resources/archive/us/20180201.html',
            'site_type': 'news',
            'social': {'facebook': {'comments': 0, 'likes': 0, 'shares': 0},
                       'gplus': {'shares': 0},
                       'linkedin': {'shares': 0},
                       'pinterest': {'shares': 0},
                       'stumbledupon': {'shares': 0},
                       'vk': {'shares': 0}},
            'spam_score': 0.21,
            'title': 'BRIEF-Skanska sells office buildings in Sweden for '
                     'around 1 bln SEK',
            'title_full': '',
            'url': 'https://www.reuters.com/article/brief-skanska-sells-office-buildings-in/brief-skanska-sells-office-buildings-in-sweden-for-around-1-bln-sek-idUSASM000IRO',
            'uuid': 'c83c8bf46fdb8d597e6c10ad16f221379c1c0705'},
'title': 'BRIEF-Skanska sells office buildings in Sweden for around 1 bln SEK',
'url': 'https://www.reuters.com/article/brief-skanska-sells-office-buildings-in/brief-skanska-sells-office-buildings-in-sweden-for-around-1-bln-sek-idUSASM000IRO',
'uuid': 'c83c8bf46fdb8d597e6c10ad16f221379c1c0705'}

From cs at cskk.id.au  Thu Oct  3 19:15:23 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Fri, 4 Oct 2019 09:15:23 +1000
Subject: [Tutor] [OT] Tutor no longer mirrored to Gmane?
In-Reply-To: <3f6cc498-f195-7efa-5b91-cb2d5ce08a34@btinternet.com>
References: <3f6cc498-f195-7efa-5b91-cb2d5ce08a34@btinternet.com>
Message-ID: <20191003231523.GA86856@cskk.homeip.net>

On 03Oct2019 14:57, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 03/10/2019 13:57, David Lowry-Duda wrote:
>> Interesting. It has been my impression that gmane stopped archiving in
>> 2016.
>
>It stopped being maintained but those archives that still existed
>continued working. Unfortunately the mass unsubscription has
>effectively removed Python tutor from that list of services!

The tutor list admin could manually add the gmane address to the 
subscription list.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From alan.gauld at btinternet.com  Thu Oct  3 19:12:47 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 4 Oct 2019 00:12:47 +0100
Subject: [Tutor] print issue
In-Reply-To: <608230864.3396203.1570136574576@mail.yahoo.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <182617636.2758926.1570041827090@mail.yahoo.com>
 <5d04817d-f84c-09fe-2373-3b5a54eeb413@btinternet.com>
 <608230864.3396203.1570136574576@mail.yahoo.com>
Message-ID: <1b00babf-b739-165c-b782-53eb8f984617@btinternet.com>

On 03/10/2019 22:02, ose micah wrote:

> cloudfront_ips = [item['ip_prefix'] for item in ip_ranges if item ==
> "CLOUDFRONT_GLOBAL_IP_LIST"]

This line makes no sense.

First of all you treat item as a dictionary using item['ip_prefix']
Then you treat item as a string with item=="CLOUDFRONT_GLOBAL_IP_LIST"

It can't be both, its either a dict or a string. Which is it?



> ec2_ips = [item['ip_prefix'] for item in ip_ranges if item ==
> "CLOUDFRONT_REGIONAL_EDGE_IP_LIST"]

And this is the same.

> for ip in cloudfront_ips:
> ? ? if ip not in ec2_ips:
> ? ? ? ? cloudfront_ips_more_edge.append(ip)

Why not use list comprehensions here too:

cloudfront_ips_more_edge=[ip for ip in cloudfront_ips
                             if ip not in ec2_ips]

An alternative approach would be to use sets and
use the intersection and other set operators

> for ip in ec2_ips:
> ? ? if ip not in cloudfront_ips:
> ? ? ? ? cloudfront_ips_more_edge.append(ip)

same as above...

> for ip in cloudfront_ips_more_edge: print(str(ip))

I suspect ip is already a string so you shouldn't need the str() conversion.


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


From cs at cskk.id.au  Thu Oct  3 19:27:17 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Fri, 4 Oct 2019 09:27:17 +1000
Subject: [Tutor] python: extracting nested json object from multiple
 files, write to separate text files
In-Reply-To: <DM5PR1201MB0026032DD34BC17AD675C1F7D79F0@DM5PR1201MB0026.namprd12.prod.outlook.com>
References: <DM5PR1201MB0026032DD34BC17AD675C1F7D79F0@DM5PR1201MB0026.namprd12.prod.outlook.com>
Message-ID: <20191003232717.GA98262@cskk.homeip.net>

On 03Oct2019 22:57, Gary LaRose <garylarose at outlook.com> wrote:
>Thank you for you guidance.
>I am attempting to extract nested json object in multiple json files and write to individual text files.
>I have been able to get a non-nested element ['text'] from the json files and write to text files using:
>
>import os, json
>import glob
>
>filelist = glob.glob('./*.json')

No need for the leading "./" here. "*.json" will do.

>for fname in filelist:
>     FI = open(fname, 'r', encoding = 'UTF-8')
>     FO = open(fname.replace('json', 'txt'), 'w', encoding = 'UTF-8')

Minor remark: this is not robust; consider the filename 
"some-json-in-here.json". Have a glance at the os.pathsplitext function.

>     json_object = json.load(FI)
>     FO.write(json_object['text'])
>
>FI.close()
>FO.close()

Second minor remark: these are better written:

    with open(fname, 'r', encoding = 'UTF-8') as FI:
        json_object = json.load(FI)
    with open(fname.replace('json', 'txt'), 'w', encoding = 'UTF-8') as FO:
        FO.write(json_object['text'])

which do the closes for you (even if an exception happens).

>I have set the working directory to the folder that contains the json files.
>Below is example json file. For each file (2,900), I need to extract 'entities' and write to a separate text file:
>
>{'author': 'Reuters Editorial',
>'crawled': '2018-02-02T12:58:39.000+02:00',
>'entities': {'locations': [{'name': 'sweden', 'sentiment': 'none'},
>                            {'name': 'sweden', 'sentiment': 'none'},
>                            {'name': 'gothenburg', 'sentiment': 'none'}],
>              'organizations': [{'name': 'reuters', 'sentiment': 'negative'},
>                                {'name': 'skanska ab', 'sentiment': 'negative'},
>                                {'name': 'eikon', 'sentiment': 'none'}],
>              'persons': [{'name': 'anna ringstrom', 'sentiment': 'none'}]},
[...]

Well, the entities come in from the JSON as a dictionary mapping str to 
list. Thus:

    entities = json_object['entities']

FOr example, with the example data above, the expression 
entities['locations'] has the value:

    [
        {'name': 'sweden', 'sentiment': 'none'},
        {'name': 'sweden', 'sentiment': 'none'},
        {'name': 'gothenburg', 'sentiment': 'none'}
    ]

Which is just a list of dictionaries. You just need to access whatever 
you need as required. When you went:

    FO.write(json_object['text'])

that has the advantage that json_object['text'] is a simple string. If 
you need to write out the values from entities then you _likely_ want to 
print it in some more meaningful way. However, just to get off the 
ground you would go:

    FO.write(repr(entities))

as a proff of concept. When happy, write something more elaborate to get 
the actual output format you desire.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From cs at cskk.id.au  Thu Oct  3 19:56:01 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Fri, 4 Oct 2019 09:56:01 +1000
Subject: [Tutor] print issue
In-Reply-To: <1b00babf-b739-165c-b782-53eb8f984617@btinternet.com>
References: <1b00babf-b739-165c-b782-53eb8f984617@btinternet.com>
Message-ID: <20191003235601.GA93316@cskk.homeip.net>

On 04Oct2019 00:12, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 03/10/2019 22:02, ose micah wrote:
>> for ip in cloudfront_ips_more_edge: print(str(ip))
>
>I suspect ip is already a string so you shouldn't need the str() 
>conversion.

Not to mention that print() calls str() on its arguments anyway.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From akleider at sonic.net  Thu Oct  3 19:55:15 2019
From: akleider at sonic.net (Alex Kleider)
Date: Thu, 03 Oct 2019 16:55:15 -0700
Subject: [Tutor] python: extracting nested json object from multiple
 files, write to separate text files
In-Reply-To: <DM5PR1201MB0026032DD34BC17AD675C1F7D79F0@DM5PR1201MB0026.namprd12.prod.outlook.com>
References: <DM5PR1201MB0026032DD34BC17AD675C1F7D79F0@DM5PR1201MB0026.namprd12.prod.outlook.com>
Message-ID: <bca2c52dd5fbbfa21789a937fa149ef2@sonic.net>

On 2019-10-03 15:57, Gary LaRose wrote:
> Thank you for you guidance.
> I am attempting to extract nested json object in multiple json files
> and write to individual text files.
> I have been able to get a non-nested element ['text'] from the json
> files and write to text files using:


> for fname in filelist:
>      FI = open(fname, 'r', encoding = 'UTF-8')
>      FO = open(fname.replace('json', 'txt'), 'w', encoding = 'UTF-8')
>      json_object = json.load(FI)
>      FO.write(json_object['text'])
> 
> FI.close()
> FO.close()
> 
> Below is example json file. For each file (2,900), I need to extract
> 'entities' and write to a separate text file:
> 
> {'author': 'Reuters Editorial',
> 'crawled': '2018-02-02T12:58:39.000+02:00',
> 'entities': {'locations': [{'name': 'sweden', 'sentiment': 'none'},
>                             {'name': 'sweden', 'sentiment': 'none'},
>                             {'name': 'gothenburg', 'sentiment': 
> 'none'}],
>               'organizations': [{'name': 'reuters', 'sentiment': 
> 'negative'},
>                                 {'name': 'skanska ab', 'sentiment': 
> 'negative'},
>                                 {'name': 'eikon', 'sentiment': 
> 'none'}],
>               'persons': [{'name': 'anna ringstrom', 'sentiment': 
> 'none'}]},
> 'external_links':
> ...........



Although not one of the "tutors" I'd like to take a stab at helping
you with the goal of getting some feed back as to how close I get to
the correct answer.
I suggest you replace the line "FO.write(json_object['text'])" with
the following to get what I think you want:

     ret = []
     ret.append("Text component")
     ret.append("==============")
     for line in json_object["text"]:
         # I assume you want the "text" component as well;
         # if not, delete this for loop and the two lines above it.
         ret.append(line)
     ret.append("")
     ret.append("entities")
     ret.append("========")
     for key in json_object['entities']:
         ret.append(key)
         ret.append("-" * len(key))
         for record in json_object[key]:
             ret.append("{name}: {sentiment}".format(**record))
     FO.write("\n".join(ret))

I've not tested.

From alan.gauld at btinternet.com  Thu Oct  3 20:19:13 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 4 Oct 2019 01:19:13 +0100
Subject: [Tutor] [OT] Tutor no longer mirrored to Gmane?
In-Reply-To: <20191003231523.GA86856@cskk.homeip.net>
References: <3f6cc498-f195-7efa-5b91-cb2d5ce08a34@btinternet.com>
 <20191003231523.GA86856@cskk.homeip.net>
Message-ID: <b871c116-0bf0-c331-1691-e51a19c50129@btinternet.com>

On 04/10/2019 00:15, Cameron Simpson wrote:
> On 03Oct2019 14:57, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>> On 03/10/2019 13:57, David Lowry-Duda wrote:
>>> Interesting. It has been my impression that gmane stopped archiving in
>>> 2016.
>>
>> It stopped being maintained but those archives that still existed
>> continued working. Unfortunately the mass unsubscription has
>> effectively removed Python tutor from that list of services!
> 
> The tutor list admin could manually add the gmane address to the 
> subscription list.

I could if I knew what that address was. But I have no way
of knowing what email address gmane subscribed as.

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


From kharatemihir at gmail.com  Fri Oct  4 06:39:34 2019
From: kharatemihir at gmail.com (Mihir Kharate)
Date: Fri, 4 Oct 2019 05:39:34 -0500
Subject: [Tutor] Printing Complimentary strand of the DNA sequence:
Message-ID: <CAH3WxOMte00QHfTp+MCFO5O5yA6aKvA5TddNSLOZZ5ZonBj+yw@mail.gmail.com>

Hi!

I wrote this code to print out the complimentary strand of the DNA
sequence that is prompted to input.

(In a DNA sequence, the base 'A' binds to the base 'T' and 'C' binds
to 'G'. These base letters are compliments of each other). So the
expected output for a 'ATTGC' should be 'TAACG'

The code I have written does the job, but instead of printing the code
in a line, it prints every letter on a new line and it does this two
times.

This is the pastebin site link to my code: (
https://commie.io/#yCvdFhuj ). Please give me some insight on why it
is doing this and how to fix this for expected output.

Thank you!
~ Mihir

From osaosemwe at yahoo.com  Fri Oct  4 10:30:28 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Fri, 4 Oct 2019 14:30:28 +0000 (UTC)
Subject: [Tutor] print issue
In-Reply-To: <1b00babf-b739-165c-b782-53eb8f984617@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <182617636.2758926.1570041827090@mail.yahoo.com>
 <5d04817d-f84c-09fe-2373-3b5a54eeb413@btinternet.com>
 <608230864.3396203.1570136574576@mail.yahoo.com>
 <1b00babf-b739-165c-b782-53eb8f984617@btinternet.com>
Message-ID: <1111933804.3688630.1570199428862@mail.yahoo.com>

 Hello Alan,?
Thanks, It is a dictionary.
I wrote it that way because, am trying to append the list of ips in both the cloudfront_ips and the ec2_ips as one:
Here is the updates:

#!/usr/bin/env python
import requestsimport sysimport fileinput
ip_ranges = requests.get('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips').json()cloudfront_ips = [item['CLOUDFRONT_GLOBAL_IP_LIST'] for item in ip_ranges]ec2_ips = [item['CLOUDFRONT_REGIONAL_EDGE_IP_LIST'] for item in ip_ranges]
for ip in cloudfront_ips? ? if ip not in ec2_ips? ? ? ? cloudfront_ips_more_edge.append(ip)
for ip in ec2_ips? ? if ip not in cloudfront_ips? ? ? ? cloudfront_ips_more_edge.append(ip)

for ip in cloudfront_ips_more_edge: print(str(ip))


such that output would be like
52.94.22.0/2452.94.17.0/2452.95.154.0/2352.95.212.0/2254.239.0.240/2854.239.54.0/2352.119.224.0/21....
    On Thursday, October 3, 2019, 07:12:49 PM EDT, Alan Gauld <alan.gauld at btinternet.com> wrote:  
 
 On 03/10/2019 22:02, ose micah wrote:

> cloudfront_ips = [item['ip_prefix'] for item in ip_ranges if item ==
> "CLOUDFRONT_GLOBAL_IP_LIST"]

This line makes no sense.

First of all you treat item as a dictionary using item['ip_prefix']
Then you treat item as a string with item=="CLOUDFRONT_GLOBAL_IP_LIST"

It can't be both, its either a dict or a string. Which is it?



> ec2_ips = [item['ip_prefix'] for item in ip_ranges if item ==
> "CLOUDFRONT_REGIONAL_EDGE_IP_LIST"]

And this is the same.

> for ip in cloudfront_ips:
> ? ? if ip not in ec2_ips:
> ? ? ? ? cloudfront_ips_more_edge.append(ip)

Why not use list comprehensions here too:

cloudfront_ips_more_edge=[ip for ip in cloudfront_ips
? ? ? ? ? ? ? ? ? ? ? ? ? ? if ip not in ec2_ips]

An alternative approach would be to use sets and
use the intersection and other set operators

> for ip in ec2_ips:
> ? ? if ip not in cloudfront_ips:
> ? ? ? ? cloudfront_ips_more_edge.append(ip)

same as above...

> for ip in cloudfront_ips_more_edge: print(str(ip))

I suspect ip is already a string so you shouldn't need the str() conversion.


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

  

From osaosemwe at yahoo.com  Fri Oct  4 12:04:40 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Fri, 4 Oct 2019 16:04:40 +0000 (UTC)
Subject: [Tutor] print issue
In-Reply-To: <1b00babf-b739-165c-b782-53eb8f984617@btinternet.com>
References: <1162792864.1860056.1569899911609@mail.yahoo.com>
 <20191001080314.GA19311@cskk.homeip.net>
 <673247016.2006902.1569937036192@mail.yahoo.com>
 <6630807b-51e0-4dc5-724d-556f90756aad@btinternet.com>
 <1461408383.2614096.1570030235654@mail.yahoo.com>
 <ef8fc134-bd0b-4c52-7daf-bf77a66049ed@btinternet.com>
 <182617636.2758926.1570041827090@mail.yahoo.com>
 <5d04817d-f84c-09fe-2373-3b5a54eeb413@btinternet.com>
 <608230864.3396203.1570136574576@mail.yahoo.com>
 <1b00babf-b739-165c-b782-53eb8f984617@btinternet.com>
Message-ID: <1166118446.3715786.1570205080769@mail.yahoo.com>

 Thanks Alan,
I have solved the problemm, main issue, I think was I was not importing json and using the items in the dictionary properly:here is the solution:



import requests

import json

resp = requests.get('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips')

ip_json = json.loads(resp.text)

for eachSubnet in ip_json['CLOUDFRONT_GLOBAL_IP_LIST']:

?? ? print eachSubnet


Thanks?
Ose M.
    On Thursday, October 3, 2019, 07:12:49 PM EDT, Alan Gauld <alan.gauld at btinternet.com> wrote:  
 
 On 03/10/2019 22:02, ose micah wrote:

> cloudfront_ips = [item['ip_prefix'] for item in ip_ranges if item ==
> "CLOUDFRONT_GLOBAL_IP_LIST"]

This line makes no sense.

First of all you treat item as a dictionary using item['ip_prefix']
Then you treat item as a string with item=="CLOUDFRONT_GLOBAL_IP_LIST"

It can't be both, its either a dict or a string. Which is it?



> ec2_ips = [item['ip_prefix'] for item in ip_ranges if item ==
> "CLOUDFRONT_REGIONAL_EDGE_IP_LIST"]

And this is the same.

> for ip in cloudfront_ips:
> ? ? if ip not in ec2_ips:
> ? ? ? ? cloudfront_ips_more_edge.append(ip)

Why not use list comprehensions here too:

cloudfront_ips_more_edge=[ip for ip in cloudfront_ips
? ? ? ? ? ? ? ? ? ? ? ? ? ? if ip not in ec2_ips]

An alternative approach would be to use sets and
use the intersection and other set operators

> for ip in ec2_ips:
> ? ? if ip not in cloudfront_ips:
> ? ? ? ? cloudfront_ips_more_edge.append(ip)

same as above...

> for ip in cloudfront_ips_more_edge: print(str(ip))

I suspect ip is already a string so you shouldn't need the str() conversion.


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

  

From mats at wichmann.us  Fri Oct  4 14:16:11 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Fri, 4 Oct 2019 12:16:11 -0600
Subject: [Tutor] Printing Complimentary strand of the DNA sequence:
In-Reply-To: <CAH3WxOMte00QHfTp+MCFO5O5yA6aKvA5TddNSLOZZ5ZonBj+yw@mail.gmail.com>
References: <CAH3WxOMte00QHfTp+MCFO5O5yA6aKvA5TddNSLOZZ5ZonBj+yw@mail.gmail.com>
Message-ID: <aef0c94e-4a94-de81-fbe5-11646e62066a@wichmann.us>

On 10/4/19 4:39 AM, Mihir Kharate wrote:
> Hi!
> 
> I wrote this code to print out the complimentary strand of the DNA
> sequence that is prompted to input.
> 
> (In a DNA sequence, the base 'A' binds to the base 'T' and 'C' binds
> to 'G'. These base letters are compliments of each other). So the
> expected output for a 'ATTGC' should be 'TAACG'
> 
> The code I have written does the job, but instead of printing the code
> in a line, it prints every letter on a new line and it does this two
> times.
> 
> This is the pastebin site link to my code: (
> https://commie.io/#yCvdFhuj ). Please give me some insight on why it
> is doing this and how to fix this for expected output.

you really could have just pasted the code directly into your email:

     var_DNAseq = input("Insert your DNA sequence here: ")

     def Complimentary_Strand():
         for Compliment in var_DNAseq:
             Compliment = var_DNAseq.upper()
             for character in Compliment:
                 if character == "G":
                     print("C")
                 if character == "C":
                     print("G")
                 if character == "T":
                     print("A")
                 if character == "A":
                     print("T")

     print("Complimentary Strand of your sequence: ")

     Complimentary_Strand()


you get duplicates because you're already iterating over the string in 
the first for loop, then inside that you loop over it again - the outer 
loop should be omitted entirely.

print, if you don't tell it otherwise, outputs a line of text - 
including a newline.

you can use the "end" keyword to change that, as in:

print("C", end="")

or you can use some other technique here - sys.stdout.write('C') is much 
more literal and just puts out what it's told to; or you could collect 
the characters into a string and return it from the function, and then 
print it in the main program - that would feel more natural because you 
can use the returned string for other purposes than putting it out on 
the console.





From alan.gauld at btinternet.com  Fri Oct  4 14:23:47 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 4 Oct 2019 19:23:47 +0100
Subject: [Tutor] Printing Complimentary strand of the DNA sequence:
In-Reply-To: <CAH3WxOMte00QHfTp+MCFO5O5yA6aKvA5TddNSLOZZ5ZonBj+yw@mail.gmail.com>
References: <CAH3WxOMte00QHfTp+MCFO5O5yA6aKvA5TddNSLOZZ5ZonBj+yw@mail.gmail.com>
Message-ID: <97bcfa58-3407-07da-5043-54fedf009224@btinternet.com>

On 04/10/2019 11:39, Mihir Kharate wrote:

> (In a DNA sequence, the base 'A' binds to the base 'T' and 'C' binds
> to 'G'. These base letters are compliments of each other). So the
> expected output for a 'ATTGC' should be 'TAACG'
Look at the translate method of strings combined with the
maketrans() function....


>>> table = str.maketrans('ATCG','TAGC')
>>> 'AGTCAGACT'.translate(table)
'CTGACTCAG'

Is that what you want?

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


From garylarose at outlook.com  Fri Oct  4 14:32:36 2019
From: garylarose at outlook.com (Gary LaRose)
Date: Fri, 4 Oct 2019 18:32:36 +0000
Subject: [Tutor] python: extracting nested json object from multiple
 files, write to separate text files
In-Reply-To: <20191003232717.GA98262@cskk.homeip.net>
References: <DM5PR1201MB0026032DD34BC17AD675C1F7D79F0@DM5PR1201MB0026.namprd12.prod.outlook.com>
 <20191003232717.GA98262@cskk.homeip.net>
Message-ID: <DM5PR1201MB0026BAB0CE390138DF96BB33D79E0@DM5PR1201MB0026.namprd12.prod.outlook.com>

Thank you Cameron, this works nicely - and thanks for pointing me to os.pathsplitext and repr functions
The 'with open...as' ran faster on my local machine.

Best regards


-----Original Message-----
From: Cameron Simpson <cs at cskk.id.au> 
Sent: October 3, 2019 7:27 PM
To: Gary LaRose <garylarose at outlook.com>
Cc: tutor at python.org
Subject: Re: [Tutor] python: extracting nested json object from multiple files, write to separate text files

On 03Oct2019 22:57, Gary LaRose <garylarose at outlook.com> wrote:
>Thank you for you guidance.
>I am attempting to extract nested json object in multiple json files and write to individual text files.
>I have been able to get a non-nested element ['text'] from the json files and write to text files using:
>
>import os, json
>import glob
>
>filelist = glob.glob('./*.json')

No need for the leading "./" here. "*.json" will do.

>for fname in filelist:
>     FI = open(fname, 'r', encoding = 'UTF-8')
>     FO = open(fname.replace('json', 'txt'), 'w', encoding = 'UTF-8')

Minor remark: this is not robust; consider the filename "some-json-in-here.json". Have a glance at the os.pathsplitext function.

>     json_object = json.load(FI)
>     FO.write(json_object['text'])
>
>FI.close()
>FO.close()

Second minor remark: these are better written:

    with open(fname, 'r', encoding = 'UTF-8') as FI:
        json_object = json.load(FI)
    with open(fname.replace('json', 'txt'), 'w', encoding = 'UTF-8') as FO:
        FO.write(json_object['text'])

which do the closes for you (even if an exception happens).

>I have set the working directory to the folder that contains the json files.
>Below is example json file. For each file (2,900), I need to extract 'entities' and write to a separate text file:
>
>{'author': 'Reuters Editorial',
>'crawled': '2018-02-02T12:58:39.000+02:00',
>'entities': {'locations': [{'name': 'sweden', 'sentiment': 'none'},
>                            {'name': 'sweden', 'sentiment': 'none'},
>                            {'name': 'gothenburg', 'sentiment': 'none'}],
>              'organizations': [{'name': 'reuters', 'sentiment': 'negative'},
>                                {'name': 'skanska ab', 'sentiment': 'negative'},
>                                {'name': 'eikon', 'sentiment': 'none'}],
>              'persons': [{'name': 'anna ringstrom', 'sentiment': 
>'none'}]},
[...]

Well, the entities come in from the JSON as a dictionary mapping str to list. Thus:

    entities = json_object['entities']

FOr example, with the example data above, the expression entities['locations'] has the value:

    [
        {'name': 'sweden', 'sentiment': 'none'},
        {'name': 'sweden', 'sentiment': 'none'},
        {'name': 'gothenburg', 'sentiment': 'none'}
    ]

Which is just a list of dictionaries. You just need to access whatever you need as required. When you went:

    FO.write(json_object['text'])

that has the advantage that json_object['text'] is a simple string. If you need to write out the values from entities then you _likely_ want to print it in some more meaningful way. However, just to get off the ground you would go:

    FO.write(repr(entities))

as a proff of concept. When happy, write something more elaborate to get the actual output format you desire.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From kharatemihir at gmail.com  Sun Oct  6 19:59:39 2019
From: kharatemihir at gmail.com (Mihir Kharate)
Date: Sun, 6 Oct 2019 18:59:39 -0500
Subject: [Tutor] Printing Complimentary strand of the DNA sequence:
In-Reply-To: <97bcfa58-3407-07da-5043-54fedf009224@btinternet.com>
References: <CAH3WxOMte00QHfTp+MCFO5O5yA6aKvA5TddNSLOZZ5ZonBj+yw@mail.gmail.com>
 <97bcfa58-3407-07da-5043-54fedf009224@btinternet.com>
Message-ID: <CAH3WxOOMGsRBMch2pKHoPDhefgUbgvxCEOOFG9i1+NS8uXFaEQ@mail.gmail.com>

Thanks @Mats Wichmann , I tried all the suggestions for returning the
output I wanted. They all worked great. Although removing the second
for loop returned an error. So I removed the extra indentation and
then it worked fine.
Also, I think that by default, when I assign a variable to input
something, the input is stored as a string unless maybe when it is a
number.

@Alan Gauld , thank you for the suggestion of the maketrans function!
It worked out great, with relatively less code.


On Fri, Oct 4, 2019 at 1:23 PM Alan Gauld via Tutor <tutor at python.org> wrote:
>
> On 04/10/2019 11:39, Mihir Kharate wrote:
>
> > (In a DNA sequence, the base 'A' binds to the base 'T' and 'C' binds
> > to 'G'. These base letters are compliments of each other). So the
> > expected output for a 'ATTGC' should be 'TAACG'
> Look at the translate method of strings combined with the
> maketrans() function....
>
>
> >>> table = str.maketrans('ATCG','TAGC')
> >>> 'AGTCAGACT'.translate(table)
> 'CTGACTCAG'
>
> Is that what you want?
>
> --
> 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 at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From cs at cskk.id.au  Sun Oct  6 21:39:10 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Mon, 7 Oct 2019 12:39:10 +1100
Subject: [Tutor] Printing Complimentary strand of the DNA sequence:
In-Reply-To: <CAH3WxOOMGsRBMch2pKHoPDhefgUbgvxCEOOFG9i1+NS8uXFaEQ@mail.gmail.com>
References: <CAH3WxOOMGsRBMch2pKHoPDhefgUbgvxCEOOFG9i1+NS8uXFaEQ@mail.gmail.com>
Message-ID: <20191007013910.GA63868@cskk.homeip.net>

On 06Oct2019 18:59, Mihir Kharate <kharatemihir at gmail.com> wrote:
>Also, I think that by default, when I assign a variable to input
>something, the input is stored as a string unless maybe when it is a
>number.

If you mean:

    x = input("prompt...")

then it is always a string. You must convert it if it has another 
meaning.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From alan.gauld at yahoo.co.uk  Mon Oct  7 17:41:10 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 7 Oct 2019 22:41:10 +0100
Subject: [Tutor] Fwd: Re: dynamical program to create subnets CIDR
In-Reply-To: <571386883.4912920.1570476911879@mail.yahoo.com>
References: <571386883.4912920.1570476911879@mail.yahoo.com>
Message-ID: <e0c7f477-ac51-7863-8f4d-4e4b4eba3c77@yahoo.co.uk>


Please use Reply All or reply List when responding to the list.
Otherwise it just goes to the author.

-------- Forwarded Message --------
Subject: 	Re: dynamical program to create subnets CIDR
Date: 	Mon, 7 Oct 2019 19:35:11 +0000 (UTC)
From: 	ose micah <osaosemwe at yahoo.com>
To: 	alan.gauld at yahoo.co.uk



Hello Alan,??

Basically, the algorithm I have in mind is one that takes the first Ip
in the list, and compares it to others in the list. It can definitely be
improved on.??
>From the list of subnets, it pick the first subnet and compares it with
others, such that if the first and second set of 3 digit are same in the
subnet, it pushes this to a temp list, so that it combines all these
subnets into one subnet, and overwrites the new subnet created (which is
the least CIDR block of the subnets in the temp list) and the rest
subnet to a file. If the number of subnets in the file is not less or
equals to four, it continues the process comparing list of subnets.??
Next if the after comparing the first and the second set of 3 digit, it
has not yielded the result needed, it compares the first set of 3 digits
in the IPs left. it create a list of those that are same, and generates
a subnet of least CIDR block to the list left until the least of CIDR is
4 or less than 4.??

Thanks and regards,

Ose Micah.

On Monday, October 7, 2019, 02:54:23 PM EDT, Alan Gauld
<alan.gauld at btinternet.com> wrote:


On 07/10/2019 19:31, ose micah wrote:


> Can anyone help with a program that could compare a list of IPs and
> create the least possible CIDR block sets from these IPs.
>
> for example.
>
> I have a list say:
>
...
>
> I want to reduce this list to:
>
> 10.32.0.0/14
> 202.238.149.0/19
> 10.224.0.0/13
> 10.54.63.0/13



Sorry but I cannot see how you get to the second list
from the first. I think you need to give us a clue what
the high level algorithm is. Don't assume we know your
problem domain. Most of us don't, we know Python.

At a basic level I'd suggest investigating functions
like str.split(), sort(), max/min(). But even that
does not appear sufficient to meet your needs.
Without understanding the criteria I can't guess the algorithm.

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



From osaosemwe at yahoo.com  Mon Oct  7 14:31:07 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Mon, 7 Oct 2019 18:31:07 +0000 (UTC)
Subject: [Tutor] dynamical program to create subnets CIDR
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
Message-ID: <1601109860.4879400.1570473067728@mail.yahoo.com>

Hello All,
Can anyone help with a program that could compare a list of IPs and create the least possible CIDR block sets from these IPs.
for example.
I have a list say:
202.238.149.0/22202.238.164.0/22202.238.168.0/23202.238.176.0/20202.238.174.0/23202.238.172.0/2320.226.12.224/2720.223.14.0/2410.32.0.0/1510.35.0.0/1610.54.63.128/2610.59.250.0/2610.224.0.0/2410.228.69.0/24
I want to reduce this list to:
10.32.0.0/14202.238.149.0/19
10.224.0.0/1310.54.63.0/13

Thanks
Ose Micah




From npbhogill at cpp.edu  Mon Oct  7 09:33:09 2019
From: npbhogill at cpp.edu (Nirmeet P. Bhogill)
Date: Mon, 7 Oct 2019 13:33:09 +0000
Subject: [Tutor] python assignment
Message-ID: <BYAPR01MB511236B31DB16596B9E214F4B69B0@BYAPR01MB5112.prod.exchangelabs.com>

Hi,

I need help in this Python assignment that I am doing. I'm not sure how to complete it. Could you please help me?



From cs at cskk.id.au  Mon Oct  7 18:28:05 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Tue, 8 Oct 2019 09:28:05 +1100
Subject: [Tutor] python assignment
In-Reply-To: <BYAPR01MB511236B31DB16596B9E214F4B69B0@BYAPR01MB5112.prod.exchangelabs.com>
References: <BYAPR01MB511236B31DB16596B9E214F4B69B0@BYAPR01MB5112.prod.exchangelabs.com>
Message-ID: <20191007222805.GA7817@cskk.homeip.net>

On 07Oct2019 13:33, Nirmeet P. Bhogill <npbhogill at cpp.edu> wrote:
>I need help in this Python assignment that I am doing. I'm not sure how 
>to complete it. Could you please help me?

We do not do homework directly. Humans learn by doing, so you need to do 
it yourself in order to learn.

What we will do is look at your _attempt_ at some task, and identify 
problems or suggest approaches or explain something which is not 
understood.

So you can post a shiny new question (with a good subject line; "help" 
is a bit vague, and rather implicit) showing your task and the code you 
have tried, which did not work. Also include the output of the code and 
an explaination of what is wrong.

Also, this list does not do attachments; paste your code and output 
inline in the message.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From PyTutor at danceswithmice.info  Mon Oct  7 18:43:52 2019
From: PyTutor at danceswithmice.info (DL Neil)
Date: Tue, 8 Oct 2019 11:43:52 +1300
Subject: [Tutor] Fwd: Re: dynamical program to create subnets CIDR
In-Reply-To: <e0c7f477-ac51-7863-8f4d-4e4b4eba3c77@yahoo.co.uk>
References: <571386883.4912920.1570476911879@mail.yahoo.com>
 <e0c7f477-ac51-7863-8f4d-4e4b4eba3c77@yahoo.co.uk>
Message-ID: <983c9fe4-2140-69d3-c116-5093ee63fce4@DancesWithMice.info>

Please consider also that maintaining the order of the conversation 
makes it easier to follow!
(comments below)


> On Monday, October 7, 2019, 02:54:23 PM EDT, Alan Gauld
> <alan.gauld at btinternet.com> wrote:
> On 07/10/2019 19:31, ose micah wrote:
>> Can anyone help with a program that could compare a list of IPs and
>> create the least possible CIDR block sets from these IPs.
>> for example.
>> I have a list say:
> ...
>> I want to reduce this list to:
>> 10.32.0.0/14
>> 202.238.149.0/19
>> 10.224.0.0/13
>> 10.54.63.0/13
> 
> Sorry but I cannot see how you get to the second list
> from the first. I think you need to give us a clue what
> the high level algorithm is. Don't assume we know your
> problem domain. Most of us don't, we know Python.
> 
> At a basic level I'd suggest investigating functions
> like str.split(), sort(), max/min(). But even that
> does not appear sufficient to meet your needs.
> Without understanding the criteria I can't guess the algorithm.


 > -------- Forwarded Message --------
 > Subject: 	Re: dynamical program to create subnets CIDR
 > Date: 	Mon, 7 Oct 2019 19:35:11 +0000 (UTC)
 > From: 	ose micah <osaosemwe at yahoo.com>
 > To: 	alan.gauld at yahoo.co.uk
 > Basically, the algorithm I have in mind is one that takes the first Ip
 > in the list, and compares it to others in the list. It can definitely be
 > improved on.??
 >  From the list of subnets, it pick the first subnet and compares it with
 > others, such that if the first and second set of 3 digit are same in the
 > subnet, it pushes this to a temp list, so that it combines all these
 > subnets into one subnet, and overwrites the new subnet created (which is
 > the least CIDR block of the subnets in the temp list) and the rest
 > subnet to a file. If the number of subnets in the file is not less or
 > equals to four, it continues the process comparing list of subnets.??
 > Next if the after comparing the first and the second set of 3 digit, it
 > has not yielded the result needed, it compares the first set of 3 digits
 > in the IPs left. it create a list of those that are same, and generates
 > a subnet of least CIDR block to the list left until the least of CIDR is
 > 4 or less than 4.??


A dictionary is a very useful way of 'classifying' items, eg
	
	people[ 'male' ] = 'Fred'
	people[ 'female' ] = 'Wilma'

A set is a data structure for grouping more than one 'similar' item, eg

	couple == { 'Fred', 'Wilma' }

Perhaps break the larger problem into two:
- which sub-nets are relevant?
- how should each sub-net be described?

Possibility:
- each time a new sub-net is 'discovered' use the higher two octets as 
the key to a dictionary
- make the dictionary-entry's value a set, add-ing the lower octets as 
its first value/member
- when the next item on the source-data list matches an existing sub-net 
(key) in the dictionary (easy and fast comparison), add the lower octets 
to the value-set
- afterwards, consider each sub-net in the dictionary in-turn, and 
rationalise the CIDR addresses.

-- 
Regards =dn

From cs at cskk.id.au  Mon Oct  7 18:54:50 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Tue, 8 Oct 2019 09:54:50 +1100
Subject: [Tutor] Fwd: Re: dynamical program to create subnets CIDR
In-Reply-To: <983c9fe4-2140-69d3-c116-5093ee63fce4@DancesWithMice.info>
References: <983c9fe4-2140-69d3-c116-5093ee63fce4@DancesWithMice.info>
Message-ID: <20191007225450.GA75546@cskk.homeip.net>

On 08Oct2019 11:43, DL Neil <PyTutor at danceswithmice.info> wrote:
>>On 07/10/2019 19:31, ose micah wrote:
>>>Can anyone help with a program that could compare a list of IPs and
>>>create the least possible CIDR block sets from these IPs.
>>>for example.
>>>I have a list say:
>>...
>>>I want to reduce this list to:
>>>10.32.0.0/14
>>>202.238.149.0/19
>>>10.224.0.0/13
>>>10.54.63.0/13
[...]
>Perhaps break the larger problem into two:
>- which sub-nets are relevant?
>- how should each sub-net be described?
>
>Possibility:
>- each time a new sub-net is 'discovered' use the higher two octets as 
>the key to a dictionary

Subnets can be larger than this. For example the 127.0.0.0/8 subnet.  
Also, subnets need not land on octet boundaries.

>- make the dictionary-entry's value a set, add-ing the lower octets as 
>its first value/member
>- when the next item on the source-data list matches an existing 
>sub-net (key) in the dictionary (easy and fast comparison), add the 
>lower octets to the value-set
>- afterwards, consider each sub-net in the dictionary in-turn, and 
>rationalise the CIDR addresses.

I would be inclined to compute the subnets' (top-bits, length) pairs and 
write a small function to test whether one such pair is entirely covered 
by another pair. Then sort the subnets by size and then prefix and 
compare.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From gursimran.maken at gmail.com  Tue Oct  8 03:32:37 2019
From: gursimran.maken at gmail.com (Gursimran Maken)
Date: Tue, 8 Oct 2019 13:02:37 +0530
Subject: [Tutor] Difference between range and xrange
Message-ID: <CAPug6nYyF+G-UBd3rLmExPMMjyqvyZg4-18ajF+LhTT6D5bx_g@mail.gmail.com>

Hi All,

I would like to know the difference between range and xrange with respect
to both python2 and python3.

Thank you in advance,
Gursimran.

From cs at cskk.id.au  Tue Oct  8 05:11:45 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Tue, 8 Oct 2019 20:11:45 +1100
Subject: [Tutor] Difference between range and xrange
In-Reply-To: <CAPug6nYyF+G-UBd3rLmExPMMjyqvyZg4-18ajF+LhTT6D5bx_g@mail.gmail.com>
References: <CAPug6nYyF+G-UBd3rLmExPMMjyqvyZg4-18ajF+LhTT6D5bx_g@mail.gmail.com>
Message-ID: <20191008091145.GA33459@cskk.homeip.net>

On 08Oct2019 13:02, Gursimran Maken <gursimran.maken at gmail.com> wrote:
>I would like to know the difference between range and xrange with 
>respect
>to both python2 and python3.

In python2 range() returns a list of values and xrange() is a generator 
which yields those values progressively. So range() (a) consumes enough 
memory to store all the values individually and (b) does not return 
until it has computed and stored all those values. By contrast, xrange() 
is a generator yielding the same values. You get the first value 
immediately, and the values are not stored.

In python3 there's no xrange(), and range() is a generator function 
yields values like xrange() used to in Python 2.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From alan.gauld at btinternet.com  Mon Oct  7 14:54:21 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 7 Oct 2019 19:54:21 +0100
Subject: [Tutor] dynamical program to create subnets CIDR
In-Reply-To: <1601109860.4879400.1570473067728@mail.yahoo.com>
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
 <1601109860.4879400.1570473067728@mail.yahoo.com>
Message-ID: <38fc3078-e4b5-5c12-3e63-9e3def27165a@btinternet.com>

On 07/10/2019 19:31, ose micah wrote:

> Can anyone help with a program that could compare a list of IPs and
> create the least possible CIDR block sets from these IPs.
> 
> for example.
> 
> I have a list say:
> 
...
> 
> I want to reduce this list to:
> 
> 10.32.0.0/14
> 202.238.149.0/19
> 10.224.0.0/13
> 10.54.63.0/13


Sorry but I cannot see how you get to the second list
from the first. I think you need to give us a clue what
the high level algorithm is. Don't assume we know your
problem domain. Most of us don't, we know Python.

At a basic level I'd suggest investigating functions
like str.split(), sort(), max/min(). But even that
does not appear sufficient to meet your needs.
Without understanding the criteria I can't guess the algorithm.

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


From PyTutor at DancesWithMice.info  Tue Oct  8 16:32:13 2019
From: PyTutor at DancesWithMice.info (David L Neil)
Date: Wed, 9 Oct 2019 09:32:13 +1300
Subject: [Tutor] OT: Re:  Pointers Towards Appropriate Python Methods
In-Reply-To: <5D91E6E2.5000909@sbcglobal.net>
References: <5D90F7CA.5080108@sbcglobal.net>
 <5b952c30-2ba4-3842-369c-6fde92cee56b@DancesWithMice.info>
 <5D91E6E2.5000909@sbcglobal.net>
Message-ID: <ffadf25f-84ac-4519-74a1-8152fd0fa8a8@DancesWithMice.info>

On 1/10/19 12:28 AM, Stephen P. Molnar wrote:


Stephen,
You wrote to me privately (cf to the list).
My reply has bounced-off your email provider:

<s.molnar at sbcglobal.net>: host 
ff-ip4-mx-vip1.prodigy.net[144.160.159.21] said:
     553 5.3.0 flpd590 DNSBL:RBL 521< 51.254.211.219 >_is_blocked.For 
assistance
     forward this error to abuse_rbl at abuse-att.net (in reply to MAIL FROM
     command)

-- 
Regards =dn

From savageapple850 at gmail.com  Wed Oct  9 02:09:42 2019
From: savageapple850 at gmail.com (Cravan)
Date: Wed, 09 Oct 2019 14:09:42 +0800
Subject: [Tutor] USEREVENT not detected
Message-ID: <543C6A98-96DA-4EEE-8B1B-F9BF888B8D14@gmail.com>

Hi all,

??????????????? While doing some game programming, I ran into a problem with the set_timer function. In my code, I wanted a bar which shows the current amount of food I have, which is supposed to decrease every second. However, it appears that the amount of space empty in my bar does not increase and pygame cannot detect my HUNGEREVENT. May I know what is the problem in my code?

````

def run(self):

??????? self.playing = True

??????? while self.playing:

??????????? self.dt = self.clock.tick(FPS) / 1000

??????????? self.hunger()

??????????? self.events()

??????????? self.update()

??????????? self.draw()

 

??? def hunger(self):

??????? HUNGEREVENT = pygame.USEREVENT + 1

??????? pygame.time.set_timer(HUNGEREVENT, 1000)

??????? self.all_sprites.update()

??????? pygame.display.flip()

 

??? def food_food(self, x, y, cool):

??????? if cool < 0:

??????????? cool = 0

??????? BAR_LENGTH = 100

??????? BAR_HEIGHT = 10

??????? fill = (cool / 100) * BAR_LENGTH

??????? outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)

??????? fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)

??????? pygame.draw.rect(screen, GREEN, fill_rect)

??????? pygame.draw.rect(screen, WHITE, outline_rect, 2)

 

??? def quit(self):

??????? pygame.quit()

??????? sys.exit()

 

??? def update(self):

??????? self.all_sprites.update()

 

 

??? def draw(self):

??????? self.screen.fill(BGCOLOR)

??????? self.all_sprites.draw(self.screen)

??????? font = pygame.font.SysFont('Arial', 15, True, False)

??????? self.food_food(120, 50, self.food_bar)

??????? text = font.render("Number of days:" , True, BLACK)

??????? screen.blit(text, [0, 110])

??????? font = pygame.font.SysFont('Arial', 30, True, False)

??????? text = font.render("= " + str(self.education_level), True, BLACK)

??????? screen.blit(text, [400, 40])

??????? font = pygame.font.SysFont('Arial', 30, True, False)

??????? text = font.render("= " + str(self.family_member), True, BLACK)

??????? screen.blit(text, [700, 40])

??????? font = pygame.font.SysFont('Arial', 30, True, False)

??????? text = font.render("= $" + str(self.money_bar), True, BLACK)

??????? screen.blit(text, [900, 40])

??????? self.all_sprites.update()

??????? pygame.display.flip()

 

??? def events(self):

??????? # catch all events here

??????? HUNGEREVENT = pygame.USEREVENT + 1

??????? pygame.time.set_timer(HUNGEREVENT, 10000)

??????? if pygame.event.get(HUNGEREVENT):

??????????? self.food_bar = self.food_bar - 10

??????????? print("hi")

??????????? self.all_sprites.update()

??????????? pygame.display.flip()

??????? for event in pygame.event.get():

??????????? if event.type == pygame.QUIT:

??????????????? self.quit()

??????????????? if event.key == pygame.K_ESCAPE:

??????????????????? self.quit()

````

Thanks,

Cravan


From savageapple850 at gmail.com  Wed Oct  9 05:06:46 2019
From: savageapple850 at gmail.com (Cravan)
Date: Wed, 09 Oct 2019 17:06:46 +0800
Subject: [Tutor] Problem handling keyboard commands
Message-ID: <143B9C3E-50C2-41AC-A27F-BF817D44246D@gmail.com>

Hi guys,

I fixed the problem I mentioned beforehand, but ran into a new problem with the keyboard commands. In my code, I wanted the food_bar in my game to increase when i press a key, say f, in my game, and also deduct say $10 from my money_bar when i press f. The food bar shows the current amount of food I have, which is supposed to decrease every second. However, it appears that none of my keyboard commands in the event() are working. May I know what is the problem in my code?

def __init__(self):

??????? pygame.init()

??????? self.clock = pygame.time.Clock()

??????? self.living = 1

??????? self.screen = pygame.display.set_mode((WIDTH, HEIGHT))

??????? pygame.display.set_caption(TITLE)

??????? self.time = pygame.time.get_ticks()

??????? pygame.key.set_repeat(500, 100)

??????? self.all_sprites = pygame.sprite.Group()

??????? self.console = Console(self, 0)

??????? self.player = Player(self, 390, 595)

??????? self.work = Work(self, 450, 250)

??????? self.food_station = Food_Station(self, 750, 200)

??????? self.food = Food(self, 25, 20)

??????? self.education = Education(self, 300, 10)

??????? self.school = School(self, 100, 200)

??????? self.family = Family(self, 600, 10)

??????? self.money = Money(self, 800, 15)

??????? initial_food = 100

??????? self.food_bar = initial_food

??????? initial_money = 0

??????? self.money_bar = initial_money

??????? initial_education = "Student"

??????? self.education_level = initial_education

??????? initial_family = 3

??????? self.family_member = 3

 

??? def run(self):

??????? self.playing = True

??????? self.hunger()

??????? while self.playing:

??????????? self.dt = self.clock.tick(FPS) / 1000

??????????? self.events()

??????????? self.draw()

??????????? self.update()

 

??? def hunger(self):

??????? self.HUNGEREVENT = pygame.USEREVENT + 1

??????? pygame.time.set_timer(self.HUNGEREVENT, 1000)

??????? self.all_sprites.update()

??????? pygame.display.flip()

 

??? def food_food(self, x, y, cool):

??????? if cool < 0:

??????????? cool = 0

??????? BAR_LENGTH = 100

??????? BAR_HEIGHT = 10

??????? fill = (cool / 100) * BAR_LENGTH

??????? outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)

??????? fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)

??????? pygame.draw.rect(screen, GREEN, fill_rect)

??????? pygame.draw.rect(screen, WHITE, outline_rect, 2)

??????? if cool == 0:

??????????? self.living = 0

??????????? self.quit()

 

??? def quit(self):

??????? pygame.quit()

??????? sys.exit()

 

??? def update(self):

??????? self.all_sprites.update()

 

 

??? def draw(self):

?? ?????self.screen.fill(BGCOLOR)

??????? self.all_sprites.draw(self.screen)

??????? font = pygame.font.SysFont('Arial', 15, True, False)

??????? self.food_food(120, 50, self.food_bar)

??????? text = font.render("Number of days:" , True, BLACK)

??????? screen.blit(text, [0, 110])

??????? font = pygame.font.SysFont('Arial', 30, True, False)

??????? text = font.render("= " + str(self.education_level), True, BLACK)

??????? screen.blit(text, [400, 40])

??????? font = pygame.font.SysFont('Arial', 30, True, False)

??????? text = font.render("= " + str(self.family_member), True, BLACK)

??????? screen.blit(text, [700, 40])

??????? font = pygame.font.SysFont('Arial', 30, True, False)

??????? text = font.render("= $" + str(self.money_bar), True, BLACK)

??????? screen.blit(text, [900, 40])

??????? self.all_sprites.update()

??????? pygame.display.flip()

 

??? def events(self):

??????? for event in pygame.event.get():

??????????? if event.type == pygame.QUIT:

??????????????? self.quit()

??????????? if event.type == self.HUNGEREVENT:

??????????????? self.food_bar = self.food_bar - 10

??????????????? self.all_sprites.update()

??????????????? pygame.display.flip()

 

??????????? if event.type == pygame.K_f:

??????????????? self.money_bar = self.money_bar - 10

??????? ????????self.food_bar = self.food_bar + 15

??????????????? self.all_sprites.update()

??????????????? pygame.display.flip()

 

??????????? if event.type == pygame.K_ESCAPE:

??????????????? self.quit()

Thanks in advance,

Cravan

 


From alan.gauld at btinternet.com  Wed Oct  9 18:52:32 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Oct 2019 23:52:32 +0100
Subject: [Tutor] Fwd: Re:  Problem handling keyboard commands
In-Reply-To: <4aaaf390-c177-0f1f-d0e9-d7ba9687d6d2@btinternet.com>
References: <4aaaf390-c177-0f1f-d0e9-d7ba9687d6d2@btinternet.com>
Message-ID: <33ae76ee-bfd5-161b-07fd-2ad268a77d2a@btinternet.com>


This didn't seem to come through on the list. If it now appears twice I
apologize in advance....


-------- Forwarded Message --------
Subject: Re: [Tutor] Problem handling keyboard commands
Date: Wed, 9 Oct 2019 17:23:52 +0100
From: Alan Gauld <alan.gauld at btinternet.com>
Reply-To: alan.gauld at yahoo.co.uk
To: tutor at python.org

On 09/10/2019 10:06, Cravan wrote:

>  it appears that none of my keyboard commands in the event() are working. May I know what is the problem in my code?

> 
> ??????????? if event.type == pygame.K_f:
> 

I believe that in pygame this should look like:

if event.type == pygame.KEYDOWN and event.key == pygame.K_f:
    ....

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


From alan.gauld at btinternet.com  Wed Oct  9 06:20:15 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Oct 2019 11:20:15 +0100
Subject: [Tutor] USEREVENT not detected
In-Reply-To: <543C6A98-96DA-4EEE-8B1B-F9BF888B8D14@gmail.com>
References: <543C6A98-96DA-4EEE-8B1B-F9BF888B8D14@gmail.com>
Message-ID: <c32d867e-6f52-999e-3d72-c5266bd25de0@btinternet.com>

On 09/10/2019 07:09, Cravan wrote:
> Hi all,
> 
> ??????????????? While doing some game programming,... pygame cannot detect my HUNGEREVENT. 

The tutor list is mainly for questions about the core python
language and libraries aswell as fundamentals of programming.
Questions about specific packages like pygame are more likely
to get good answers on their own fora.

There is a pygame forum link here:

https://www.pygame.org/wiki/info

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


From eggo at hotmail.com  Thu Oct 10 17:26:27 2019
From: eggo at hotmail.com (Eggo why)
Date: Thu, 10 Oct 2019 21:26:27 +0000
Subject: [Tutor] Assign exec() value to a variable
Message-ID: <CH2PR01MB59738415EB674FBD548FA1C6C5940@CH2PR01MB5973.prod.exchangelabs.com>

Hi all,
   How can I assign result from exec() into a variable.  Following is my code.

import config

sid='configdb'
SID = ("config.%s()" % sid)
print('--params: ',SID)
params = exec(SID)
print('-- params :',params)


Gary

From mats at wichmann.us  Thu Oct 10 21:26:12 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Thu, 10 Oct 2019 19:26:12 -0600
Subject: [Tutor] Assign exec() value to a variable
In-Reply-To: <CH2PR01MB59738415EB674FBD548FA1C6C5940@CH2PR01MB5973.prod.exchangelabs.com>
References: <CH2PR01MB59738415EB674FBD548FA1C6C5940@CH2PR01MB5973.prod.exchangelabs.com>
Message-ID: <987ce748-0f1f-fdc7-0998-582a2696f144@wichmann.us>

On 10/10/19 3:26 PM, Eggo why wrote:
> Hi all,
>     How can I assign result from exec() into a variable.  Following is my code.
> 
> import config
> 
> sid='configdb'
> SID = ("config.%s()" % sid)
> print('--params: ',SID)
> params = exec(SID)
> print('-- params :',params)

exec doesn't return anything (i.e. None), and is not what you want for 
this job - assuming the idea is "call function dynamically".

Instead you can use getattr to look up the function object in the 
module, and then call it. Not promising this actually works since I 
don't have your code:


import config

params = getattr(config, 'configdb')()



From alan.gauld at btinternet.com  Fri Oct 11 05:36:04 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Oct 2019 10:36:04 +0100
Subject: [Tutor] Assign exec() value to a variable
In-Reply-To: <CH2PR01MB59738415EB674FBD548FA1C6C5940@CH2PR01MB5973.prod.exchangelabs.com>
References: <CH2PR01MB59738415EB674FBD548FA1C6C5940@CH2PR01MB5973.prod.exchangelabs.com>
Message-ID: <30a4f6fb-4ad1-dc9a-f727-9c9fa68769e2@btinternet.com>

On 10/10/2019 22:26, Eggo why wrote:
> Hi all,
>    How can I assign result from exec() into a variable. 

You can't, exec() doesn't return anything it just executes
the code. But that's not a problem because you should almost
never use exec(). It is a security nightmare, impossible to
debug, and there are nearly always better ways to achieve
what you want safely (or at least more safely!).


> import config
> 
> sid='configdb'
> SID = ("config.%s()" % sid)
> print('--params: ',SID)
> params = exec(SID)

So what you really want is to execute config.configdb()
but, presumably, want the function to be assigned dynamically
rather than statically. And you want the return value.

The simplest solution is to use eval rather than exec()
since eval returns the result. But eval has many of the
same problems as exec()

I see Mats has already pointed you at getattr()

Another approach is to create a dispatch table (or dict)
of all the config functions that you want to execute and
then translate your dynamic input into one of those and
call it indirectly via the table. This is one of the
safest methods, since you can only call the things you
know are valid, and quite fast.

dispatch = {'friendly name': config.func,
            'another name': config.func2
}

func_name = get_func()  # get the function name from wherever

try: param = dispatch[func_name]()
except KeyError: print("No such function")


You could replace the last two lines with

param = dispatch.get(func_name, lambda : print("No such function"))()


But I personally think the try/except is easier to read
and allows more flexibility.

-- 

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


From alan.gauld at btinternet.com  Fri Oct 11 11:32:23 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Oct 2019 16:32:23 +0100
Subject: [Tutor] loop print issue
In-Reply-To: <732029288.249778.1570806005876@mail.yahoo.com>
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
 <1601109860.4879400.1570473067728@mail.yahoo.com>
 <38fc3078-e4b5-5c12-3e63-9e3def27165a@btinternet.com>
 <732029288.249778.1570806005876@mail.yahoo.com>
Message-ID: <c9597a56-6c72-6636-9e42-cb0f2b0612c5@btinternet.com>

Please do not hijack someone else's thread to raise a new issue
it makes searching the archives much more difficult. Raise a new
message to start a new topic. (Note that simply changing the
subject line does not change the thread identifier in the message)

On 11/10/2019 16:00, ose micah wrote:

> I need your quick help, I am same loop print issue you pointed out.
> I have a file "xlist_file" with a list of varying values of up to 70.
> from this file I intend to split the content to two different files
> output1.txt and output2.txt. I want this values to be always fresh,
> making use of w+ and no appending. currently if I switch? +a to +w in
> the output2.txt, it always cleans out the values.
> 
> 
> "line of code:"
> 
> /sys.stdout = open('output1.txt','w+')/
> /

This is the main problem. You are using sys.stdout for file output.
That is not what sys.stdout is intended for and if you continue
to do so you will continue to have these kinds of issues.
You will also confuse yourself and anyone else who reads your code.

It is possible to do it but it requires you to do a whole heap of
extra work that would not be necessary if you just used regular
files.

OK, To the code...


You open sys.stdout on output1.txt here. Once only at the start of the
code. You never open it again.

> /
> /for i in xlist_file:/
> /? ? ? ? if counter < 36:/

You are comparing counter even though you never initialize it? I'm
assuming you missed a line above that sets counter to 0?

> /? ? ? ? ? ? if counter >= 35:/
> /? ? ? ? ? ? ? ? sys.stdout.close()/

Here you close sys.stdout (output1.txt on the first occurence)

> /? ? ? ? ? ? ? ? sys.stdout = open('output2.txt','a+')/

And now you open sys.stdout again with output2.txt.

On the first time round this closes output1 and opes output2.
On subsequent occurences it will close output2 then immediately reopwen
it again.

Notice that on each opening you will reposition the file cursor
to the beginning of the file if you use 'w+' and at the end of
the file if you use 'a+'.  I'm not sure which you actually want.
And I'm even less sure why you think you want the plus version.
(That brings yet more complexity that you don't want or need)

> /? ? ? ? ? ? ? ? print(i)/
> /? ? ? ? ? ? ? ? counter +=1/
> /? ? ? ? ? ? else:/
> /? ? ? ? ? ? ? ? print(i)/
> /? ? ? ? ? ? ? ? counter +=1/

You are using counters so you are writing the first 36 lines(0-35)
to output1. Then you write the rest to output2. If that is what
you want it would be a lot easier to say so explicitly:

with open('output1.txt','w') as output1
   for count in range(36):
       output1.write(xlist_file.readline())

with open('output2.txt','w') as output2:
   for line in xlist_file:
       output2 write(line)

No need for resetting sys.stdout.
No need for fancy '+' modes.
No need for complex counters or if statements.

However, I have a sneaky suspicion this is not actually what
you want to do. But either way it will almost certainly be
easier if you stop abusing sys.stdout and just open two
output files and write() to them!

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


From mats at wichmann.us  Fri Oct 11 12:50:18 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Fri, 11 Oct 2019 10:50:18 -0600
Subject: [Tutor] loop print issue
In-Reply-To: <c9597a56-6c72-6636-9e42-cb0f2b0612c5@btinternet.com>
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
 <1601109860.4879400.1570473067728@mail.yahoo.com>
 <38fc3078-e4b5-5c12-3e63-9e3def27165a@btinternet.com>
 <732029288.249778.1570806005876@mail.yahoo.com>
 <c9597a56-6c72-6636-9e42-cb0f2b0612c5@btinternet.com>
Message-ID: <95bb6715-395e-ef46-f0b0-2c1e8c659de7@wichmann.us>

On 10/11/19 9:32 AM, Alan Gauld via Tutor wrote:

> You are using counters so you are writing the first 36 lines(0-35)
> to output1. Then you write the rest to output2. If that is what
> you want it would be a lot easier to say so explicitly:
> 
> with open('output1.txt','w') as output1
>     for count in range(36):
>         output1.write(xlist_file.readline())
> 
> with open('output2.txt','w') as output2:
>     for line in xlist_file:
>         output2 write(line)
> 
> No need for resetting sys.stdout.
> No need for fancy '+' modes.
> No need for complex counters or if statements.

Just for grins, here's another way to implement the idiom of splitting a 
list into chunks:

import itertools

with open('output1.txt', 'w') as output1:
     output1.writelines(itertools.islice(xlist_file, 36))
with open('output2.txt', 'w') as output2:
     # previous islice has "consumed" the 36 lines, continue to end
     output2.writelines(itertools.islice(xlist_file, None))


From eggo at hotmail.com  Thu Oct 10 21:42:40 2019
From: eggo at hotmail.com (Eggo why)
Date: Fri, 11 Oct 2019 01:42:40 +0000
Subject: [Tutor] Assign exec() value to a variable
In-Reply-To: <987ce748-0f1f-fdc7-0998-582a2696f144@wichmann.us>
References: <CH2PR01MB59738415EB674FBD548FA1C6C5940@CH2PR01MB5973.prod.exchangelabs.com>,
 <987ce748-0f1f-fdc7-0998-582a2696f144@wichmann.us>
Message-ID: <CH2PR01MB59733AC8C4349C9BE2E1D510C5970@CH2PR01MB5973.prod.exchangelabs.com>

Hi Mats,
     Thank you very much.  It works the way I wanted.

Gary
________________________________
From: Tutor <tutor-bounces+eggo=hotmail.com at python.org> on behalf of Mats Wichmann <mats at wichmann.us>
Sent: Friday, October 11, 2019 1:26 AM
To: tutor at python.org <tutor at python.org>
Subject: Re: [Tutor] Assign exec() value to a variable

On 10/10/19 3:26 PM, Eggo why wrote:
> Hi all,
>     How can I assign result from exec() into a variable.  Following is my code.
>
> import config
>
> sid='configdb'
> SID = ("config.%s()" % sid)
> print('--params: ',SID)
> params = exec(SID)
> print('-- params :',params)

exec doesn't return anything (i.e. None), and is not what you want for
this job - assuming the idea is "call function dynamically".

Instead you can use getattr to look up the function object in the
module, and then call it. Not promising this actually works since I
don't have your code:


import config

params = getattr(config, 'configdb')()


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

From osaosemwe at yahoo.com  Fri Oct 11 11:00:05 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Fri, 11 Oct 2019 15:00:05 +0000 (UTC)
Subject: [Tutor] loop print issue
In-Reply-To: <38fc3078-e4b5-5c12-3e63-9e3def27165a@btinternet.com>
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
 <1601109860.4879400.1570473067728@mail.yahoo.com>
 <38fc3078-e4b5-5c12-3e63-9e3def27165a@btinternet.com>
Message-ID: <732029288.249778.1570806005876@mail.yahoo.com>

 Hello Alan,
I need your quick help, I am same loop print issue you pointed out.I have a file "xlist_file" with a list of varying values of up to 70. from this file I intend to split the content to two different files output1.txt and output2.txt. I want this values to be always fresh, making use of w+ and no appending. currently if I switch? +a to +w in the output2.txt, it always cleans out the values.

"line of code:"
sys.stdout = open('output1.txt','w+')
for i in xlist_file:? ? ? ? if counter < 36:? ? ? ? ? ? if counter >= 35:? ? ? ? ? ? ? ? sys.stdout.close()? ? ? ? ? ? ? ? sys.stdout = open('output2.txt','a+')? ? ? ? ? ? ? ? print(i)? ? ? ? ? ? ? ? counter +=1? ? ? ? ? ? else:? ? ? ? ? ? ? ? print(i)? ? ? ? ? ? ? ? counter +=1sys.stdout.close()

content of xlist_file
1541091716262537365049......
is there a way I can go about this issue? I really value your input.
Thanks

Ose Micah.

From alan.gauld at yahoo.co.uk  Fri Oct 11 20:08:34 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 12 Oct 2019 01:08:34 +0100
Subject: [Tutor] loop print issue
In-Reply-To: <285143223.361687.1570818554091@mail.yahoo.com>
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
 <1601109860.4879400.1570473067728@mail.yahoo.com>
 <38fc3078-e4b5-5c12-3e63-9e3def27165a@btinternet.com>
 <732029288.249778.1570806005876@mail.yahoo.com>
 <c9597a56-6c72-6636-9e42-cb0f2b0612c5@btinternet.com>
 <285143223.361687.1570818554091@mail.yahoo.com>
Message-ID: <f7fd8201-5348-97cd-daf3-5f4f4c5dc28b@yahoo.co.uk>

On 11/10/2019 19:29, ose micah wrote:

> Thanks for your initial answer, I do appreciate it only this does not
> give the needed results:

I don't think your code did what you wanted either. I simply showed a
cleaner way of doing what you were doing. But I don't think what you
were doing was what you wanted to do. Unfortunately you didn't say what
you wanted to do so I couldn't be sure.

> The output2.txt file has only one line (the last line) with your code.

I'm guessing your input file has 37 lines?

36 went to output1 and 1 to output2? Thats what the program
(both yours and mine) says to do...

> and output1.txt has the results all on a single line against line by
> line as my initial code.

In that case add a \n to the end of the write string...

> with open('output1.txt','w') as output1
> ?? for count in range(36):
> ?? ?? ?? output1.write(xlist_file.readline() + '\n')
> 
> with open('output2.txt','w') as output2:
> ?? for line in xlist_file:
> ?? ?? ?? output2 write(line+'\n')


> However, I have a sneaky suspicion this is not actually what
> you want to do. But either way it will almost certainly be
> easier if you stop abusing sys.stdout and just open two
> output files and write() to them!

If you don't just want the first 36 lines in output1 then you need to
tell us what you do want. How do you want to split the file?
I suspect you actually want to put the lines containing
line values <36 in one file and values >36 in the other.
Is that right?

If so it should look something like(untested):

with open('output1.txt,'w') as output1:
   with open('output2.txt','w') as output2:
      for line in xlist_file:
           if int(line) > 35:
              output1.write(line + '\n')
           else output2.write(line + '\n')



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


From kharatemihir at gmail.com  Sun Oct 13 01:17:31 2019
From: kharatemihir at gmail.com (Mihir Kharate)
Date: Sun, 13 Oct 2019 00:17:31 -0500
Subject: [Tutor] GC content: Help with if/else statements:
Message-ID: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>

Hi,

Following is part of the code I am working on in Python3. I am trying to
calculate the GC content of the input DNA sequence. I want the function to
return "Invalid base-pair in your sequence" if the input sequence has
letters other than A, T, G and C.

######################################################
input_sequence = input("Input your sequence here: ")
input_sequence = input_sequence.upper()
print("\nYour sequence is: " + input_sequence)
print("\n")
a=t=g=c=0
def gc_content():
    global a,g,t,c
    for character in input_sequence:
        if character == 'G':
            g+=1
        if character == 'C':
            c+=1
        if character == 'T':
            t+=1
        if character == 'A':
            a+=1
        gc_cont = (g+c)/(a+g+t+c)*100
    if character == 'A' or 'T' or 'G' or 'C':
        print ("The GC content is: " + str(gc_cont) + " %")
    else :
        print("Invalid base-pair in your Sequence")

gc_content()

############################################
*Question 1*: When I use the else statement as I have in the code above, it
is ineffective. Even if I input other letters in my input sequence, it
still returns the GC content.

*Question 2*: When I use another if statement like below, it returns the GC
content and "Invalid base-pair in your Sequence" both. No matter whether
the input has any other characters than A,T,G,C or not.

    if character == 'A' or 'T' or 'G' or 'C':
        print ("The GC content is: " + str(gc_cont) + " %")
    if character is not 'A' or 'T' or 'G' or 'C':
        print("Invalid base-pair in your Sequence")

*Question 3*: How do I fix this?

Thank you for any suggestions and help!
~Mihir

From joel.goldstick at gmail.com  Sun Oct 13 03:41:58 2019
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sun, 13 Oct 2019 03:41:58 -0400
Subject: [Tutor] GC content: Help with if/else statements:
In-Reply-To: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
References: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
Message-ID: <CAPM-O+yCaYTG7CbWeU54r1gHjZwTHS2pyxWLadqV5Wusq1O91w@mail.gmail.com>

On Sun, Oct 13, 2019 at 3:35 AM Mihir Kharate <kharatemihir at gmail.com> wrote:
>
> Hi,
>
> Following is part of the code I am working on in Python3. I am trying to
> calculate the GC content of the input DNA sequence. I want the function to
> return "Invalid base-pair in your sequence" if the input sequence has
> letters other than A, T, G and C.
>
> ######################################################
> input_sequence = input("Input your sequence here: ")
> input_sequence = input_sequence.upper()
> print("\nYour sequence is: " + input_sequence)
> print("\n")
> a=t=g=c=0
> def gc_content():
>     global a,g,t,c
>     for character in input_sequence:
>         if character == 'G':
>             g+=1
>         if character == 'C':
>             c+=1
>         if character == 'T':
>             t+=1
>         if character == 'A':
>             a+=1
>         gc_cont = (g+c)/(a+g+t+c)*100
>     if character == 'A' or 'T' or 'G' or 'C':

The if statement isn't doing what you think it is.
Try:
    if character in ('A', 'T', 'G', 'C'):
         ....


>         print ("The GC content is: " + str(gc_cont) + " %")
>     else :
>         print("Invalid base-pair in your Sequence")
>
> gc_content()
>
> ############################################
> *Question 1*: When I use the else statement as I have in the code above, it
> is ineffective. Even if I input other letters in my input sequence, it
> still returns the GC content.
>
> *Question 2*: When I use another if statement like below, it returns the GC
> content and "Invalid base-pair in your Sequence" both. No matter whether
> the input has any other characters than A,T,G,C or not.
>
>     if character == 'A' or 'T' or 'G' or 'C':
>         print ("The GC content is: " + str(gc_cont) + " %")
>     if character is not 'A' or 'T' or 'G' or 'C':
>         print("Invalid base-pair in your Sequence")
>
> *Question 3*: How do I fix this?
>
> Thank you for any suggestions and help!
> ~Mihir
> _______________________________________________
> Tutor maillist  -  Tutor at 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

From kharatemihir at gmail.com  Sun Oct 13 11:52:11 2019
From: kharatemihir at gmail.com (Mihir Kharate)
Date: Sun, 13 Oct 2019 10:52:11 -0500
Subject: [Tutor] GC content: Help with if/else statements:
In-Reply-To: <CAPM-O+yCaYTG7CbWeU54r1gHjZwTHS2pyxWLadqV5Wusq1O91w@mail.gmail.com>
References: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
 <CAPM-O+yCaYTG7CbWeU54r1gHjZwTHS2pyxWLadqV5Wusq1O91w@mail.gmail.com>
Message-ID: <CAH3WxOPkQFU_ReWum_kZZCXKTAQ=tdqWv23L-ST9wtKUbbntvg@mail.gmail.com>

@Joel Goldstick , I tried what you suggested. Its still returning the first
if statement. If I input a sequence which has a different letter than
A/T/G/C (for example, if I input ATFGC as my input when prompted) , it does
not return the error message: "Invalid base-pair in your Sequence".
It seems like the second if statement (or else statement, if I change it
that way) does not run at all.

On Sun, Oct 13, 2019 at 2:42 AM Joel Goldstick <joel.goldstick at gmail.com>
wrote:

> On Sun, Oct 13, 2019 at 3:35 AM Mihir Kharate <kharatemihir at gmail.com>
> wrote:
> >
> > Hi,
> >
> > Following is part of the code I am working on in Python3. I am trying to
> > calculate the GC content of the input DNA sequence. I want the function
> to
> > return "Invalid base-pair in your sequence" if the input sequence has
> > letters other than A, T, G and C.
> >
> > ######################################################
> > input_sequence = input("Input your sequence here: ")
> > input_sequence = input_sequence.upper()
> > print("\nYour sequence is: " + input_sequence)
> > print("\n")
> > a=t=g=c=0
> > def gc_content():
> >     global a,g,t,c
> >     for character in input_sequence:
> >         if character == 'G':
> >             g+=1
> >         if character == 'C':
> >             c+=1
> >         if character == 'T':
> >             t+=1
> >         if character == 'A':
> >             a+=1
> >         gc_cont = (g+c)/(a+g+t+c)*100
> >     if character == 'A' or 'T' or 'G' or 'C':
>
> The if statement isn't doing what you think it is.
> Try:
>     if character in ('A', 'T', 'G', 'C'):
>          ....
>
>
> >         print ("The GC content is: " + str(gc_cont) + " %")
> >     else :
> >         print("Invalid base-pair in your Sequence")
> >
> > gc_content()
> >
> > ############################################
> > *Question 1*: When I use the else statement as I have in the code above,
> it
> > is ineffective. Even if I input other letters in my input sequence, it
> > still returns the GC content.
> >
> > *Question 2*: When I use another if statement like below, it returns the
> GC
> > content and "Invalid base-pair in your Sequence" both. No matter whether
> > the input has any other characters than A,T,G,C or not.
> >
> >     if character == 'A' or 'T' or 'G' or 'C':
> >         print ("The GC content is: " + str(gc_cont) + " %")
> >     if character is not 'A' or 'T' or 'G' or 'C':
> >         print("Invalid base-pair in your Sequence")
> >
> > *Question 3*: How do I fix this?
> >
> > Thank you for any suggestions and help!
> > ~Mihir
> > _______________________________________________
> > Tutor maillist  -  Tutor at 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 at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at btinternet.com  Sun Oct 13 14:10:18 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 13 Oct 2019 19:10:18 +0100
Subject: [Tutor] GC content: Help with if/else statements:
In-Reply-To: <CAH3WxOPkQFU_ReWum_kZZCXKTAQ=tdqWv23L-ST9wtKUbbntvg@mail.gmail.com>
References: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
 <CAPM-O+yCaYTG7CbWeU54r1gHjZwTHS2pyxWLadqV5Wusq1O91w@mail.gmail.com>
 <CAH3WxOPkQFU_ReWum_kZZCXKTAQ=tdqWv23L-ST9wtKUbbntvg@mail.gmail.com>
Message-ID: <0135c9fb-4275-d72c-1d0f-822e6cf04ce4@btinternet.com>

On 13/10/2019 16:52, Mihir Kharate wrote:
> @Joel Goldstick , I tried what you suggested. Its still returning the first
> if statement. If I input a sequence which has a different letter than
> A/T/G/C (for example, if I input ATFGC as my input when prompted) , it does
> not return the error message: "Invalid base-pair in your Sequence".

First a point about terminology, which is important in programming.
Your function des not *return* anything it prints its output. Returning
something means you use thereturn statement to pass back a value to the
caller. You are not doing that.

Now to your point.
You say you took Joel's advive which means, I assume,
that your function now looks like:

def gc_content():
    global a,t,g,c
    for character in input_sequence:
        if character == 'G':
            g+=1
        if character == 'C':
            c+=1
        if character == 'T':
            t+=1
        if character == 'A':
            a+=1
        gc_cont = (g+c)/(a+g+t+c)*100
    if character in ('A',  'T', 'G', 'C'):
        print ("The GC content is: " + str(gc_cont) + " %")
    else :
        print("Invalid base-pair in your Sequence")

If so the if test only looks at the last character because it
is outside the for loop. If you want the if test to apply to all the
characters then you need to put it inside the functon.
Like this:

def gc_content():
    global a,t,g,c
    for character in input_sequence:
        if character == 'G':
            g+=1
        if character == 'C':
            c+=1
        if character == 'T':
            t+=1
        if character == 'A':
            a+=1
        gc_cont = (g+c)/(a+g+t+c)*100
        if character in ('A',  'T', 'G', 'C'):
            print ("The GC content is: " + str(gc_cont) + " %")
        else :
            print("Invalid base-pair in your Sequence")

That will do what I think you want.

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


From mats at wichmann.us  Sun Oct 13 14:22:57 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 13 Oct 2019 12:22:57 -0600
Subject: [Tutor] GC content: Help with if/else statements:
In-Reply-To: <CAH3WxOPkQFU_ReWum_kZZCXKTAQ=tdqWv23L-ST9wtKUbbntvg@mail.gmail.com>
References: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
 <CAPM-O+yCaYTG7CbWeU54r1gHjZwTHS2pyxWLadqV5Wusq1O91w@mail.gmail.com>
 <CAH3WxOPkQFU_ReWum_kZZCXKTAQ=tdqWv23L-ST9wtKUbbntvg@mail.gmail.com>
Message-ID: <6422d822-e99e-8027-f5cd-c9522d2fc212@wichmann.us>

On 10/13/19 9:52 AM, Mihir Kharate wrote:
> @Joel Goldstick , I tried what you suggested. Its still returning the first
> if statement. If I input a sequence which has a different letter than
> A/T/G/C (for example, if I input ATFGC as my input when prompted) , it does
> not return the error message: "Invalid base-pair in your Sequence".
> It seems like the second if statement (or else statement, if I change it
> that way) does not run at all.

You have some logic and/or indentation problems.

>>> ######################################################
>>> input_sequence = input("Input your sequence here: ")
>>> input_sequence = input_sequence.upper()
>>> print("\nYour sequence is: " + input_sequence)
>>> print("\n")
>>> a=t=g=c=0
>>> def gc_content():
>>>      global a,g,t,c

is there a reason to have these as global?  do you have a need to save 
values across repeated calls to this function? - seems unlikely.

>>>      for character in input_sequence:
>>>          if character == 'G':
>>>              g+=1
>>>          if character == 'C':
>>>              c+=1
>>>          if character == 'T':
>>>              t+=1
>>>          if character == 'A':
>>>              a+=1
>>>          gc_cont = (g+c)/(a+g+t+c)*100

this means you will do a pointless - and indeed destructive computation 
if the character is invalid (you'll get a divide-by-zero unless some 
valid character has been previously seen).  Probably you don't want to 
do this computation at all inside the loop, but rather finish processing 
the whole sequence first.

the tests here should properly be if-else, which will also let you 
easily bail out in the case of an invalid character.


>>>      if character == 'A' or 'T' or 'G' or 'C':

and this test, which is outside the loop as shown by the indentation, 
tests only the value of the last character will be tested.

>>
>> The if statement isn't doing what you think it is.
>> Try:
>>      if character in ('A', 'T', 'G', 'C'):
>>           ....
>>
>>
>>>          print ("The GC content is: " + str(gc_cont) + " %")

the formatting on this could be more elegant.  Here's a quicky refactor 
(more could be done), which also adds a sanity check in the beginning, 
and returning the result from the function (I see Alan has commented on 
the same thing while I was typing):

def gc_content():
     """ calculate and return GC content of a sequence

     Returns None if invalid
     """

     global a,g,t,c

     if not input_sequence:
         return None

     for character in input_sequence:
         if character == 'G':
             g+=1
         elif character == 'C':
             c+=1
         elif character == 'T':
             t+=1
         elif character == 'A':
             a+=1
         else:
             print(f"Invalid base-pair in your Sequence: {character}")
             return None

     gc_cont = (g+c)/(a+g+t+c)*100
     print (f"The GC content is: {gc_cont}%")
     return gc_cont







From alan.gauld at btinternet.com  Sun Oct 13 09:38:43 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 13 Oct 2019 14:38:43 +0100
Subject: [Tutor] GC content: Help with if/else statements:
In-Reply-To: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
References: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
Message-ID: <97be14b8-1813-6f5c-9477-8715e31ed0fb@btinternet.com>

On 13/10/2019 06:17, Mihir Kharate wrote:

>     if character == 'A' or 'T' or 'G' or 'C':

Python doesn't see this the way you do.
It sees

if (character == 'A') or
   ('T' == true) or
   ('G' == True) or
   ('C' == True):

And it evaluates it from the leftmost expression, so first t checks if
character is 'A'. If not it then tests if 'T' is True. Now in python any
non-empty string is considered to be True, so it sees the second test as
True.

Now in an or expression Python stops evaluating conditions
when it finds a True expression. Thus it never evaluates the
last two expression(although they would always be True too)
and interprets the whole if expression as True and so never
enters the else clause.

You could change the code to

if character == 'A' or character == 'T'
   or character == 'G' or character == 'C':

But, as Joel has already pointed out a more Pythonic option
in this case is to use the in operator:

if character in ('A','T','G','C'):



> *Question 2*: When I use another if statement like below, it returns the GC
> content and "Invalid base-pair in your Sequence" both. No matter whether
> the input has any other characters than A,T,G,C or not.
> 
>     if character == 'A' or 'T' or 'G' or 'C':
>         print ("The GC content is: " + str(gc_cont) + " %")
>     if character is not 'A' or 'T' or 'G' or 'C':

Same problem again. Python sees this as

if (character is not 'A') or ('T' == True)....

With the same result as before. The fix is similar:

if character not in ('A','T','G','C')...

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


From tysonwbarber at gmail.com  Mon Oct 14 20:07:29 2019
From: tysonwbarber at gmail.com (Tyson Barber)
Date: Mon, 14 Oct 2019 20:07:29 -0400
Subject: [Tutor] Help on Python
Message-ID: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>

Hello Tutor,

I am new to Python and had a question.

incomevar = (input("Please enter the income: ")
            income = int(incomevar)
costvar = int(input("Please enter the cost: ")
            cost = int(costvar)
                if income >= cost :
                  print (income - cost == profit)
              else income < cost :
                  print (cost - income == loss)

I have tried many things for this to work, including changing the variable
names, spacing issues. Nothing seems to work and I am quite confused. I
honestly don't even know if this is the right email address to send this to.

Thank you,
Tyson Barber

From Richard at Damon-Family.org  Tue Oct 15 06:38:08 2019
From: Richard at Damon-Family.org (Richard Damon)
Date: Tue, 15 Oct 2019 06:38:08 -0400
Subject: [Tutor] Help on Python
In-Reply-To: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
Message-ID: <21333407-db64-1539-8455-acf6b4354e31@Damon-Family.org>

On 10/14/19 8:07 PM, Tyson Barber wrote:
> Hello Tutor,
>
> I am new to Python and had a question.
>
> incomevar = (input("Please enter the income: ")
>             income = int(incomevar)
> costvar = int(input("Please enter the cost: ")
>             cost = int(costvar)
>                 if income >= cost :
>                   print (income - cost == profit)
>               else income < cost :
>                   print (cost - income == loss)
>
> I have tried many things for this to work, including changing the variable
> names, spacing issues. Nothing seems to work and I am quite confused. I
> honestly don't even know if this is the right email address to send this to.
>
> Thank you,
> Tyson Barber
>
What are you expecting a line like

                  print (income - cost == profit)

to do, and why?

That statement says in python, compare the value of income - cost to the
value of profit, and print True or False depending on if they are equal
or not.


Also, in python spacing is important, lines should not be randomly
indented. All the statements should be at the same indent (probably no
indent), except those controlled by the if and else statements, which
should be indented a bit more than the if and else statements.


-- 
Richard Damon


From joel.goldstick at gmail.com  Tue Oct 15 06:49:02 2019
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 15 Oct 2019 06:49:02 -0400
Subject: [Tutor] Help on Python
In-Reply-To: <21333407-db64-1539-8455-acf6b4354e31@Damon-Family.org>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
 <21333407-db64-1539-8455-acf6b4354e31@Damon-Family.org>
Message-ID: <CAPM-O+ycA0R2J5BVqh5NM2iX70h5WFana-2pYUkqZdxDsve-OQ@mail.gmail.com>

On Tue, Oct 15, 2019 at 6:38 AM Richard Damon <Richard at damon-family.org> wrote:
>
> On 10/14/19 8:07 PM, Tyson Barber wrote:
> > Hello Tutor,
> >
> > I am new to Python and had a question.
> >
> > incomevar = (input("Please enter the income: ")
> >             income = int(incomevar)
> > costvar = int(input("Please enter the cost: ")
> >             cost = int(costvar)
> >                 if income >= cost :
> >                   print (income - cost == profit)
> >               else income < cost :
> >                   print (cost - income == loss)
> >
> > I have tried many things for this to work, including changing the variable
> > names, spacing issues. Nothing seems to work and I am quite confused. I
> > honestly don't even know if this is the right email address to send this to.
> >
> > Thank you,
> > Tyson Barber

You haven't asked a question.  The first thing I remember when trying
to learn python is the requirement of proper indentation.  Python
doesn't use braces like C and other languages.  Your spacing is wrong.
You should run your program, then cut and paste the traceback in your
message to this list. It provides information as to what is wrong.

From nulla.epistola at web.de  Tue Oct 15 07:34:41 2019
From: nulla.epistola at web.de (Sibylle Koczian)
Date: Tue, 15 Oct 2019 13:34:41 +0200
Subject: [Tutor] Help on Python
In-Reply-To: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
Message-ID: <00350db7-9854-3f09-6b8a-bba1dd959802@web.de>

Am 15.10.2019 um 02:07 schrieb Tyson Barber:
> Hello Tutor,
>
> I am new to Python and had a question.
>
> incomevar = (input("Please enter the income: ")
>              income = int(incomevar)
> costvar = int(input("Please enter the cost: ")
>              cost = int(costvar)
>                  if income >= cost :
>                    print (income - cost == profit)
>                else income < cost :
>                    print (cost - income == loss)
>
> I have tried many things for this to work, including changing the variable
> names, spacing issues. Nothing seems to work and I am quite confused. I
> honestly don't even know if this is the right email address to send this to.
>
It is.

In addition to the advice you already got: the line

else income < cost :

is syntactically wrong. It would be correct to write

elif income < cost:

but the elif isn't necessary. Income and cost are numbers, so either
income >= cost or income < cost. No third possibility. So you can and
should simply write

if income >= cost:
     # ...
else:
     # ...

Your print statements won't run either, because the variables profit and
loss aren't defined.


From osaosemwe at yahoo.com  Tue Oct 15 08:59:34 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Tue, 15 Oct 2019 12:59:34 +0000 (UTC)
Subject: [Tutor] loop print issue
In-Reply-To: <f7fd8201-5348-97cd-daf3-5f4f4c5dc28b@yahoo.co.uk>
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
 <1601109860.4879400.1570473067728@mail.yahoo.com>
 <38fc3078-e4b5-5c12-3e63-9e3def27165a@btinternet.com>
 <732029288.249778.1570806005876@mail.yahoo.com>
 <c9597a56-6c72-6636-9e42-cb0f2b0612c5@btinternet.com>
 <285143223.361687.1570818554091@mail.yahoo.com>
 <f7fd8201-5348-97cd-daf3-5f4f4c5dc28b@yahoo.co.uk>
Message-ID: <1628927034.1750880.1571144374780@mail.yahoo.com>

 Hello Alan,?
Thanks for the Idea. actually the input had 70 lines which contents I wanted to be used in a program and divided two outputs.?I used your idea although had to make a few tweaks to it, and it works as I wanted.?
Thanks,
Ose Osamudiamen
    On Friday, October 11, 2019, 08:08:39 PM EDT, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:  
 
 On 11/10/2019 19:29, ose micah wrote:

> Thanks for your initial answer, I do appreciate it only this does not
> give the needed results:

I don't think your code did what you wanted either. I simply showed a
cleaner way of doing what you were doing. But I don't think what you
were doing was what you wanted to do. Unfortunately you didn't say what
you wanted to do so I couldn't be sure.

> The output2.txt file has only one line (the last line) with your code.

I'm guessing your input file has 37 lines?

36 went to output1 and 1 to output2? Thats what the program
(both yours and mine) says to do...

> and output1.txt has the results all on a single line against line by
> line as my initial code.

In that case add a \n to the end of the write string...

> with open('output1.txt','w') as output1
> ?? for count in range(36):
> ?? ?? ?? output1.write(xlist_file.readline() + '\n')
> 
> with open('output2.txt','w') as output2:
> ?? for line in xlist_file:
> ?? ?? ?? output2 write(line+'\n')


> However, I have a sneaky suspicion this is not actually what
> you want to do. But either way it will almost certainly be
> easier if you stop abusing sys.stdout and just open two
> output files and write() to them!

If you don't just want the first 36 lines in output1 then you need to
tell us what you do want. How do you want to split the file?
I suspect you actually want to put the lines containing
line values <36 in one file and values >36 in the other.
Is that right?

If so it should look something like(untested):

with open('output1.txt,'w') as output1:
? with open('output2.txt','w') as output2:
? ? ? for line in xlist_file:
? ? ? ? ? if int(line) > 35:
? ? ? ? ? ? ? output1.write(line + '\n')
? ? ? ? ? else output2.write(line + '\n')



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

  

From mats at wichmann.us  Tue Oct 15 11:38:35 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 15 Oct 2019 09:38:35 -0600
Subject: [Tutor] Help on Python
In-Reply-To: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
Message-ID: <34dcf752-ff27-a1da-aeb7-5a3354b069c4@wichmann.us>

On 10/14/19 6:07 PM, Tyson Barber wrote:
> Hello Tutor,
> 
> I am new to Python and had a question.
> 
> incomevar = (input("Please enter the income: ")
>              income = int(incomevar)
> costvar = int(input("Please enter the cost: ")
>              cost = int(costvar)
>                  if income >= cost :
>                    print (income - cost == profit)
>                else income < cost :
>                    print (cost - income == loss)
> 
> I have tried many things for this to work, including changing the variable
> names, spacing issues. Nothing seems to work and I am quite confused. I
> honestly don't even know if this is the right email address to send this to.

Your comment on having tried spacing changes suggests you haven't yet 
grasped how it works, so let's try:

within a file, a code block is a piece of Python code that can be 
executed together - one or more statements.  For example, when you do a 
condition test (if statement), and the test evaluates true, then the 
things you do in that case are a "code block".  code blocks are indented 
- it's part of the Python syntax.  Your hint that a block is about to 
occur is a statement ending with a colon, so

if color == "red":
    do something that relates to that
    and another line
    and one more
this is no longer part of the code block.

that's the only time you should be indenting, so your other indents 
above are incorrect (some of the other replies have pointed this out as 
well).  code aligns consistently, then when there's a block, indent it; 
blocks can nest so there can be another layer of indentation, and another.

hope that helps clear things up a bit...

you have several erorrs above - most have already been pointed out. 
parentheses have to match, so the places you have two opening and one 
closing paren will always be syntax errors.



From david at lowryduda.com  Tue Oct 15 11:44:52 2019
From: david at lowryduda.com (David Lowry-Duda)
Date: Tue, 15 Oct 2019 11:44:52 -0400
Subject: [Tutor] Help on Python
In-Reply-To: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
Message-ID: <20191015154452.GA19587@icerm-dld>

Hello Tyson,

You have found the right email and come to the right place.

> I am new to Python and had a question.
> 
> incomevar = (input("Please enter the income: ")
>             income = int(incomevar)
> costvar = int(input("Please enter the cost: ")
>             cost = int(costvar)
>                 if income >= cost :
>                   print (income - cost == profit)
>               else income < cost :
>                   print (cost - income == loss)
> 
> I have tried many things for this to work, including changing the variable
> names, spacing issues. Nothing seems to work and I am quite confused. I
> honestly don't even know if this is the right email address to send 
> this to.

To get a good response, I suggest you give a bit of additional info. In 
particular, I suggest that you add

- what you are trying to do
- what you expect your program to run and do
- the output of your program when it runs (or the error if an error is 
  produced)

This advice applies not only to this post, but any future questions you 
might give to any programming-help environment.

With your post --- with proper indentation, I expect that your program 
would not run because `profit` and `loss` are not defined.

Good luck!

- DLD

--
David Lowry-Duda <david at lowryduda.com> <davidlowryduda.com>

From stephen.m.smith at comcast.net  Tue Oct 15 14:03:23 2019
From: stephen.m.smith at comcast.net (stephen.m.smith at comcast.net)
Date: Tue, 15 Oct 2019 14:03:23 -0400
Subject: [Tutor] Help on Python
In-Reply-To: <20191015154452.GA19587@icerm-dld>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
 <20191015154452.GA19587@icerm-dld>
Message-ID: <001b01d58382$d6e6e160$84b4a420$@comcast.net>

I looked at your few lines and made an assumption or two. Pretty sure this
does what you want:

incomevar = input("Please enter the income: ")
income = int(incomevar)
costvar = input("Please enter the cost: ")
cost = int(costvar)
if income >= cost :
    print("Profit = ",income - cost)
else:
    print ("Loss = ", cost - income)

However, there is some stuff in there you don't need. This works as well and
is a little more efficient and elegant:

income = input("Please enter the income: ")
cost = input("Please enter the cost: ")
result = int(income) - int(cost)
if result > 0:
    print("Profit = ",result)
elif result < 0:
    print ("Loss = ", result)
else:
    print("There was no profit, Income = Expenses!")

Good luck!
-----Original Message-----
From: Tutor <tutor-bounces+stephen.m.smith=comcast.net at python.org> On Behalf
Of David Lowry-Duda
Sent: Tuesday, October 15, 2019 11:45 AM
To: tutor at python.org
Subject: Re: [Tutor] Help on Python

Hello Tyson,

You have found the right email and come to the right place.

> I am new to Python and had a question.
> 
> incomevar = (input("Please enter the income: ")
>             income = int(incomevar)
> costvar = int(input("Please enter the cost: ")
>             cost = int(costvar)
>                 if income >= cost :
>                   print (income - cost == profit)
>               else income < cost :
>                   print (cost - income == loss)
> 
> I have tried many things for this to work, including changing the 
> variable names, spacing issues. Nothing seems to work and I am quite 
> confused. I honestly don't even know if this is the right email 
> address to send this to.

To get a good response, I suggest you give a bit of additional info. In
particular, I suggest that you add

- what you are trying to do
- what you expect your program to run and do
- the output of your program when it runs (or the error if an error is
  produced)

This advice applies not only to this post, but any future questions you
might give to any programming-help environment.

With your post --- with proper indentation, I expect that your program would
not run because `profit` and `loss` are not defined.

Good luck!

- DLD

--
David Lowry-Duda <david at lowryduda.com> <davidlowryduda.com>
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


From stephen.m.smith at comcast.net  Tue Oct 15 14:23:45 2019
From: stephen.m.smith at comcast.net (stephen.m.smith at comcast.net)
Date: Tue, 15 Oct 2019 14:23:45 -0400
Subject: [Tutor] Help on Python
In-Reply-To: <001b01d58382$d6e6e160$84b4a420$@comcast.net>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
 <20191015154452.GA19587@icerm-dld>
 <001b01d58382$d6e6e160$84b4a420$@comcast.net>
Message-ID: <003401d58385$af144d50$0d3ce7f0$@comcast.net>

Not exactly sure why, but the system removed some line feeds that need to be
in there.

Here is the code sent:



-----Original Message-----
From: Tutor <tutor-bounces+stephen.m.smith=comcast.net at python.org> On Behalf
Of stephen.m.smith at comcast.net
Sent: Tuesday, October 15, 2019 2:03 PM
To: 'David Lowry-Duda' <david at lowryduda.com>; tutor at python.org
Subject: Re: [Tutor] Help on Python

I looked at your few lines and made an assumption or two. Pretty sure this
does what you want:

incomevar = input("Please enter the income: ") income = int(incomevar)
costvar = input("Please enter the cost: ") cost = int(costvar) if income >=
cost :
    print("Profit = ",income - cost)
else:
    print ("Loss = ", cost - income)

However, there is some stuff in there you don't need. This works as well and
is a little more efficient and elegant:

income = input("Please enter the income: ") cost = input("Please enter the
cost: ") result = int(income) - int(cost) if result > 0:
    print("Profit = ",result)
elif result < 0:
    print ("Loss = ", result)
else:
    print("There was no profit, Income = Expenses!")

Good luck!
-----Original Message-----
From: Tutor <tutor-bounces+stephen.m.smith=comcast.net at python.org> On Behalf
Of David Lowry-Duda
Sent: Tuesday, October 15, 2019 11:45 AM
To: tutor at python.org
Subject: Re: [Tutor] Help on Python

Hello Tyson,

You have found the right email and come to the right place.

> I am new to Python and had a question.
> 
> incomevar = (input("Please enter the income: ")
>             income = int(incomevar)
> costvar = int(input("Please enter the cost: ")
>             cost = int(costvar)
>                 if income >= cost :
>                   print (income - cost == profit)
>               else income < cost :
>                   print (cost - income == loss)
> 
> I have tried many things for this to work, including changing the 
> variable names, spacing issues. Nothing seems to work and I am quite 
> confused. I honestly don't even know if this is the right email 
> address to send this to.

To get a good response, I suggest you give a bit of additional info. In
particular, I suggest that you add

- what you are trying to do
- what you expect your program to run and do
- the output of your program when it runs (or the error if an error is
  produced)

This advice applies not only to this post, but any future questions you
might give to any programming-help environment.

With your post --- with proper indentation, I expect that your program would
not run because `profit` and `loss` are not defined.

Good luck!

- DLD

--
David Lowry-Duda <david at lowryduda.com> <davidlowryduda.com>
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: temp2.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20191015/fb8fb645/attachment.ksh>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: temp.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20191015/fb8fb645/attachment-0001.ksh>

From alan.gauld at yahoo.co.uk  Tue Oct 15 20:21:14 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 16 Oct 2019 01:21:14 +0100
Subject: [Tutor] Help on Python
In-Reply-To: <CAK__PGPap87rygh78_Nt1WzPx7Vm62NYr+T9MTGVR52kEX=foQ@mail.gmail.com>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
 <f2ed57bd-cee9-3eee-d2bc-b4fe8c754b76@btinternet.com>
 <CAK__PGPap87rygh78_Nt1WzPx7Vm62NYr+T9MTGVR52kEX=foQ@mail.gmail.com>
Message-ID: <9823e876-9ae5-e9cf-1130-a92bd542ee6e@yahoo.co.uk>

You have to use reply-All or reply-List to reply to the list,
otherwise it just goes to the original sender.


On 16/10/2019 00:46, Tyson Barber wrote:
> I have tweaked the code slightly to look like this:
> 
> income = (input("Please enter the income: "))

You haven't converted to int. Use the same pattern
you use in the next line.

> cost = int(input("Please enter the cost: "))
> if income >= cost :
> ?? ?? ?? ?? print (income - cost == profit)

Your print is still trying to print the boolean result of the expression

income - cost == profit

And you have not defined profit yet so this will
yield errors if it ever gets this far.


> else:
> ?? ?? income < cost :?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ??

The else syntax is simply

else:
   # code here that gets executed when the preceding if fails
   # You cannot have an expression with a colon on its own.
   # That's invalid Python.


> ?? ?? ?? ?? print (cost - income == loss)

Same as above you are trying to print the boolean expression result.

You probably want to add a string here like:

print ("cost - income ==", cost-income)


Or on two lines:

loss = cost-income
print(loss)

> in the line after the else statement, it is giving me an error message
> of invalid syntax (where the red is).

This is a text only list so binary attachments get stripped out.
You need to paste the full error text into the mail message.
Starting with the line:

Traceback (most recent call last):
...

> It does not give me a syntax error for the other line that is similar to
> it earlier (highlighted in yellow).

I can't see the colours but expect it is that else statement
 - or more precisely the expression following it.

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


From tysonwbarber at gmail.com  Tue Oct 15 20:20:28 2019
From: tysonwbarber at gmail.com (Tyson Barber)
Date: Tue, 15 Oct 2019 20:20:28 -0400
Subject: [Tutor] Help on Python
In-Reply-To: <9823e876-9ae5-e9cf-1130-a92bd542ee6e@yahoo.co.uk>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
 <f2ed57bd-cee9-3eee-d2bc-b4fe8c754b76@btinternet.com>
 <CAK__PGPap87rygh78_Nt1WzPx7Vm62NYr+T9MTGVR52kEX=foQ@mail.gmail.com>
 <9823e876-9ae5-e9cf-1130-a92bd542ee6e@yahoo.co.uk>
Message-ID: <CAK__PGMdtA_E9AWzONkeCJBDq8AV4=pOgiZk7Dp97tkAsJRU9A@mail.gmail.com>

Tyson Barber <tysonwbarber at gmail.com>
7:46 PM (32 minutes ago)
to *alan.gauld*
Hi Python Help,

Sorry about the confusion of my last email, this is my first time using
this method of help.

I have tweaked the code slightly to look like this:

income = (input("Please enter the income: "))
cost = int(input("Please enter the cost: "))
if income >= cost :
        print (income - cost == profit)
else:
    income < cost :
        print (cost - income == loss)

in the line after the else statement, it is giving me an error message of
invalid syntax (where the red is).

It does not give me a syntax error for the other line that is similar to it
earlier (highlighted in yellow).

Is it still a spacing issue, or is it possibly something with the text?

Thank you,

Tyson Barber

On Tue, Oct 15, 2019 at 8:21 PM Alan Gauld <alan.gauld at yahoo.co.uk> wrote:

> You have to use reply-All or reply-List to reply to the list,
> otherwise it just goes to the original sender.
>
>
> On 16/10/2019 00:46, Tyson Barber wrote:
> > I have tweaked the code slightly to look like this:
> >
> > income = (input("Please enter the income: "))
>
> You haven't converted to int. Use the same pattern
> you use in the next line.
>
> > cost = int(input("Please enter the cost: "))
> > if income >= cost :
> > ?? ?? ?? ?? print (income - cost == profit)
>
> Your print is still trying to print the boolean result of the expression
>
> income - cost == profit
>
> And you have not defined profit yet so this will
> yield errors if it ever gets this far.
>
>
> > else:
> > ?? ?? income < cost :?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ??
>
> The else syntax is simply
>
> else:
>    # code here that gets executed when the preceding if fails
>    # You cannot have an expression with a colon on its own.
>    # That's invalid Python.
>
>
> > ?? ?? ?? ?? print (cost - income == loss)
>
> Same as above you are trying to print the boolean expression result.
>
> You probably want to add a string here like:
>
> print ("cost - income ==", cost-income)
>
>
> Or on two lines:
>
> loss = cost-income
> print(loss)
>
> > in the line after the else statement, it is giving me an error message
> > of invalid syntax (where the red is).
>
> This is a text only list so binary attachments get stripped out.
> You need to paste the full error text into the mail message.
> Starting with the line:
>
> Traceback (most recent call last):
> ...
>
> > It does not give me a syntax error for the other line that is similar to
> > it earlier (highlighted in yellow).
>
> I can't see the colours but expect it is that else statement
>  - or more precisely the expression following it.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>

From tysonwbarber at gmail.com  Tue Oct 15 23:24:45 2019
From: tysonwbarber at gmail.com (Tyson Barber)
Date: Tue, 15 Oct 2019 23:24:45 -0400
Subject: [Tutor] Invalid Syntax Error
Message-ID: <CAK__PGPnOhvFx96aZpAbbUNLzZZn-vTwX_8=twcozomnd3T9DA@mail.gmail.com>

Hello Python Help!
I am trying to make a video game selector for my friend since he never
knows what to play and I thought it would be interesting to give him a
little simple Python code! In the code however there is a syntax error
(highlighted in yellow) and I was wondering if it was because I had to
declare it as a string? I was taught that it was automatically declared as
a string so I do not know where I went wrong?
print ("Welcome to the Video Game Selector!")
print ("Please decide between fps, sports, rpg or battle royale!")
genre = input("Please enter your preferred genre of video games: ")
if result = ("fps"):
    print ("Call of Duty MW, Battlefield V, Fallout 76, Gears of War 5")
elif result = ("sports"):
    print ("NBA 2K20, NHL 20, Madden 20, FIFA 20")
elif result = ("rpg"):
    print ("Skyrim, The Witcher, World of Warcraft")
elif result = ("battle royale"):
    print = ("Fortnite, APEX Legends, PUBG")
else:
    print = ("Sorry, that is not in the database.\n Try using a keyword!")

Thank you,
Tyson Barber

From cs at cskk.id.au  Wed Oct 16 04:39:16 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Wed, 16 Oct 2019 19:39:16 +1100
Subject: [Tutor] Help on Python
In-Reply-To: <CAK__PGMdtA_E9AWzONkeCJBDq8AV4=pOgiZk7Dp97tkAsJRU9A@mail.gmail.com>
References: <CAK__PGMdtA_E9AWzONkeCJBDq8AV4=pOgiZk7Dp97tkAsJRU9A@mail.gmail.com>
Message-ID: <20191016083916.GA63180@cskk.homeip.net>

We use the inline reply style in this list. Remarks are inline below the 
relevant parts of your email. Please do the same in your replies.

On 15Oct2019 20:20, Tyson Barber <tysonwbarber at gmail.com> wrote:
>Sorry about the confusion of my last email, this is my first time using
>this method of help.
>
>I have tweaked the code slightly to look like this:
>
>income = (input("Please enter the income: "))
>cost = int(input("Please enter the cost: "))
>if income >= cost :
>        print (income - cost == profit)
>else:
>    income < cost :
>        print (cost - income == loss)
>
>in the line after the else statement, it is giving me an error message of
>invalid syntax (where the red is).

This is a plain text mailing list. There are no colour here. I expect 
your error message concenrs this line:

    income < cost :

That is not a legal Python statement (hence the error). It should look 
like this:

    if income < cost :

However, because it is immediate in the "else" part Python has a 
convenient shorter version, where you replace this:

    else:
        if income < cost :
            print (cost - income == loss)

with this:

    elif income < cost :
            print (cost - income == loss)

The other point (already made by someone else in this list) is that:

    income < cost

is the dual of:

    income >= cost

so you don't really need the second test at all. You could just write:

if income >= cost :
        print (income - cost == profit)
else:
        print (cost - income == loss)

because in the "else" part it _must_ already be the case that income < 
cost.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From cs at cskk.id.au  Wed Oct 16 04:46:05 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Wed, 16 Oct 2019 19:46:05 +1100
Subject: [Tutor] Invalid Syntax Error
In-Reply-To: <CAK__PGPnOhvFx96aZpAbbUNLzZZn-vTwX_8=twcozomnd3T9DA@mail.gmail.com>
References: <CAK__PGPnOhvFx96aZpAbbUNLzZZn-vTwX_8=twcozomnd3T9DA@mail.gmail.com>
Message-ID: <20191016084605.GA85813@cskk.homeip.net>

On 15Oct2019 23:24, Tyson Barber <tysonwbarber at gmail.com> wrote:
>I am trying to make a video game selector for my friend since he never
>knows what to play and I thought it would be interesting to give him a
>little simple Python code! In the code however there is a syntax error
>(highlighted in yellow)

As mentioned, this is a plain text list. We don't see any colour 
highlighting you supply.

>and I was wondering if it was because I had to
>declare it as a string? I was taught that it was automatically declared as
>a string so I do not know where I went wrong?

You don't have to declare variables in Python, and they do not have 
fixed types. Their _values_ have types though; a variable is a reference 
to a value.

To the code itself:

>print ("Welcome to the Video Game Selector!")
>print ("Please decide between fps, sports, rpg or battle royale!")
>genre = input("Please enter your preferred genre of video games: ")

Ok, the return value from input() is a string. Which is fine.

>if result = ("fps"):

The primary problem here is that a single equals ("=") is for variable 
assignments. Comparison is spelt with two equals ("==") thus:

    if result == ("fps"):

You also do not need the brackets:

    if result == "fps":

>    print ("Call of Duty MW, Battlefield V, Fallout 76, Gears of War 5")
>elif result = ("sports"):
>    print ("NBA 2K20, NHL 20, Madden 20, FIFA 20")
>elif result = ("rpg"):
>    print ("Skyrim, The Witcher, World of Warcraft")
>elif result = ("battle royale"):
>    print = ("Fortnite, APEX Legends, PUBG")

You don't want the "=" in the print call. print() is just a function 
call, so:

    print ("Fortnite, APEX Legends, PUBG")

>else:
>    print = ("Sorry, that is not in the database.\n Try using a 
>    keyword!")

Cheers,
Cameron Simpson <cs at cskk.id.au>

From mats at wichmann.us  Wed Oct 16 12:03:19 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 16 Oct 2019 10:03:19 -0600
Subject: [Tutor] dynamical program to create subnets CIDR
In-Reply-To: <1601109860.4879400.1570473067728@mail.yahoo.com>
References: <1601109860.4879400.1570473067728.ref@mail.yahoo.com>
 <1601109860.4879400.1570473067728@mail.yahoo.com>
Message-ID: <90248a32-b75c-f3a4-4658-f17e6f0d26bb@wichmann.us>

On 10/7/19 12:31 PM, ose micah via Tutor wrote:
> Hello All,
> Can anyone help with a program that could compare a list of IPs and create the least possible CIDR block sets from these IPs.
> for example.
> I have a list say:
> 202.238.149.0/22202.238.164.0/22202.238.168.0/23202.238.176.0/20202.238.174.0/23202.238.172.0/2320.226.12.224/2720.223.14.0/2410.32.0.0/1510.35.0.0/1610.54.63.128/2610.59.250.0/2610.224.0.0/2410.228.69.0/24
> I want to reduce this list to:
> 10.32.0.0/14202.238.149.0/19
> 10.224.0.0/1310.54.63.0/13
> 
> Thanks
> Ose Micah

don't know if this ever got resolved satisfactorily, but I ought to have 
piped in with the observation that there are existing tools for dealing 
with IP addresses in Python, which was part of the problem expressed 
here (I realize there was also a file-reading-and-processing part). A 
couple here:

https://pypi.org/project/iptools/
https://pypi.org/project/netaddr/

and some further hunting will probably turn up more.

Also don't forget the standard library's ipaddress module.

From andre.luis.m.pinto at gmail.com  Wed Oct 16 17:09:04 2019
From: andre.luis.m.pinto at gmail.com (=?iso-8859-1?Q?Andr=E9_Pinto?=)
Date: Wed, 16 Oct 2019 18:09:04 -0300
Subject: [Tutor] Please help me on Python Code
Message-ID: <012a01d58465$f2b46690$d81d33b0$@gmail.com>

Dear.

 

I have a question and I can't solve it.

I need to average 40,000 items in a dataset and for each item I have 4
different conditioners.

I am writing the code as follows, but I am not achieving my goal which is to
classify the item according to its conditional, it should get the number 1
or the number zero and at the end the sum of them in a last column in the
dataset.

What is the best solution to this question? My code is:

 

def media6(dataset):

                val6 = 10  

if 0 < dataset['43709'].isin([dataset]).all():

                val6 = 1

elif 43709 > dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                 val6 = 1

elif 43709 > dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 <
dataset['43739'].isin([dataset]).all():

                 val6 = 1

else:

                val6 = 0

return (val6)

 

def media5(dataset):

val5 = 9

                if 0 < dataset['43678'].isin([dataset]).all():

                 val5 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val5 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43709',
'43739'].isin([dataset]).all():

                val5 = 1

                else:

                val5 = 0

                return (media5)    

 

def media4(dataset):

                 val4 = 8

                if 0 < dataset['43647'].isin([dataset]).all():

                val4 = 1

                elif 43647 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
(dataset['Saldo_Estoque']).isin([dataset]).all():

                val4 = 1

                elif 43647 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
(dataset['Saldo_Estoque']).isin([dataset]).all() and 0 < dataset['43678',
'43709', '43739'].isin([dataset]).all():

                val4 = 1

                else:

                val4 = 0

                return (media4)

 

def media3(dataset):

                val3 = 7

                if 0 < dataset['43617'].isin([dataset]).all():

                val3 = 1

                elif 43617 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val3 = 1

                elif 43617 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43647',
'43678', '43709', '43739'].isin([dataset]).all():

                val3 = 1

                else:

                val3 = 0

                return (media3)

 

def media2(dataset):

                val2 = 6

                if 0 < dataset['43678'].isin([dataset]).all():

                val2 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val2 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43617',
'43647', '43678', '43709', '43739'].isin([dataset]).all():

                val2 = 1

                else:

                val2 = 0

                return (media2)

 

def media1(dataset):

                val1 = 5

                if 0 < dataset['43556'].isin([dataset]).all():

                val1 = 1

                elif 43556 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val1 = 1

                elif 43556 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43678',
'43617', '43647', '43678', '43709', '43739'].isin([dataset]).all():

                val1 = 1

                else:

                val1 = 0

                return (media1)

 

dataset[?MEDIA?] = (media6 + media5 + media4 + media3 + media2 + media1)

 

Waiting your help to solve this problem. Thank you very much.

 

 

Com os cumprimentos

Best Regards

Atentos Saludos

 

Andr? Lu?s M. Pinto

* +55 (71) 98802-6841

Skype ID:  <mailto:andre.luis.m.pinto at outlook.com>
andre.luis.m.pinto at outlook.com

P Antes de imprimir pense em seu comprimisso com o Meio Ambiente.

 

 



-- 
Este email foi escaneado pelo Avast antiv?rus.
https://www.avast.com/antivirus

From andre.luis.m.pinto at gmail.com  Wed Oct 16 17:20:11 2019
From: andre.luis.m.pinto at gmail.com (=?iso-8859-1?Q?Andr=E9_Pinto?=)
Date: Wed, 16 Oct 2019 18:20:11 -0300
Subject: [Tutor] Please help me on Python Code
Message-ID: <000301d58467$7fae1270$7f0a3750$@gmail.com>

Dear.

 

I have a question and I can't solve it.

I need to average 40,000 items in a dataset and for each item I have 4
different conditioners.

I am writing the code as follows, but I am not achieving my goal which is to
classify the item according to its conditional, it should get the number 1
or the number zero and at the end the sum of them in a last column in the
dataset.

What is the best solution to this question? My code is:

 

def media6(dataset):

                val6 = 10  

if 0 < dataset['43709'].isin([dataset]).all():

                val6 = 1

elif 43709 > dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                 val6 = 1

elif 43709 > dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 <
dataset['43739'].isin([dataset]).all():

                 val6 = 1

else:

                val6 = 0

return (val6)

 

def media5(dataset):

val5 = 9

                if 0 < dataset['43678'].isin([dataset]).all():

                 val5 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val5 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43709',
'43739'].isin([dataset]).all():

                val5 = 1

                else:

                val5 = 0

                return (media5)    

 

def media4(dataset):

                 val4 = 8

                if 0 < dataset['43647'].isin([dataset]).all():

                val4 = 1

                elif 43647 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
(dataset['Saldo_Estoque']).isin([dataset]).all():

                val4 = 1

                elif 43647 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
(dataset['Saldo_Estoque']).isin([dataset]).all() and 0 < dataset['43678',
'43709', '43739'].isin([dataset]).all():

                val4 = 1

                else:

                val4 = 0

                return (media4)

 

def media3(dataset):

                val3 = 7

                if 0 < dataset['43617'].isin([dataset]).all():

                val3 = 1

                elif 43617 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val3 = 1

                elif 43617 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43647',
'43678', '43709', '43739'].isin([dataset]).all():

                val3 = 1

                else:

                val3 = 0

                return (media3)

 

def media2(dataset):

                val2 = 6

                if 0 < dataset['43678'].isin([dataset]).all():

                val2 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val2 = 1

                elif 43678 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43617',
'43647', '43678', '43709', '43739'].isin([dataset]).all():

                val2 = 1

                else:

                val2 = 0

                return (media2)

 

def media1(dataset):

                val1 = 5

                if 0 < dataset['43556'].isin([dataset]).all():

                val1 = 1

                elif 43556 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 <
dataset['Saldo_Estoque'].isin([dataset]).all():

                val1 = 1

                elif 43556 >
dataset['Data_Ultima_Entrada'].isin([dataset]).all() and 0 ==
dataset['Saldo_Estoque'].isin([dataset]).all() and 0 < dataset['43678',
'43617', '43647', '43678', '43709', '43739'].isin([dataset]).all():

                val1 = 1

                else:

                val1 = 0

                return (media1)

 

dataset[?MEDIA?] = (media6 + media5 + media4 + media3 + media2 + media1)

 

Waiting your help to solve this problem. Thank you very much.

 

 

Com os cumprimentos

Best Regards

Atentos Saludos

 

Andr? Lu?s M. Pinto

* +55 (71) 98802-6841

Skype ID:  <mailto:andre.luis.m.pinto at outlook.com>
andre.luis.m.pinto at outlook.com

P Antes de imprimir pense em seu comprimisso com o Meio Ambiente.

 

 



-- 
Este email foi escaneado pelo Avast antiv?rus.
https://www.avast.com/antivirus

From mats at wichmann.us  Wed Oct 16 19:12:35 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 16 Oct 2019 17:12:35 -0600
Subject: [Tutor] Please help me on Python Code
In-Reply-To: <000301d58467$7fae1270$7f0a3750$@gmail.com>
References: <000301d58467$7fae1270$7f0a3750$@gmail.com>
Message-ID: <86f11110-5c0d-b0cd-8b98-f4279ea4c14d@wichmann.us>

On 10/16/19 3:20 PM, Andr? Pinto wrote:
> Dear.
> 
>   
> 
> I have a question and I can't solve it.
> 
> I need to average 40,000 items in a dataset and for each item I have 4
> different conditioners.
> 
> I am writing the code as follows, but I am not achieving my goal which is to
> classify the item according to its conditional, it should get the number 1
> or the number zero and at the end the sum of them in a last column in the
> dataset.
> 
> What is the best solution to this question? My code is:


sorry, we can't solve this for you, because there is too much missing 
information.  I'll give you the benefit of the doubt about the horribly 
formatted code, which can't possibly run as it appears in this email, 
and assume that the process of getting the code into the email, or your 
email program itself, broke that part of it.  You don't say in what way 
you're not achieving the goal: is Python telling you your program has 
errors and so isn't running it?  Or are you not getting the results you 
want?

here are two reactions:

> 
>   
> 
> def media6(dataset):
> 
>                  val6 = 10
> 
> if 0 < dataset['43709'].isin([dataset]).all():

1/  dataset looks like it is an instance of a class, but we know nothing 
all about that class, so .isin and .all might or might not be doing 
anything useful for you.

[lots clipped]

> dataset[?MEDIA?] = (media6 + media5 + media4 + media3 + media2 + media1)

You define these six functions, but just listing them by name doesn't 
call them, so the functions are never being called.  This will certainly 
make your program do something different than you are expecting.

Here is a short interactive sesssion that shows that concept in action:

 >>> def funcA():
...     return 10
...
 >>> def funcB():
...     return 20
...
 >>>
 >>> x = (funcA + funcB)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'function' and 'function'
 >>>
 >>> x = funcA() + funcB()
 >>> print(x)
30
 >>>



From andre.luis.m.pinto at gmail.com  Thu Oct 17 08:07:53 2019
From: andre.luis.m.pinto at gmail.com (=?utf-8?Q?Andr=C3=A9_Pinto?=)
Date: Thu, 17 Oct 2019 09:07:53 -0300
Subject: [Tutor] Help me on Python Code
Message-ID: <000001d584e3$827e8530$877b8f90$@gmail.com>

Dear Mats Wichman

 

I transformed the columns "date" into number to make it easier to logically compare the values ??of this column with the dates (entry and registration) of items in the dataset.

As there are 40000 items, I need to separate those that meet each of the conditions, reading them line by line (ie item by item), comparing their values ??and then adding the results obtained from these conditions (1 = meets the condition) and (0 = not meeting condition).

 

Enclosed you have my Jupyter notebook file. I already sent the csv format data file in your email.

 

Thank you for your help. If it is possible we can talk via Skype and share screen to solve this problem I have here.

 

 

Com os cumprimentos

Best Regards

Atentos Saludos

 

Andr? Lu?s M. Pinto

Skype ID:  <mailto:andre.luis.m.pinto at outlook.com> andre.luis.m.pinto at outlook.com

P Antes de imprimir pense em seu comprimisso com o Meio Ambiente.

 

 

 

 

 

 



-- 
Este email foi escaneado pelo Avast antiv?rus.
https://www.avast.com/antivirus

From eggo at hotmail.com  Fri Oct 18 14:38:19 2019
From: eggo at hotmail.com (Eggo why)
Date: Fri, 18 Oct 2019 18:38:19 +0000
Subject: [Tutor] how to do this using psycopg2
Message-ID: <CH2PR01MB597397A4410BF0018E202B7AC56C0@CH2PR01MB5973.prod.exchangelabs.com>

Hi all,
     I have following python code  but when perform execute got error due to signal quote.  How can I prepare the query without the signal quote?


sql = ("alter table %s rename to %s")
print(cur.mogrify(sql, (str_tab, tab_b)))
cur.execute(sql, (str_tab, tab_b))


b"alter table 't_win_sys_data_consolidated' rename to 't_win_sys_data_consolidated_B'"
can't adapt type 'SyntaxError'
syntax error at or near "'t_all_remedy_asset_data'"
LINE 1: alter table 't_all_remedy_asset_data' rename to 't_all_remed...

From james.londonsw15 at gmail.com  Fri Oct 18 18:03:40 2019
From: james.londonsw15 at gmail.com (James Austin)
Date: Fri, 18 Oct 2019 23:03:40 +0100
Subject: [Tutor] Deleting items from a shelve file when items are unknown
Message-ID: <cbe07c70-5d34-f380-f08f-9a4ada0a3df3@gmail.com>

Hello list

I am quite new? to Python, so please bare with me.

I am developing a basic clipboard application that saves text to a 
keyword and lists the saved items for the user. Users will then be able 
to paste saved text into an external? application by using the keyword 
they first assigned. Saved data is stored in a Shelve file. I have a 
working prototype for the 'save' and 'list' features of the program. 
Currently this program is command line only.

Before adding the 'paste' feature, I am working on implementing a way 
for users to delete keywords and text they no longer want. This is where 
I hope the list can advise? please. I am trying to write code that will 
allow the user to delete **any** keyword that they find in the list. A 
portion of my code is below and below that is a brief summary of what I 
have tried so far:


---snip---

# Delete keywords/comments

elif len(sys.argv) == 2 and sys.argv[1] == 'delete':

 ? if clipboardShelf[sys.argv[2]] in clipboardShelf.keys():

 ?? clipboardShelf.pop()


This code does not throw errors when tested with: python clipboard.py. 
However, when I run python clipboard.py list, the keyword remains in the 
shelve file.


Although my understanding is limited, I believe, from what I have read, 
that shelve files act like dictionaries. However, using the 'del' option 
yields the same result.

I have tried several variations including the following 'for' loop:

---snip---

elif len(sys.argv) == 2 and sys.argv[1] == 'delete':

 ? for key in clipboardShelf.keys():

 ?? del clipboardShelf['']


I have also tried signifying the unknown key with empty brackets.

I hope I have provided enough context for someone to help. I suspect 
that I have misunderstood something or am overthinking what may be a 
very simple solution.

Thank you for any and all help? offered.


Best wishes

James


From rwalker2007 at verizon.net  Sat Oct 19 07:02:18 2019
From: rwalker2007 at verizon.net (Ronald Walker)
Date: Sat, 19 Oct 2019 04:02:18 -0700
Subject: [Tutor] Need Help!
Message-ID: <000001d5866c$ad483c40$07d8b4c0$@verizon.net>

I am uninitiated with computers and with computer speak.

 

I would very much appreciate some help at a primary level.

 

I am trying to learn Python because most of the research I did on
programming languages suggest that Python is supposed to be quite easy to
learn. However, in reading Python materials it seems to assume that I know
what they are talking about and am familiar with the jargon and many other
matters.

 

I am not.

 

For example I have found how to use the help function in Python. However, in
reading it, I cannot understand what it is trying to communicate.

 

If I do 

 

dir(str)

 

I get a whole list of "methods" available for the str function.

 

So then I :type 

 

help(str.count)

 

This is what I get:

 

Help on method_descriptor:

 

count(...)

    S.count(sub[, start[, end]]) -> int

    

    Return the number of non-overlapping occurrences of substring sub in

    string S[start:end].  Optional arguments start and end are

    interpreted as in slice notation.

 

This is completely unintelligible to me.

How would I use this? 

What does

S.count(sub[,start[, end[]] -> int

Mean?

What does 

Return the number of non-overlapping occurrences of substring sub in

    string S[start:end].  Optional arguments start and end are

    interpreted as in slice notation.

Mean?

 

It is English. And I am quite literate in English. But this English is not
using English vocabulary and syntax in a way that I can semantically
understand.

 

How can this help me? 

 

I want to find some actual concrete Python code from an actual working
program that explains what all this means!

 

Remember diagramming sentences? I am a native English speaker and I look at
a sentence diagram and cannot figure out what is happening unless I am
schooled in how to read and construct sentence diagrams. Remember that
diagraming sentences is separate and apart from learning to speak and write
English.

 

This is how I feel with getting help from the Python help and other Python
and computer documentation

 

This is what I might get if I did a help for verb tense for English and I
got back a help like I get in Python:

 

Help(verb.tense) 

 

v.conjugation [tense, person, number] [voice] [mood]

 

OK. So I want help on constructing verb tense for the word sing. How does
this help me?

 

Do you see my confusion?

 

Can anyone provide some clarity and direction for material that could "help"
my understanding?


From cs at cskk.id.au  Sat Oct 19 18:09:31 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Sun, 20 Oct 2019 09:09:31 +1100
Subject: [Tutor] Deleting items from a shelve file when items are unknown
In-Reply-To: <cbe07c70-5d34-f380-f08f-9a4ada0a3df3@gmail.com>
References: <cbe07c70-5d34-f380-f08f-9a4ada0a3df3@gmail.com>
Message-ID: <20191019220931.GA53248@cskk.homeip.net>

On 18Oct2019 23:03, James Austin <james.londonsw15 at gmail.com> wrote:
>I am quite new? to Python, so please bare with me.

I'd rather remain clothed, but I'm happy to bear with you.

>I am developing a basic clipboard application that saves text to a 
>keyword and lists the saved items for the user. Users will then be 
>able to paste saved text into an external? application by using the 
>keyword they first assigned. Saved data is stored in a Shelve file.

I _presume_ you mean Shelf objects from the "shelve" module? Please 
verify that.

>I have a working prototype for the 'save' and 'list' features of the 
>program. Currently this program is command line only.

Command line programmes are easy to use with scripts and easier to debug 
than GUIs. Always a good starting point.

>Before adding the 'paste' feature, I am working on implementing a way 
>for users to delete keywords and text they no longer want. This is 
>where I hope the list can advise? please. I am trying to write code 
>that will allow the user to delete **any** keyword that they find in 
>the list. A portion of my code is below and below that is a brief 
>summary of what I have tried so far:
>
>---snip---
># Delete keywords/comments
>elif len(sys.argv) == 2 and sys.argv[1] == 'delete':
>? if clipboardShelf[sys.argv[2]] in clipboardShelf.keys():
>?? clipboardShelf.pop()

Problem 1: if you have sys.argv[2], then len(sys.argv) is at least 3 
(elements 0,1,2).

Personally I tend to pop things off sys.argv progressively so that they 
can get nice names:

    cmd = sys.argv.pop(0)   # command name
    op = sys.argv.pop(0)    # operation
    if op == 'delete':
        key = sys.argv.pop(0)

This has the advantage of not hardwiring argument positions into your 
code. (Suppose you latter add some option parsing ahead of the 'delete' 
operation word?) It also mades the code more readable ("key" instead of 
"sys.argv[2]").

Anyway, to the code again:

>? if clipboardShelf[sys.argv[2]] in clipboardShelf.keys():
>?? clipboardShelf.pop()

A Shelf is a mutable mapping of keys to values. So
clipboardShelf[sys.argv[2]] is a clipboard value.  That will not be in 
the keys. You probably mean:

    if sys.argv[2] in clipboardShelf.keys():

Then you go: clipboardShelf.pop(). I imagine your intent here it to 
remove the clipboard entry with key sys.argv[2], but you do not tell the 
pop method what key to remove. If clipboardShelf really is a mapping you 
can go:

    del clipboardShelf[sys.argv[2]]

>This code does not throw errors when tested with: python clipboard.py.  

If you attached clipboard.py, it is gone. This list is text only and 
discards attachments. Just paste the code into the message body. If the 
cde is long, paste it at the end with your discussion up front.

>However, when I run python clipboard.py list, the keyword remains in 
>the shelve file.
>
>Although my understanding is limited, I believe, from what I have 
>read, that shelve files act like dictionaries. However, using the 
>'del' option yields the same result.

Maybe there's some method to _save_ the new state of the clipboard?

I see that a shelve.Shelf object has .sync and /close methods. You need 
to use there is the Shelf is to be saved back to the file.

>I have tried several variations including the following 'for' loop:
>---snip---
>elif len(sys.argv) == 2 and sys.argv[1] == 'delete':
>? for key in clipboardShelf.keys():
>?? del clipboardShelf['']

This deletes the key '' many times, not the key specified by "key".

Also, if is not safe to modify a mapping while you are iterating over 
it. This is a general rule, but in this specific case .keys() usually 
returns a generator which yields keys. If you modify the mapping while 
using that generator it may skip some keys or behave in other unexpected 
ways. try:

    keys = list(clipboardShelf.keys())
    for key in keys:
        del clipboardShelf[key]

i.e. run the generator completely and get a list, and _then_ modify the 
mapping.

>I have also tried signifying the unknown key with empty brackets.

Is deleting an unknown key a sensible concept?

I see the Shelf class is a context manager. You chould wrap your command 
line parse code in a with statement:

    cmd = sys.argv.pop(0)
    with shelve.open(filename, writeback=True) as clipboardShelf:
        do delete, etc etc

When you exit the with suite the shelf gets saved.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From alan.gauld at yahoo.co.uk  Sat Oct 19 18:20:44 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 19 Oct 2019 23:20:44 +0100
Subject: [Tutor] Need Help!
Message-ID: <e462srsldr7hv5t2ut7btvro.1571523644704@email.android.com>



On 19 October 2019, at 22:47, Ronald Walker via Tutor <tutor at python.org> wrote:

>I am uninitiated with computers and with computer speak.
>I would very much appreciate some help at a primary level.
>I am trying to learn Python because most of the research I did on
>programming languages suggest that Python is supposed to be quite easy to
>learn. However, in reading Python materials it seems to assume that I know
>what they are talking about and am familiar with the jargon and many other
>matters.
>I am not.


That's ok, most tutorials are aimed at programmers learning python as a new language, not complete beginners. The good news is that there are several tutorials for complete beginners too. Check out the non programmers page on the python.org website.

>For example I have found how to use the help function in Python. However, in
>reading it, I cannot understand what it is trying to communicate.

Again that is aimed at experienced programmers.


>
>It is English. And I am quite literate in English. But this English is not
>using English vocabulary and syntax in a way that I can semantically
>understand.

That's because computer science is a branch of math and uses math concepts. It is not much like learning a natural language. 


>
>Do you see my confusion?
>Can anyone provide some clarity and direction for material that could "help"
>my understanding?

Absolutely understand but unfortunately I'm away from my pc and can't provide a useful answer via my tablet. Hopefully somebody else will explain the notation. However there are tutorials that will explain the jargon which will help. Mine is one such but there are several others in the non programmers page mentioned earlier.

Alan g.
www.alan-g.me.uk

From PyTutor at DancesWithMice.info  Sat Oct 19 18:26:13 2019
From: PyTutor at DancesWithMice.info (David L Neil)
Date: Sun, 20 Oct 2019 11:26:13 +1300
Subject: [Tutor] Need Help!
In-Reply-To: <000001d5866c$ad483c40$07d8b4c0$@verizon.net>
References: <000001d5866c$ad483c40$07d8b4c0$@verizon.net>
Message-ID: <594b8973-a5ca-9ffe-6c29-eaf3ab4ebbca@DancesWithMice.info>

On 20/10/19 12:02 AM, Ronald Walker via Tutor wrote:
> I am uninitiated with computers and with computer speak.
> 
> I would very much appreciate some help at a primary level.
> 
> I am trying to learn Python because most of the research I did on
> programming languages suggest that Python is supposed to be quite easy to
> learn. However, in reading Python materials it seems to assume that I know
> what they are talking about and am familiar with the jargon and many other
> matters.
> 
> I am not.


It is inevitable that learning the jargon and basics of a new field will 
be demanding. Yes, you will benefit enormously from a (knowledgeable) 
guide.

May I suggest that you find a book (either from your local library or 
book-store, or on-line) and/or choose an on-line training course 
(edX.org, Coursera, etc).

Be aware that the generic term: "Python", now means "Python3", whereas 
in the past we used "Python2" (both numbers often followed by a 
decimal-point and further digits indicating a more precise version 
number). Thus, check that your chosen 'guide' is up-to-date!

You will be welcome to verify your choice with us, and to ask further 
questions 'here'...

Welcome to the wonderful world of Python!
-- 
Regards =dn

From mats at wichmann.us  Sat Oct 19 18:39:29 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Sat, 19 Oct 2019 16:39:29 -0600
Subject: [Tutor] Need Help!
In-Reply-To: <000001d5866c$ad483c40$07d8b4c0$@verizon.net>
References: <000001d5866c$ad483c40$07d8b4c0$@verizon.net>
Message-ID: <bb3d86e0-b13a-8528-9ea3-97519a43cf6f@wichmann.us>

On 10/19/19 5:02 AM, Ronald Walker via Tutor wrote:
> I am uninitiated with computers and with computer speak.
> 
> I would very much appreciate some help at a primary level.
> 
> I am trying to learn Python because most of the research I did on
> programming languages suggest that Python is supposed to be quite easy to
> learn. However, in reading Python materials it seems to assume that I know
> what they are talking about and am familiar with the jargon and many other
> matters.

that's correct.  reference materials (typically) use a concise dialect 
which attempts to be quite precise but is oriented to the experienced 
user.  the dialect uses English words as well as a certain "well known" 
symbology, but it could never be mistaken for conversational English. 
You will want to learn to program from other materials, then when you're 
familiar will find that going back to the reference materials (in 
Python's case online language and standard library documents and the 
interactive help) will clear up specific points you might have been 
unclear on quite well. The tutorial in the python.org documentation is 
more accessible, but is not written for non-programmers, in fact it 
spends time referencing some concepts from what I find to be rather 
obscure programming languages...

> Help on method_descriptor:
>  
> count(...)
>      S.count(sub[, start[, end]]) -> int
> 
>      Return the number of non-overlapping occurrences of substring sub in
>      string S[start:end].  Optional arguments start and end are
>      interpreted as in slice notation.
> 

> What does
> 
> S.count(sub[,start[, end[]] -> int
> 
> Mean?

As I said, you don't want to be doing your initial learning from this, 
but since you ask:

given a string 'S', if you call the 'count' method on it (S.count), you 
are to give it 'sub', the substring to count the occurrences of. 
Optionally you may give a starting position in S to begin this 
search-and-count operation, and if you do then you also have the option 
to give an ending position.  The method returns (->) an integer count.

> What does
> 
> Return the number of non-overlapping occurrences of substring sub in
>      string S[start:end].  Optional arguments start and end are
>      interpreted as in slice notation.
> 
> Mean?

it means you count how many times the substring occurs, but you ignore 
cases where occurrences overlap. "Slice notation" is something that will 
become familiar to you fairly soon, but you should not expect to know 
what it is now. Testing this out this interactively:

 >>> S = "This description is caca.  In fact you might call it cacacaca."
 >>> S.count('caca')
3

the word at the end 'cacacaca' is back-to-back instances of caca, thus 
counts two - you can see there's a case of overlap and one might say if 
you look independently that the substring occurs three times in it, but 
the text of the help message tells you it won't count it that way. if in 
doubt: try it out, that's one of the real benefits of an interactive 
interpreted language - it's really cheap to experiment, so if you find a 
description unclear, just try it out.

> It is English. And I am quite literate in English. But this English is not
> using English vocabulary and syntax in a way that I can semantically
> understand.

as noted above.


> I want to find some actual concrete Python code from an actual working
> program that explains what all this means!

you can find interesting code examples at ProgramCreek here:

https://www.programcreek.com/python/

however they are unannotated and basics like this one are hard to 
construct a match for.  there are many many websites which do show 
Python interfaces and examples.

There are a number of resources for non-programmers.  Some are listed on 
the Python wiki, which since it depends on user contributions, is never 
complete, but nonetheless worth a look:

https://wiki.python.org/moin/BeginnersGuide/NonProgrammers

I might particularly mention the Learn to Program website and materials 
by Alan Gauld, who is a very frequent contributor here:

http://www.alan-g.me.uk/l2p/index.htm


From akleider at sonic.net  Sat Oct 19 18:57:07 2019
From: akleider at sonic.net (Alex Kleider)
Date: Sat, 19 Oct 2019 15:57:07 -0700
Subject: [Tutor] Need Help!
In-Reply-To: <000001d5866c$ad483c40$07d8b4c0$@verizon.net>
References: <000001d5866c$ad483c40$07d8b4c0$@verizon.net>
Message-ID: <2679d8e992182eddea421f793cbdc757@sonic.net>

On 2019-10-19 04:02, Ronald Walker via Tutor wrote:


> 
> help(str.count)
> 
> 
> 
> This is what I get:
> 
> 
> 
> Help on method_descriptor:
> 
> 
> 
> count(...)
> 
>     S.count(sub[, start[, end]]) -> int
> 
> 
> 
>     Return the number of non-overlapping occurrences of substring sub 
> in
> 
>     string S[start:end].  Optional arguments start and end are
> 
>     interpreted as in slice notation.
> 
> 
> 
> This is completely unintelligible to me.
Taciturn, yes, unintelligible, I'd have to disagree (and I am certainly 
no computer scientist!)

It's explaining what the string method 'count' does and how to use it:
If you have a string, in this case it's represented by 'S',
you can call its count method as described: S.count(....
There is a mandatory parameter represented by sub- a string of your 
choosing to specify the sub-string for which you are looking/counting.
Optional elements in computer jargon are often indicated by square 
brackets- you'll get used to it.
So there are optional parameters within the square brackets:
'start' (defaults to 0 if not specified) allows you to specify where in 
the string (S) you want to begin (if not at the beginning which is 0, 
the default.)
'end' lets you also specify where in the string (S) to stop looking if 
you don't wish to go to the end.
The '-> int' tells you that the method returns an integer. Another 
convention to which you'll get accustomed.
The next line spells this out in a bit more detail: "..the number ..."


> 
> How would I use this?

To give you an easy to find primer on how to use a particular feature of 
the language.


> Return the number of non-overlapping occurrences of substring sub in
> 
>     string S[start:end].  Optional arguments start and end are
> 
>     interpreted as in slice notation.
> 

Perhaps it'll be easier if an example is used:

s = "the cow jumped over the moon"
n = s.count('the')

The above should set n to 2, the number of instances of the substring 
'the' in s.
latter_part = s.count('the', 4)
will set latter_part to 1 because you've told it to begin 4 characters 
in, thus missing the first 'the'.
In essence s.count('the', 4, 16) (I think:-)
would yield the same as s[4:16].count('the').

If you find the last bit confusing it may be because you still haven't 
learned about "slices".

Hope that helps.

From alan.gauld at yahoo.co.uk  Sat Oct 19 19:00:09 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 20 Oct 2019 00:00:09 +0100
Subject: [Tutor] Need Help!
Message-ID: <6t6sg78hftn005fkvxldwoid.1571526009458@email.android.com>



On 19 October 2019, at 23:40, Mats Wichmann <mats at wichmann.us> wrote:

>On 10/19/19 5:02 AM, Ronald Walker via Tutor 
>http://www.alan-g.me.uk/l2p/index.htm

The latest version is actually at


http://www.alan-g.me.uk/l2p2/index.htm

But thanks for the plug ?

Alan g.

From nulla.epistola at web.de  Sun Oct 20 07:16:52 2019
From: nulla.epistola at web.de (Sibylle Koczian)
Date: Sun, 20 Oct 2019 13:16:52 +0200
Subject: [Tutor] how to do this using psycopg2
In-Reply-To: <CH2PR01MB597397A4410BF0018E202B7AC56C0@CH2PR01MB5973.prod.exchangelabs.com>
References: <CH2PR01MB597397A4410BF0018E202B7AC56C0@CH2PR01MB5973.prod.exchangelabs.com>
Message-ID: <4fffa12b-1ee1-ba6b-87f8-b5933a76f09a@web.de>

Am 18.10.2019 um 20:38 schrieb Eggo why:
> Hi all,
>       I have following python code  but when perform execute got error due to signal quote.  How can I prepare the query without the signal quote?
>
>
> sql = ("alter table %s rename to %s")
> print(cur.mogrify(sql, (str_tab, tab_b)))
> cur.execute(sql, (str_tab, tab_b))
>
>
You are passing the table names as if they were query values, but they
aren't. From the psycopg2 documentation
(http://initd.org/psycopg/docs/usage.html), "Passing parameters to SQL
queries", last paragraph:

"Only query values should be bound via this method: it shouldn?t be used
to merge table or field names to the query (Psycopg will try quoting the
table name as a string value, generating invalid SQL). If you need to
generate dynamically SQL queries (for instance choosing dynamically a
table name) you can use the facilities provided by the psycopg2.sql module:

 >>> cur.execute("INSERT INTO %s VALUES (%s)", ('numbers', 10))  # WRONG
 >>> cur.execute(                                                # correct
...     SQL("INSERT INTO {} VALUES (%s)").format(Identifier('numbers')),
...     (10,))
"

So your query should work if you change it like this:

import psycopg2
from psycopg2 import sql
ddlquery = "alter table {0} rename to {1}")
# create connection and cursor
cur.execute(sql.SQL(ddlquery).format(sql.Identifier(str_tab),
                                      sql.Identifier(tab_b)))

HTH
Sibylle



From kharatemihir at gmail.com  Sun Oct 20 13:00:53 2019
From: kharatemihir at gmail.com (Mihir Kharate)
Date: Sun, 20 Oct 2019 12:00:53 -0500
Subject: [Tutor] Taking FASTA file as an input in Python 3
Message-ID: <CAH3WxOPP=QoAFY8boW7655dvgTBg7izFFx87VSgsZLOP+wM2YA@mail.gmail.com>

Hello,

I want my python program to ask for an input that accepts the FASTA files.
FASTA files are a type of text files that we use in bioinformatics. The
first line in a FASTA file is a description about the gene it is encoding.
The data starts with the second line. An example of the fasta format would
be:

>NC_003423.3:c429013-426160 Schizosaccharomyces pombe chromosome II, complete sequence
ATGGAAAAAATAAAACTTTTAAATGTAAAAACTCCCAATCATTATACTATTATTTTCAAGGTGGTGGCAT
ACTACAGCGCACTTCAACCTAACCAAAACGAACTACGAAAAGTACGAATGCTTGCTGCTGAAAGTTCTAA
TGTTAATGGATTATTTAAATCAGTAGTTGCTGTTTTAGATTGTGATGATGAAACGGTACTATTTTGAATT
ATCAATTGGGTTTGCTGACTTTGTTTACCTAGAAAGAATTGTTCATTAAAAATGACGGGAAAGCTTTGAG
TTTTCCGTATGACTGGAAGCTGGCAACTCATGTTATATGCGATGACTTTTCCTCTCCTAATGTACAAGAA


I found the following code online and tried to print it to see whether the
first line is overread:

>  DNA_sequence = open ("sequence.fasta" , "r")
>  DNA_sequence.readline()
>  print ("DNA_sequence")

However, this prints the following statement;
>  <_io.TextIOWrapper name='sequence.fasta' mode='r' encoding='cp1252'>

What I am interested in the fasta file is the DNA code, which starts with
the second line. I want to be able to use this code as if a it is a string
(So that it could be used with attributes like maketrans,etc. which I have
in my code)

Also, it would be easier to be able to input a fasta file just by dragging
and dropping it into the shell. Any suggestions?

Thanks,
~Mihir

From alan.gauld at yahoo.co.uk  Sun Oct 20 13:49:52 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 20 Oct 2019 18:49:52 +0100
Subject: [Tutor] Taking FASTA file as an input in Python 3
Message-ID: <ebwct8rchxsnyctctfppqfgx.1571593792579@email.android.com>



On 20 October 2019, at 18:36, Mihir Kharate <kharatemihir at gmail.com> wrote:

>
>I found the following code online and tried to print it to see whether the
>first line is overread:
>>? DNA_sequence = open ("sequence.fasta" , "r")
>>? DNA_sequence.readline()
>>? print ("DNA_sequence")
>However, this prints the following statement;
>>? <_io.TextIOWrapper name='sequence.fasta' mode='r' encoding='cp1252'>

I assume the quotes around DNA_sequence in the print are an error? If so then the output is As expected since that is the file object. The line has been read but not stored. The next line you read will be the first line of the sequence so you can put it in a variable like this

line = DNA_sequence.readline()

Alan g.

From mats at wichmann.us  Sun Oct 20 13:51:33 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 20 Oct 2019 11:51:33 -0600
Subject: [Tutor] Taking FASTA file as an input in Python 3
In-Reply-To: <CAH3WxOPP=QoAFY8boW7655dvgTBg7izFFx87VSgsZLOP+wM2YA@mail.gmail.com>
References: <CAH3WxOPP=QoAFY8boW7655dvgTBg7izFFx87VSgsZLOP+wM2YA@mail.gmail.com>
Message-ID: <e657d503-bd3d-8051-ebd0-1ad3e8ce9874@wichmann.us>

On 10/20/19 11:00 AM, Mihir Kharate wrote:
> Hello,
> 
> I want my python program to ask for an input that accepts the FASTA files.
> FASTA files are a type of text files that we use in bioinformatics. The
> first line in a FASTA file is a description about the gene it is encoding.
> The data starts with the second line. An example of the fasta format would
> be:
> 
>> NC_003423.3:c429013-426160 Schizosaccharomyces pombe chromosome II, complete sequence
> ATGGAAAAAATAAAACTTTTAAATGTAAAAACTCCCAATCATTATACTATTATTTTCAAGGTGGTGGCAT
> ACTACAGCGCACTTCAACCTAACCAAAACGAACTACGAAAAGTACGAATGCTTGCTGCTGAAAGTTCTAA
> TGTTAATGGATTATTTAAATCAGTAGTTGCTGTTTTAGATTGTGATGATGAAACGGTACTATTTTGAATT
> ATCAATTGGGTTTGCTGACTTTGTTTACCTAGAAAGAATTGTTCATTAAAAATGACGGGAAAGCTTTGAG
> TTTTCCGTATGACTGGAAGCTGGCAACTCATGTTATATGCGATGACTTTTCCTCTCCTAATGTACAAGAA
> 
> 
> I found the following code online and tried to print it to see whether the
> first line is overread:
> 
>>   DNA_sequence = open ("sequence.fasta" , "r")
>>   DNA_sequence.readline()
>>   print ("DNA_sequence")
> 
> However, this prints the following statement;
>>   <_io.TextIOWrapper name='sequence.fasta' mode='r' encoding='cp1252'>

You cannot have sent us the program you are actually using, because as 
written, the output must be *exactly*

DNA_sequence

If you are printing it without the quote marks, then you will get what 
you have pasted: DNA_sequence is the name associated with the open file 
reference, and that's exactly what it is telling you.

If you want to actually print the data being read from the file, you 
will need to save a reference to it and print that.  Maybe something 
like this?:

with open ("sequence.fasta" , "r") as DNA_sequence:
     DNA_sequence.readline()  # throw away first line
     print ("DNA_sequence")
     for line in DNA_sequence:
         print(line)




From james.londonsw15 at gmail.com  Sun Oct 20 14:19:54 2019
From: james.londonsw15 at gmail.com (James Austin)
Date: Sun, 20 Oct 2019 19:19:54 +0100
Subject: [Tutor] Deleting items from a shelve file when items are unknown
In-Reply-To: <20191019220931.GA53248@cskk.homeip.net>
References: <cbe07c70-5d34-f380-f08f-9a4ada0a3df3@gmail.com>
 <20191019220931.GA53248@cskk.homeip.net>
Message-ID: <ed4d9b15-e28c-c19d-fc2a-1bd306ae49bf@gmail.com>

Hi Cameron


Thanks for the advice. I'll try as you suggest and report back here 
either way, espeically if I have more questions regarding your suggestions.



On 19/10/2019 23:09, Cameron Simpson wrote:
> Personally I tend to pop things off sys.argv progressively so that 
> they can get nice names:
>
> ?? cmd = sys.argv.pop(0)?? # command name
> ?? op = sys.argv.pop(0)??? # operation
> ?? if op == 'delete':
> ?????? key = sys.argv.pop(0)
>
> This has the advantage of not hardwiring argument positions into your 
> code. (Suppose you latter add some option parsing ahead of the 
> 'delete' operation word?) It also mades the code more readable ("key" 
> instead of "sys.argv[2]").
>
I did not know this was possible, so thank you. I am always looking to 
improve and have readaable code.
> Anyway, to the code again:
>
>> ? if clipboardShelf[sys.argv[2]] in clipboardShelf.keys():
>> ?? clipboardShelf.pop()
>
> A Shelf is a mutable mapping of keys to values. So
> clipboardShelf[sys.argv[2]] is a clipboard value.? That will not be in 
> the keys. You probably mean:
>
> ?? if sys.argv[2] in clipboardShelf.keys():
>
> Then you go: clipboardShelf.pop(). I imagine your intent here it to 
> remove the clipboard entry with key sys.argv[2], but you do not tell 
> the pop method what key to remove.


How is thsi to be achieved? The key could be anything, is there some way 
of informing pop of this?


Thanks

James

>
>
>
>

From cs at cskk.id.au  Sun Oct 20 18:51:05 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Mon, 21 Oct 2019 09:51:05 +1100
Subject: [Tutor] Deleting items from a shelve file when items are unknown
In-Reply-To: <ed4d9b15-e28c-c19d-fc2a-1bd306ae49bf@gmail.com>
References: <ed4d9b15-e28c-c19d-fc2a-1bd306ae49bf@gmail.com>
Message-ID: <20191020225105.GA85605@cskk.homeip.net>

On 20Oct2019 19:19, James Austin <james.londonsw15 at gmail.com> wrote:
>Thanks for the advice. I'll try as you suggest and report back here 
>either way, espeically if I have more questions regarding your 
>suggestions.

Great. Remember to do it by replying to a post in this thread.

[..]
>>>? if clipboardShelf[sys.argv[2]] in clipboardShelf.keys():
>>>?? clipboardShelf.pop()
>>
>>A Shelf is a mutable mapping of keys to values. So
>>clipboardShelf[sys.argv[2]] is a clipboard value.? That will not be 
>>in the keys. You probably mean:
>>
>>?? if sys.argv[2] in clipboardShelf.keys():
>>
>>Then you go: clipboardShelf.pop(). I imagine your intent here it to 
>>remove the clipboard entry with key sys.argv[2], but you do not tell 
>>the pop method what key to remove.
>
>How is thsi to be achieved? The key could be anything, is there some 
>way of informing pop of this?

Well, isn't sys.argv[2] the key in question? You could just del that 
key:

    del clipboardShelf[sys.argv[2]]

BTW, since clipboardShelf is a mapping, you can replace:

    if sys.argv[2] in clipboardShelf.keys():

with:

    if sys.argv[2] in clipboardShelf:

More readable again.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From s.molnar at sbcglobal.net  Mon Oct 21 09:45:14 2019
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Mon, 21 Oct 2019 09:45:14 -0400
Subject: [Tutor] Pass arguments from bash script to embedded python script
Message-ID: <5DADB66A.5000607@sbcglobal.net>

First of all, let me emphasize that this is not a homework assignment.

I have a large number of data files form a Quantum Chemistry program 
which all have the same format.

I have written a short python script to extract the data required for 
another program.

> #!/usr/bin/env python3
> # -*- coding: utf-8 -*-
> """
>
> Created on Tue Sep 24 07:51:11 2019
>
> """""
> import numpy as np
>
> data = np.genfromtxt(fname, usecols=(1), skip_header=27, 
> skip_footer=1, encoding=None)
>
> print(data)
>
> np.savetxt('fname.dG', data, fmt='%.10g', header='fname1')
> print(data)


and I have a bash script in which I have embedded the python script:

> #!/bin/bash
>
> # Run.dG.list_1
>
> while IFS= read -r d
> do
>     python3 DeltaGTable_V_sw.py
> done <ligand.list
The ligand.list for the bash file have the format:
>
>> fname = ['C-VX3.log', '15-7.log', '14-7.log']
>> fname1 = ['C-VX3', '15-7', '14-7'

where fname and fname1 are three typical data files.

my problem is how do I pass the argument's in the two files from the 
bash script to the python script? It has been suggested to me that the 
solution is an implementation of the sys/.argv function but it seems 
that every reference that I can find goes the other way from python to bash.

So my question is what question should I be goggling? I am not looking 
for someone to write the script for me, but pointers in the correct 
direction.

Thanks in advance.

-- 
Stephen P. Molnar, Ph.D.
www.molecular-modeling.net
614.312.7528 (c)
Skype:  smolnar1


From mats at wichmann.us  Mon Oct 21 11:39:17 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 21 Oct 2019 09:39:17 -0600
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DADB66A.5000607@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
Message-ID: <322b813e-ce02-50a5-fc89-081e80bd462f@wichmann.us>

On 10/21/19 7:45 AM, Stephen P. Molnar wrote:

> my problem is how do I pass the argument's in the two files from the 
> bash script to the python script? It has been suggested to me that the 
> solution is an implementation of the sys/.argv function but it seems 
> that every reference that I can find goes the other way from python to 
> bash.

perhaps this will illustrate:

[mats at boulder tmp]$ cat call.sh
python3 script.py A B C
[mats at boulder tmp]$ cat script.py
import sys

print("Called with:", sys.argv)
[mats at boulder tmp]$ sh call.sh
Called with: ['script.py', 'A', 'B', 'C']


usually you'll start your processing at sys.argv[1], since [0] is the 
script name itself. That incantation often appears as:

args = sys.argv[1:]


From PyTutor at DancesWithMice.info  Mon Oct 21 14:42:02 2019
From: PyTutor at DancesWithMice.info (David L Neil)
Date: Tue, 22 Oct 2019 07:42:02 +1300
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DADB66A.5000607@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
Message-ID: <fa1c4033-b329-0374-4849-52c812fab226@DancesWithMice.info>

On 22/10/19 2:45 AM, Stephen P. Molnar wrote:
> First of all, let me emphasize that this is not a homework assignment.
> 
> I have a large number of data files form a Quantum Chemistry program 
> which all have the same format.
> 
> I have written a short python script to extract the data required for 
> another program.
...

> and I have a bash script in which I have embedded the python script:
...

> The ligand.list for the bash file have the format:
>>
>>> fname = ['C-VX3.log', '15-7.log', '14-7.log']
>>> fname1 = ['C-VX3', '15-7', '14-7'
> 
> where fname and fname1 are three typical data files.
> 
> my problem is how do I pass the argument's in the two files from the 
> bash script to the python script? It has been suggested to me that the 
> solution is an implementation of the sys/.argv function but it seems 
> that every reference that I can find goes the other way from python to 
> bash.
> 
> So my question is what question should I be goggling? I am not looking 
> for someone to write the script for me, but pointers in the correct 
> direction.


- over-simplified but useful to gain context,
How to use sys.argv in Python:
https://www.pythonforbeginners.com/system/python-sys-argv

- the recommended* Python library is argparse
https://docs.python.org/3/library/argparse.html
(much of the discussion/tutorial deals with offering 'help' responses to 
incorrect cmdLN instruction, but that can be skipped in a personal 
implementation)


* previous coding-tools have been deprecated, even as they appear more 
frequently in web-tutorials, etc.


May I recommend that you do as much as possible in Python, even 
(assuming I've understood the approach) reading the 'command files' 
there, rather than trying to do more in BASH.


PS I replied to your (previous) personal msg, but SBC's email-blocker, 
blocked!
-- 
Regards =dn

From eggo at hotmail.com  Mon Oct 21 11:19:12 2019
From: eggo at hotmail.com (Eggo why)
Date: Mon, 21 Oct 2019 15:19:12 +0000
Subject: [Tutor] is there a way to convert psycopg2.DatabaseError to string
Message-ID: <DM6PR01MB597764D0EA3059ED87D6F594C5690@DM6PR01MB5977.prod.exchangelabs.com>

Hi all,
     Is there a way to convert the pcycopg2 exception DatabaseError subclass to string?  Thank you very much for your advise.

except (Exception, psycopg2.DatabaseError) as error:
      query = "insert into exception (event) value (' " + error + " ')"
      cur.execute(query)
      print(error)

Gary


From kharatemihir at gmail.com  Sun Oct 20 22:04:45 2019
From: kharatemihir at gmail.com (Mihir Kharate)
Date: Sun, 20 Oct 2019 21:04:45 -0500
Subject: [Tutor] Taking FASTA file as an input in Python 3
In-Reply-To: <e657d503-bd3d-8051-ebd0-1ad3e8ce9874@wichmann.us>
References: <CAH3WxOPP=QoAFY8boW7655dvgTBg7izFFx87VSgsZLOP+wM2YA@mail.gmail.com>
 <e657d503-bd3d-8051-ebd0-1ad3e8ce9874@wichmann.us>
Message-ID: <CAH3WxOMMyP8NqbcfLx1cfZELZF8RpnHXzWxGeaTGsC1KnhpUcw@mail.gmail.com>

@Mats Wichmann <mats at wichmann.us>  Thanks! the code you provided works
great. I have a few more questions.  This is how I used the code:

import sys
fasta = input('insert your fasta file name here: ')

with open (fasta , "r") as DNA_sequence:
     DNA_sequence.readline()  # throw away first line
     print ("DNA_sequence: \n")
     for line in DNA_sequence:
         x = sys.stdout.write(line)

y = str(x)
print (len(y))

This allows me to type the file name as the input (Although my goal is to
be able to drag and drop the fasta file in the shell when the input message
is prompted. I don't know if there's a way for doing this?)

I used the sys,stdout.write() to remove any blank spaces and indentations
in the fasta file format so that I get a continuous string (although
sys.stdout.write() converts the text into integer. I don't understand how!
How can letters and characters be converted into integers unless we are
talking binary?)

When I run the program, it simply prints out the sequence, regardless of
whether or not I make a call to print the variable it is assigned to.

       for line in DNA_sequence:
         x = sys.stdout.write(line)

I don't think it stores the input in the variable "x" at all? How to do
this?

  y = str(x)
print (len(y))

Also, here the print(len(y)) did not print the length of the Sequence. It
printed the number 1 instead. Why so?

I am just trying to play with this code here. Eventually my goal is to be
able to take the fasta file as an input ---> overread the first line --->
convert the rest of the text as a continuous string --> store this string
into a variable,.. so that I can use it to do other things.


On Sun, Oct 20, 2019 at 12:51 PM Mats Wichmann <mats at wichmann.us> wrote:

> On 10/20/19 11:00 AM, Mihir Kharate wrote:
> > Hello,
> >
> > I want my python program to ask for an input that accepts the FASTA
> files.
> > FASTA files are a type of text files that we use in bioinformatics. The
> > first line in a FASTA file is a description about the gene it is
> encoding.
> > The data starts with the second line. An example of the fasta format
> would
> > be:
> >
> >> NC_003423.3:c429013-426160 Schizosaccharomyces pombe chromosome II,
> complete sequence
> > ATGGAAAAAATAAAACTTTTAAATGTAAAAACTCCCAATCATTATACTATTATTTTCAAGGTGGTGGCAT
> > ACTACAGCGCACTTCAACCTAACCAAAACGAACTACGAAAAGTACGAATGCTTGCTGCTGAAAGTTCTAA
> > TGTTAATGGATTATTTAAATCAGTAGTTGCTGTTTTAGATTGTGATGATGAAACGGTACTATTTTGAATT
> > ATCAATTGGGTTTGCTGACTTTGTTTACCTAGAAAGAATTGTTCATTAAAAATGACGGGAAAGCTTTGAG
> > TTTTCCGTATGACTGGAAGCTGGCAACTCATGTTATATGCGATGACTTTTCCTCTCCTAATGTACAAGAA
> >
> >
> > I found the following code online and tried to print it to see whether
> the
> > first line is overread:
> >
> >>   DNA_sequence = open ("sequence.fasta" , "r")
> >>   DNA_sequence.readline()
> >>   print ("DNA_sequence")
> >
> > However, this prints the following statement;
> >>   <_io.TextIOWrapper name='sequence.fasta' mode='r' encoding='cp1252'>
>
> You cannot have sent us the program you are actually using, because as
> written, the output must be *exactly*
>
> DNA_sequence
>
> If you are printing it without the quote marks, then you will get what
> you have pasted: DNA_sequence is the name associated with the open file
> reference, and that's exactly what it is telling you.
>
> If you want to actually print the data being read from the file, you
> will need to save a reference to it and print that.  Maybe something
> like this?:
>
> with open ("sequence.fasta" , "r") as DNA_sequence:
>      DNA_sequence.readline()  # throw away first line
>      print ("DNA_sequence")
>      for line in DNA_sequence:
>          print(line)
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at yahoo.co.uk  Mon Oct 21 17:54:49 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 21 Oct 2019 22:54:49 +0100
Subject: [Tutor] Taking FASTA file as an input in Python 3
Message-ID: <3o2wh61hk1pbdxneq4qxsgir.1571694889204@email.android.com>

On 21 October 2019, at 21:54, Mihir Kharate <kharatemihir at gmail.com> wrote:

>with open (fasta , "r") as DNA_sequence:
>???? DNA_sequence.readline()? # throw away first line
>???? print ("DNA_sequence: \n")
>???? for line in DNA_sequence:
>???????? x = sys.stdout.write(line)

More that the returnable from write is the number of chats written, is a number. It is not normally very useful.

>
>I used the sys,stdout.write() to remove any blank spaces and indentations

Write does not do that. It just writes out the string which is given with no changes.


>sys.stdout.write() converts the text into integer

No. It returns an integer as discussed above. The number of characters written.


>When I run the program, it simply prints out the sequence, regardless of
>whether or not I make a call to print the variable it is assigned to.

That's what sys.stdout.Write does. It writes the line to stdout.


>? Eventually my goal is to be
>able to take the fasta file as an input ---> overread the first line --->
>convert the rest of the text as a continuous string --> store this string
>into a variable,.. so that I can use it to do other things.

In that case you need to build the string from the input. The best way to do that is store the lines in a list then use string.join to create a single string from the list contents.

In pseudo code...

With open datafile as f
     data = []
     F.readline
     For line in c:
          data.append(line)
     S = "\n".join(data)

You'll need to convert that to value python but the structure should work.


Alan g

From bouncingcats at gmail.com  Mon Oct 21 18:49:03 2019
From: bouncingcats at gmail.com (David)
Date: Tue, 22 Oct 2019 09:49:03 +1100
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DADB66A.5000607@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
Message-ID: <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>

On Tue, 22 Oct 2019 at 00:45, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:

[...]

> and I have a bash script in which I have embedded the python script:

Why is the task split between two scripts in two different languages?
This seems misguided and to introduce unnecessary complications,
given the simple nature of both scripts that were shown.

[...]

> > while IFS= read -r d
> > do
> >     python3 DeltaGTable_V_sw.py
> > done <ligand.list

The functionality in that bash code is simple to achieve using Python.

[...]

> The ligand.list for the bash file have the format:
> >
> >> fname = ['C-VX3.log', '15-7.log', '14-7.log']
> >> fname1 = ['C-VX3', '15-7', '14-7'

I wonder what generates that content? Because it strongly
resembles runnable Python code. See below.

I may be misunderstanding, but using Bash to read files
containing what looks like Python source code looks like a
confused design. Is there some reason for that?

It looks like Bash is used to parse data out of Python syntax
before then passing that data to a Python script. Yes, it could
be made to work, but it looks like a confused and inefficient design.

A cleaner approach would be to write one Python script that does
everything required, and avoid all the unnecessary parsing and
argument passing. If the Bash script was complicated, I wouldn't
advocate this because it would be a lot of work. But the Bash
script you showed us is trivial.

> So my question is what question should I be goggling? I am not looking
> for someone to write the script for me, but pointers in the correct
> direction.

Possible approaches:

1) In Python, how to read a file line-by-line, and parse data out of it.
If that is actually needed? ...

2) Or, if it is not a security risk and you control the file content, you might
be able to directly apply Python's exec() function [1] directly to the
entire content of your ligand.list file. In that case there would be no
need to read the ligand.list file line-by-line.

[1] https://docs.python.org/3/library/functions.html#exec

From cs at cskk.id.au  Mon Oct 21 19:13:08 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Tue, 22 Oct 2019 10:13:08 +1100
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DADB66A.5000607@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
Message-ID: <20191021231308.GA13170@cskk.homeip.net>

On 21Oct2019 09:45, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
>First of all, let me emphasize that this is not a homework assignment.
>I have a large number of data files form a Quantum Chemistry program 
>which all have the same format.
>
>I have written a short python script to extract the data required for 
>another program.
>
>>#!/usr/bin/env python3
>># -*- coding: utf-8 -*-
>>"""
>>
>>Created on Tue Sep 24 07:51:11 2019
>>
>>"""""
>>import numpy as np
>>
>>data = np.genfromtxt(fname, usecols=(1), skip_header=27, 
>>skip_footer=1, encoding=None)
>>
>>print(data)
>>
>>np.savetxt('fname.dG', data, fmt='%.10g', header='fname1')
>>print(data)

Can you show us a bare command line invocation of this Python programme?  
It is not clear to me what you expect to be in "fname"; I would have 
assumed a filename, but your shell script suggests otherwise.

>and I have a bash script in which I have embedded the python script:
>
>>#!/bin/bash

Please, just say "shell script" instead of "bash script", and use 
"#!/bin/sh".  All systems have a /bin/sh, not all systems have a 
/bin/bash, and nothing in your script needs anything that is special to 
bash.

>># Run.dG.list_1
>>
>>while IFS= read -r d
>>do
>>    python3 DeltaGTable_V_sw.py
>>done <ligand.list

Small recommendation: when you write a while loop in the shell which 
reads from a file, you should avoid letting the commands _inside_ the 
while loop also read from that file - they will consume it if they do 
so, and your loop will terminate early. Rewrite the above loop like 
this:

    while IFS= read -r d <&3
    do
        python3 DeltaGTable_V_sw.py 3<&-
    done 3<ligand.list

This attaches the "ligang.list" file to the "while" as file descriptor 
3, reads from file descriptor 3, and arranges to _not_ pass file 
descriptor 3 to the python programme. Much much safer.

>The ligand.list for the bash file have the format:
>>
>>>fname = ['C-VX3.log', '15-7.log', '14-7.log']
>>>fname1 = ['C-VX3', '15-7', '14-7'
>
>where fname and fname1 are three typical data files.

Are these 2 lines:

    fname = ['C-VX3.log', '15-7.log', '14-7.log']
    fname1 = ['C-VX3', '15-7', '14-7'

lines from the ligang.list file? i.e. actual Python assignment 
statements?

>my problem is how do I pass the argument's in the two files from the 
>bash script to the python script? It has been suggested to me that the 
>solution is an implementation of the sys/.argv function but it seems 
>that every reference that I can find goes the other way from python to 
>bash.

Yah, because people call shell scripts or plain commands via subprocess 
and routinely get this incorrect.

For your purpose, you have a shell variable $d containing a line from 
the "ligand.list" file. I'd like to see an example of such a line, I 
found your description unclear above.

However, to get you going...

You can pass that line as a single command line string to the Python 
programme like this:

    python3 DeltaGTable_V_sw.py "$d"

That will include any internal spaces etc in that single string, 
courtesy of the quotes. Within the Python programm that string will be 
sys.argv[1]; sys.argv being the command line invocation and sys.argv[0] 
being the script name "DeltaGTable_V_sw.py".

You will need to "import sys" to get access to sys.argv of course.

That puts the parsing of the line in your Python code: you will need to 
break it up on speaces or whatever is sesnsible (as I say, I'm unsure 
what is really in the line). If "ligand.list" is just a text file with 
filenames in it, one per line, you won't need to do anything to it - 
just use the string.

Alternatively the shell script could break up the line on spaces if you 
go:

    python3 DeltaGTable_V_sw.py $d

This just omites the quotes, which causes the shell to grep $d into 
"words". Supposing the line had:

    C-VX3.log g15-7.log 14-7.log

then inside the Python programme sys.argv would have 4 strings:

    DeltaGTable_V_sw.py
    C-VX3.log
    g15-7.log
    14-7.log

and you can use sys.argv[1:] to access the latter 3 strings.

Your shell script is, however, so simple that you may as well just do it 
_all_ in Python:

    with open("ligand.list") as ligands:
        for line in ligands:
            # drop trailing newline and whitespace
            text = line.rstrip()
            ... do whatever you want with text ...

This sidesteps the shell entirely.

Note that this kind of thing does get wordy in Python if your command 
line stuff gets more comoplicated, and there will be a sweet spot where 
it is nice to have a wrapper shell script like yours. I think you're 
possibly just below that point (shell script too simple to bother with).

We can provide more detailed help if you can make the contents of 
ligans.list more clear, and the desired invocation of the Python 
programme more clear.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From cal.97g at gmail.com  Tue Oct 22 08:17:06 2019
From: cal.97g at gmail.com (Cal97g .)
Date: Tue, 22 Oct 2019 13:17:06 +0100
Subject: [Tutor] is there a way to convert psycopg2.DatabaseError to
 string
In-Reply-To: <DM6PR01MB597764D0EA3059ED87D6F594C5690@DM6PR01MB5977.prod.exchangelabs.com>
References: <DM6PR01MB597764D0EA3059ED87D6F594C5690@DM6PR01MB5977.prod.exchangelabs.com>
Message-ID: <CABEZvgrhNmWaQuN0KjrVs53zEsbJ_CG-OE-Qi_FO4c1HMmLoRw@mail.gmail.com>

try print(error.msg) or print(str(error))
Many Thanks

Callam Delaney


On Mon, 21 Oct 2019 at 21:49, Eggo why <eggo at hotmail.com> wrote:

> Hi all,
>      Is there a way to convert the pcycopg2 exception DatabaseError
> subclass to string?  Thank you very much for your advise.
>
> except (Exception, psycopg2.DatabaseError) as error:
>       query = "insert into exception (event) value (' " + error + " ')"
>       cur.execute(query)
>       print(error)
>
> Gary
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at btinternet.com  Wed Oct 16 04:29:50 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Oct 2019 09:29:50 +0100
Subject: [Tutor] Invalid Syntax Error
In-Reply-To: <CAK__PGPnOhvFx96aZpAbbUNLzZZn-vTwX_8=twcozomnd3T9DA@mail.gmail.com>
References: <CAK__PGPnOhvFx96aZpAbbUNLzZZn-vTwX_8=twcozomnd3T9DA@mail.gmail.com>
Message-ID: <4a426e15-7a0e-544b-3c17-ab09bc42090e@btinternet.com>

On 16/10/2019 04:24, Tyson Barber wrote:

> little simple Python code! In the code however there is a syntax error
> (highlighted in yellow) and I was wondering if it was because I had to
> declare it as a string? I was taught that it was automatically declared as
> a string so I do not know where I went wrong?

We can't see the colours because the list converts it to plain text.
That's why you need to paste the entire error message into the mail.
It tells us exactly what is wrong and where.

> print ("Welcome to the Video Game Selector!")
> print ("Please decide between fps, sports, rpg or battle royale!")
> genre = input("Please enter your preferred genre of video games: ")
> if result = ("fps"):

You are doing an assignment to result. You should be doing a comparison

if result == "fps":

Also notice you don't need the parens.


>     print ("Call of Duty MW, Battlefield V, Fallout 76, Gears of War 5")
> elif result = ("sports"):
>     print ("NBA 2K20, NHL 20, Madden 20, FIFA 20")
> elif result = ("rpg"):
>     print ("Skyrim, The Witcher, World of Warcraft")
> elif result = ("battle royale"):
>     print = ("Fortnite, APEX Legends, PUBG")

And here you replace the print function with your data.
While it is legal Python code it is a very bad idea because
you will no longer be able to use print()...!

I assume you just wanted to print the string?

    print("Fortnite, APEX Legends, PUBG")

> else:
>     print = ("Sorry, that is not in the database.\n Try using a keyword!")

Same here...


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


From eggo at hotmail.com  Tue Oct 22 09:40:13 2019
From: eggo at hotmail.com (Eggo why)
Date: Tue, 22 Oct 2019 13:40:13 +0000
Subject: [Tutor] is there a way to convert psycopg2.DatabaseError to
 string
In-Reply-To: <CABEZvgrhNmWaQuN0KjrVs53zEsbJ_CG-OE-Qi_FO4c1HMmLoRw@mail.gmail.com>
References: <DM6PR01MB597764D0EA3059ED87D6F594C5690@DM6PR01MB5977.prod.exchangelabs.com>,
 <CABEZvgrhNmWaQuN0KjrVs53zEsbJ_CG-OE-Qi_FO4c1HMmLoRw@mail.gmail.com>
Message-ID: <CH2PR01MB5973809B37EE3538A4EC56BEC5680@CH2PR01MB5973.prod.exchangelabs.com>

Thanks it works.
________________________________
From: Cal97g . <cal.97g at gmail.com>
Sent: Tuesday, October 22, 2019 12:17 PM
To: Eggo why <eggo at hotmail.com>
Cc: tutor at python.org <tutor at python.org>
Subject: Re: [Tutor] is there a way to convert psycopg2.DatabaseError to string

try print(error.msg) or print(str(error))
Many Thanks

Callam Delaney


On Mon, 21 Oct 2019 at 21:49, Eggo why <eggo at hotmail.com<mailto:eggo at hotmail.com>> wrote:
Hi all,
     Is there a way to convert the pcycopg2 exception DatabaseError subclass to string?  Thank you very much for your advise.

except (Exception, psycopg2.DatabaseError) as error:
      query = "insert into exception (event) value (' " + error + " ')"
      cur.execute(query)
      print(error)

Gary

_______________________________________________
Tutor maillist  -  Tutor at python.org<mailto:Tutor at python.org>
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From pylmsn at gmail.com  Wed Oct 23 09:44:07 2019
From: pylmsn at gmail.com (Yanlei Peng)
Date: Wed, 23 Oct 2019 09:44:07 -0400
Subject: [Tutor] Invalid Syntax Error
In-Reply-To: <4a426e15-7a0e-544b-3c17-ab09bc42090e@btinternet.com>
References: <CAK__PGPnOhvFx96aZpAbbUNLzZZn-vTwX_8=twcozomnd3T9DA@mail.gmail.com>
 <4a426e15-7a0e-544b-3c17-ab09bc42090e@btinternet.com>
Message-ID: <CAMZV1hB0aPMXAo1Tv8W4b7MxQy6XpoxM=C_F5pnqtYwbgbnj=w@mail.gmail.com>

I'd like to add one more thing in addition to Alan and Cameron's comments:

> print ("Welcome to the Video Game Selector!")
> print ("Please decide between fps, sports, rpg or battle royale!")
> genre = input("Please enter your preferred genre of video games: ")
> if result = ("fps"):

You need to change all of your script where you used "result" to "genre",
because you were defining the input to read in "genre", not "result" ....

Best,
Yanlei

On Tue, Oct 22, 2019 at 6:47 PM Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 16/10/2019 04:24, Tyson Barber wrote:
>
> > little simple Python code! In the code however there is a syntax error
> > (highlighted in yellow) and I was wondering if it was because I had to
> > declare it as a string? I was taught that it was automatically declared
> as
> > a string so I do not know where I went wrong?
>
> We can't see the colours because the list converts it to plain text.
> That's why you need to paste the entire error message into the mail.
> It tells us exactly what is wrong and where.
>
> > print ("Welcome to the Video Game Selector!")
> > print ("Please decide between fps, sports, rpg or battle royale!")
> > genre = input("Please enter your preferred genre of video games: ")
> > if result = ("fps"):
>
> You are doing an assignment to result. You should be doing a comparison
>
> if result == "fps":
>
> Also notice you don't need the parens.
>
>
> >     print ("Call of Duty MW, Battlefield V, Fallout 76, Gears of War 5")
> > elif result = ("sports"):
> >     print ("NBA 2K20, NHL 20, Madden 20, FIFA 20")
> > elif result = ("rpg"):
> >     print ("Skyrim, The Witcher, World of Warcraft")
> > elif result = ("battle royale"):
> >     print = ("Fortnite, APEX Legends, PUBG")
>
> And here you replace the print function with your data.
> While it is legal Python code it is a very bad idea because
> you will no longer be able to use print()...!
>
> I assume you just wanted to print the string?
>
>     print("Fortnite, APEX Legends, PUBG")
>
> > else:
> >     print = ("Sorry, that is not in the database.\n Try using a
> keyword!")
>
> Same here...
>
>
> 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 at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From s.molnar at sbcglobal.net  Wed Oct 23 15:08:07 2019
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Wed, 23 Oct 2019 15:08:07 -0400
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
Message-ID: <5DB0A517.9090407@sbcglobal.net>

I have revised my script to make use of the def function:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 09:36:30 2019

"""

import os
import glob
import numpy as np

fileList = []
filesList = []

for files in glob.glob("*.log"):
     fileName, fileExtension = os.path.splitext(files)
     fileList.append(fileName)
     filesList.append(files)


fname = fileList
for fname in fname:
     fname

fname1 = fname+'.log'
fname2 = fname+'-dG'
print('fname = ', fname)
print('fname1 = ',fname)
print('fname2 = ',fname2)

def dG(filesList):
     data = np.genfromtxt(fname1, usecols=(1), skip_header=27, 
skip_footer=1, encoding=None)
     np.savetxt(fname2, data, fmt='%.10g', header=fname)
     return(data)

data = dG(filesList)
print(data)

where fileList = ['C-VX3', '15-7', '14-7']

Note:  the extraneous print statements s are there to track results 
during execution.

The result of running the script:

# 14-7
-9.960902669
-8.979504781
-8.942611364
-8.91552301
-8.736508831
-8.663387139
-8.410739711
-8.389146347
-8.296798909
-8.168454106
-8.127990818
-8.127103774
-7.979090739
-7.941872682
-7.900766215
-7.881485228
-7.837826485
-7.815909505
-7.722540286
-7.720346742

It seems to work with one little (actually major) problem. The only 
result saved is for the last file in the list 14-7.log.

Which s the last file  in the list.

Just what am I doing or not doing?

Thanks in advance.



On 10/21/2019 06:49 PM, David wrote:
> On Tue, 22 Oct 2019 at 00:45, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
>
> [...]
>
>> and I have a bash script in which I have embedded the python script:
> Why is the task split between two scripts in two different languages?
> This seems misguided and to introduce unnecessary complications,
> given the simple nature of both scripts that were shown.
>
> [...]
>
>>> while IFS= read -r d
>>> do
>>>      python3 DeltaGTable_V_sw.py
>>> done <ligand.list
> The functionality in that bash code is simple to achieve using Python.
>
> [...]
>
>> The ligand.list for the bash file have the format:
>>>> fname = ['C-VX3.log', '15-7.log', '14-7.log']
>>>> fname1 = ['C-VX3', '15-7', '14-7'
> I wonder what generates that content? Because it strongly
> resembles runnable Python code. See below.
>
> I may be misunderstanding, but using Bash to read files
> containing what looks like Python source code looks like a
> confused design. Is there some reason for that?
>
> It looks like Bash is used to parse data out of Python syntax
> before then passing that data to a Python script. Yes, it could
> be made to work, but it looks like a confused and inefficient design.
>
> A cleaner approach would be to write one Python script that does
> everything required, and avoid all the unnecessary parsing and
> argument passing. If the Bash script was complicated, I wouldn't
> advocate this because it would be a lot of work. But the Bash
> script you showed us is trivial.
>
>> So my question is what question should I be goggling? I am not looking
>> for someone to write the script for me, but pointers in the correct
>> direction.
> Possible approaches:
>
> 1) In Python, how to read a file line-by-line, and parse data out of it.
> If that is actually needed? ...
>
> 2) Or, if it is not a security risk and you control the file content, you might
> be able to directly apply Python's exec() function [1] directly to the
> entire content of your ligand.list file. In that case there would be no
> need to read the ligand.list file line-by-line.
>
> [1] https://docs.python.org/3/library/functions.html#exec
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

-- 
Stephen P. Molnar, Ph.D.
www.molecular-modeling.net
614.312.7528 (c)
Skype:  smolnar1


From edwinconnell at gmail.com  Wed Oct 23 12:06:20 2019
From: edwinconnell at gmail.com (Ed Connell)
Date: Wed, 23 Oct 2019 11:06:20 -0500
Subject: [Tutor] Single char input
Message-ID: <CADmpvFFpoLAPpQNDNe6HmGzQ+XVpT=nGhxW3pC3x343FMgrpsA@mail.gmail.com>

Hi,
How can I accept, evaluate, and act on a single keypress in python?
Example:

Press A, B, or C

A. Do something

B. Do other thing

C. Skip to next section

Thanks.

Ed

-- 
I have a right and a left brain, but there is nothing right in the left one
and there is nothing left in the right one!

From bouncingcats at gmail.com  Wed Oct 23 17:41:43 2019
From: bouncingcats at gmail.com (David)
Date: Thu, 24 Oct 2019 08:41:43 +1100
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DB0A517.9090407@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
 <5DB0A517.9090407@sbcglobal.net>
Message-ID: <CAMPXz=p+7ZOWhKdxY8Odkz2-Pct5OzAWfdKUagT_u6xga=ikzA@mail.gmail.com>

On Thu, 24 Oct 2019 at 06:08, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
>
> I have revised my script [...]

Hi Stephen,

That's great progress! Not much to fix, almost done!

First, here's a runnable demo of your biggest mistake:
(I'm using the same shebang line as you showed, remove the
"cut here" comments and run it).

#----cut here----
#!/usr/bin/env python
fileList = ['C-VX3', '15-7', '14-7']
fname = fileList
for fname in fname:
    print('Inside the for statement', fname)
print('After the for statement', fname)
#----cut here----

I hope that demonstrates that all the work that you want to do
with the iterated variables in a 'for' statement must appear inside
(indented directly below) its parent for statement.

You can use functions (def) to create a clean structure, here's
another similar runnable demo.

#----cut here----
#~ #!/usr/bin/env python

def doubler(x):
    return 2 * x

for a in ['a', 2, 'b']:
    b = doubler(a)
    print('Inside the for statement:', b)

print('After the for statement', b)
#----cut here----

Also, even though it does not error, this code that you showed

fname = fileList
for fname in fname:
    fname

is bad because:
1) It unnecessarily re-uses fname for two purposes
   (which works but requires unnecessary mental effort for everyone).
2) The body of the for statement (the fname statement) does nothing.

It should be replaced by this:

for fname in fileList:
    # do something with fname here
    # for example ...
    print(doubler(fname))

From alan.gauld at yahoo.co.uk  Wed Oct 23 17:47:35 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 23 Oct 2019 22:47:35 +0100
Subject: [Tutor] Single char input
Message-ID: <pykmdcqcorftel6u30x97gn1.1571867255283@email.android.com>



On 23 October 2019, at 22:25, Ed Connell <edwinconnell at gmail.com> wrote:

>Hi,
>How can I accept, evaluate, and act on a single keypress in python?

This is surprisingly difficult because it is operating system dependant. They're is no standard way to do it. As a result most programmers just read the line after the user hits return.

But if you really want to read the keypress you can use the msvcrt library in Windows or the curses like Gary on unlike systems.

I include examples of both in my event driven programming topic in my tutorial.

www.alan-g.me.uk/l2p2

Another approach might be to use ctypes to access the C standard library in your system.

Alan g.


From PyTutor at DancesWithMice.info  Wed Oct 23 17:52:26 2019
From: PyTutor at DancesWithMice.info (David L Neil)
Date: Thu, 24 Oct 2019 10:52:26 +1300
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DB0A517.9090407@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
 <5DB0A517.9090407@sbcglobal.net>
Message-ID: <3249074a-aefc-bc4a-b5d5-87f218594aa7@DancesWithMice.info>

On 24/10/19 8:08 AM, Stephen P. Molnar wrote:


 > I have revised my script to make use of the def function:

Back in FORTRAN we used to write:

	FUNCTION FUNCNAME( args )
	- specific code to implement some purpose

This, in Python, is similar. Try 'translating' "def" as "define 
function", to clarify: 'I am defining function dG'...


Please copy-paste the exact code in-use and errmsg-received, because 
what came-through doesn't make sense - likely re-formatted by the email 
system.


This is a problem:

 > fname = fileList
 > for fname in fname:
 >      fname

- fname is first set to a list
- then it is used as an iterator (right side)
	AND as a (single) variable
- finally it is used for something?what?

Apparently the same varNM is being used and re-used, for quite different 
purposes!

Whereas fileList gives a clear impression that it is a collection of 
items, "fname" suggests that it holds a single file's name.

That said, why not?

	for fname in fileList:
		# do something with fname

NB what followed the above (in the email listing) should likely be 
indented (per criticism, above)


Also:

 > where fileList = ['C-VX3', '15-7', '14-7']

This is 'for our information' and not actually part of the code-snippet 
- is it?


Is the dG function designed to accept a single file-name at a time, eg 
'C-VX3' or all three at once?

 > data = dG(filesList)

is declaring all three/the entire list as parameters!


The current design (it seems to me, reading-around any email 
re-formatting issue)
1 (loop nr1) scan the currentDIR for .log files
2 add each .log file to a list [you advise that there are three]
3 (loop nr2) pick each fileNM in the (above) list, and
4 dG() it

If you combine the two loops, many (apparent) problems should 'disappear':

1 scan the currentDIR for .log files (existing)
2 manipulate the fileNM (existing)
3 dG() it (existing)


Which brings me back to "naming":

 > for files in glob.glob("*.log"):

<<<
  glob.glob(pathname, *, recursive=False)

     Return a possibly-empty list of path names that match pathname...
 >>>

- is "files" a (single) file's *name* or a list of file-names?
(the glob.glob part is indeed a list, but files is (a) singular and (b) 
a file-name (actually, a "path-name").)

Apologies, if seeming pedantic, but an incorrect choice of varNM may 
introduce a confusion which prevents comprehension/debugging.


Good idea to use some 'debug prints'! Even better, that if you are using 
r3.8 you can take advantage of a brand-new feature:

 > print('fname = ', fname)

print( f"fname =" )

NB the "f" preceding the quoted-string is deliberate and important - we 
call these "f-strings".

My ToDo list includes (continuing to research/check first, then) 
upgrading to r3.8 - even as 'f-string debug printing' is the nr1 
personal appeal to this lazy-boy!


To help with learning Python, are you aware that Python allows, even 
enables, you to experiment and thus develop a program, line-by-line?

- open a terminal window and start python3
- try these two lines (abstracted from the code):

import glob
glob.glob("*.log")

NB the second statement is an implicit version of:

	print( glob.glob("*.log") )

- you should see something like (your):

	['C-VX3', '15-7', '14-7']

Now, you have an exact illustration and on-screen evidence of what is 
happening!

You can continue adding (your) lines of code, one-at-a-time. (in which 
case, at least initially, avoid loops and aim to get (only) 'the first 
one' to work). Once you have learned the necessary Python syntax and 
bent the code to your will, the pertinent/working parts can be copied 
into a editor and saved as a file. Then you can install loops (and 
indents!) and all the bells-and-whistles your little heart desires...

Sage advice passed to a (much) younger me: "Make it work, before you 
make it better". Python's "REPR" makes enacting such advice SO much easier!


Also, which editor are you using?


WebRef: https://docs.python.org/3.7/library/glob.html
-- 
Regards =dn

From alan.gauld at yahoo.co.uk  Wed Oct 23 17:53:33 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 23 Oct 2019 22:53:33 +0100
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
Message-ID: <xorsjxmsm8bg6i6s0u6y4aoj.1571867613777@email.android.com>




>On Thu, 24 Oct 2019 at 06:08, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
>>
>

>fileList = ['C-VX3', '15-7', '14-7']
>fname = fileList
>for fname in fname:

Can I point out that this is a really bad idea. Having the item and the collection have the same name is a recipe for confusion. It's also entirely unnecessary since you already have the collection referenced as fileList, so you can just use

for fname in fileList:....

Alan g.


From cs at cskk.id.au  Wed Oct 23 17:58:59 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Thu, 24 Oct 2019 08:58:59 +1100
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DB0A517.9090407@sbcglobal.net>
References: <5DB0A517.9090407@sbcglobal.net>
Message-ID: <20191023215859.GA33599@cskk.homeip.net>

On 23Oct2019 15:08, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
>I have revised my script to make use of the def function:

There's no "def function". A "def" statement defines a function.  
Anyway, remarks inline below:

>fileList = []
>filesList = []
>
>for files in glob.glob("*.log"):
>    fileName, fileExtension = os.path.splitext(files)
>    fileList.append(fileName)
>    filesList.append(files)

This iterates over a list of filenames. So "files" is a single filename; 
I would not make this a plural. 

Also, "fileList" and "filesList" are so similar that I would expect them 
to cause confusion. And, in fact, they did confuse me later.

>fname = fileList

And here "fileList" is a list of filenames. So "fname" _should_ be 
plural. This may seem like nitpicking, but getting this right is very 
important for readability and therefore debugging. So much so that I 
initially misread what your loop above did.

>for fname in fname:
>    fname

This loop does nothing _inside_ the loop; why bother? However, its 
control action is to iterate over the list "fname", assigning each value 
to...  "fname"!

The end result of this is that after the loop, "fname" is no longer a 
list of filenames, it is now just the _last_ filename.

Again, getting plurality consistent would probably prevent you from this 
result.

>fname1 = fname+'.log'
>fname2 = fname+'-dG'
>print('fname = ', fname)
>print('fname1 = ',fname)
>print('fname2 = ',fname2)

Ok, preparing a filename (by reassembling the stuff you undid earlier) 
and the associated "-dG" name. And printing them out (which is fine, an 
aid to debugging).

>def dG(filesList):
>    data = np.genfromtxt(fname1, usecols=(1), skip_header=27, 
>skip_footer=1, encoding=None)
>    np.savetxt(fname2, data, fmt='%.10g', header=fname)
>    return(data)

The function dG does not use its parameter "filesList". Why do you pass 
it in?

Also, it is a source of bugs to use a parameter with the same name as a 
global because inside the function you might work on the parameter, 
_thinking_ you were working on the global. This is called "shadowing", 
and linters will say something like "the parameter filesList shadows a 
global of the same name" in order to point this out to you.

Then within the function you use the _global_ names "fname", "fname1" 
and "fname2". Normally a function will never use any global names; that 
is why we pass parameters to them. The whole point is to encapsulate 
their tasks as a generic method of doing something, _not_ dependent on 
any outside state.

I would have written this function thus:

    def dG(basic_name):
        src_filename = basic_name + '.log'
        dst_filename = basic_name + '-dG'
        data = np.genfromtxt(src_filename, usecols=(1), skip_header=27, skip_footer=1, encoding=None)
        np.savetxt(dst_filename, data, fmt='%.10g', header=basic_name)
        return data

so that has no dependence on external global names.

>data = dG(filesList)

Again, the function never uses "filesList" - there's no point in passing 
it in. I would have used the revised function above and gone:

    data = dG(fname)

>It seems to work with one little (actually major) problem. The only 
>result saved is for the last file in the list 14-7.log.
>Which s the last file  in the list.

That is because of the earlier for-loop I pointed out, which puts just 
the last filename into fname.

Regardless, your script will only ever process one file because the call 
to dG() is not inside any kind of iteration; it will only be run once.

Consider this:

    for fname in filesList:
        data = dG(fname)
        print(data)

which calls the function (in this case my revised function) once for 
each name in filesList.

You could put a print call inside dG() to see what fnam it was 
processing to make things more obvious.

Finally, I recommend avoiding global variables altogether - they are a 
rich source of bugs, particularly when some function quietly uses a 
global. Instead you can put _all_ the code into functions, eg:

    def dG(......):
        ..... as above ...

    def main(argv):
        fileList = []
        filesList = []
        for files in glob.glob("*.log"):
            fileName, fileExtension = os.path.splitext(files)
            fileList.append(fileName)
            filesList.append(files)
        for fname in filesList:
            data = dG(fname)
            print(data)

    # call the main function
    main()

By structuring things this way there are no global variables and you 
cannot accidentally use one in dG().

Cheers,
Cameron Simpson <cs at cskk.id.au>

From akleider at sonic.net  Wed Oct 23 19:14:59 2019
From: akleider at sonic.net (Alex Kleider)
Date: Wed, 23 Oct 2019 16:14:59 -0700
Subject: [Tutor] Single char input
In-Reply-To: <pykmdcqcorftel6u30x97gn1.1571867255283@email.android.com>
References: <pykmdcqcorftel6u30x97gn1.1571867255283@email.android.com>
Message-ID: <5e8edf44e9ca81f541207f41016b4d05@sonic.net>


> On 23 October 2019, at 22:25, Ed Connell <edwinconnell at gmail.com> 
> wrote:
> 
>> Hi,
>> How can I accept, evaluate, and act on a single keypress in python?

This question rang bells in my head so I dug around and found something 
I came up with years (>5 to be precise) ago, probably based on help I 
got from this same tutor list so I pass it on with the proviso that Alan 
mentions: it is likely to work only on a Unix system (Linux and probably 
Mac OsX.) I'm running Ubuntu (GNU/Linux.) (On second thought, perhaps it 
could work on a MicroSoft platform since the work is really done by the 
imported modules and presumably they'd be custom for the OS on which 
they are installed.)

import sys
import tty
import termios

class ReadChar():
     def __enter__(self):
         self.fd = sys.stdin.fileno()
         self.old_settings = termios.tcgetattr(self.fd)
         tty.setraw(sys.stdin.fileno())
         return sys.stdin.read(1)
     def __exit__(self, type, value, traceback):
         termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)

def readchar():
     with ReadChar() as rc:
         return rc

def testrc():
     print\
     ("Testing ReadChar: enter a character ('q' to quit.)")
     while True:
         char = readchar()
         if ord(char) <= 32:
             print("You entered character with ordinal {}, aka {}."\
                         .format(ord(char), repr(char)))
         else:
             print("You entered character '{}'."\
                         .format(char))
             if char in "qQ":
                 print("..which is the signal to quit testing 
readchar().")
                 break


From jf_byrnes at comcast.net  Wed Oct 23 22:20:55 2019
From: jf_byrnes at comcast.net (Jim)
Date: Wed, 23 Oct 2019 21:20:55 -0500
Subject: [Tutor] Tab key in tkinter
Message-ID: <7716c3a5-d503-2a72-be74-d7c6e509edbc@comcast.net>

I needed to know the keycodes for the tab and return keys. When I was 
searching for them I came across this little program. I modified it to 
give me the keycodes. It seems to work with every key I tried except the 
tab key. I wonder why? The tab key does work in my editor.

# bind and show a key press event with Tkinter
# tested with Python24      vegaseat     20nov2006
from tkinter import *
root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
def key(event):
     if event.char == event.keysym:
         msg = 'Normal Key %r' % event.keycode #event.char
     elif len(event.char) == 1:
         msg = 'Punctuation Key %r (%r)' % (event.keycode, event.char) 
  #(event.keysym, event.char)
         # added by me
         if event.keycode == 23:
             print('tab')
         else:
             print('nada')
     else:
         msg = 'Special Key %r' % event.keycode #event.keysym
         # added by me
         if event.keycode == 23:
             print('tab')
         else:
             print('nada')
     label1.config(text=msg)
root.bind_all('<Key>', key)
root.mainloop()

Thanks,  Jim


From alan.gauld at yahoo.co.uk  Thu Oct 24 08:25:05 2019
From: alan.gauld at yahoo.co.uk (Alan G)
Date: Thu, 24 Oct 2019 13:25:05 +0100
Subject: [Tutor] Tab key in tkinter
In-Reply-To: <7716c3a5-d503-2a72-be74-d7c6e509edbc@comcast.net>
Message-ID: <271fe11c-87e5-4037-be83-8094332b36f5@email.android.com>

   I am guessing but it is probably similar to the function keys _did you try
   them with your code? Look at the event driven programming page in my tutor
   to see how I dealt with those, something similar should be possible.
   Alan g
   On 24 Oct 2019 03:20, Jim <jf_byrnes at comcast.net> wrote:

     I needed to know the keycodes for the tab and return keys. When I was
     searching for them I came across this little program. I modified it to
     give me the keycodes. It seems to work with every key I tried except the

     tab key. I wonder why? The tab key does work in my editor.

     # bind and show a key press event with Tkinter
     # tested with Python24????? vegaseat???? 20nov2006
     from tkinter import *
     root = Tk()
     prompt = '????? Press any key????? '
     label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
     label1.pack()
     def key(event):
     ???? if event.char == event.keysym:
     ???????? msg = 'Normal Key %r' % event.keycode #event.char
     ???? elif len(event.char) == 1:
     ???????? msg = 'Punctuation Key %r (%r)' % (event.keycode, event.char)
     ? #(event.keysym, event.char)
     ???????? # added by me
     ???????? if event.keycode == 23:
     ???????????? print('tab')
     ???????? else:
     ???????????? print('nada')
     ???? else:
     ???????? msg = 'Special Key %r' % event.keycode #event.keysym
     ???????? # added by me
     ???????? if event.keycode == 23:
     ???????????? print('tab')
     ???????? else:
     ???????????? print('nada')
     ???? label1.config(text=msg)
     root.bind_all('<Key>', key)
     root.mainloop()

     Thanks,? Jim

     _______________________________________________
     Tutor maillist? -? Tutor at python.org
     To unsubscribe or change subscription options:
     https://mail.python.org/mailman/listinfo/tutor

From s.molnar at sbcglobal.net  Thu Oct 24 09:23:12 2019
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Thu, 24 Oct 2019 09:23:12 -0400
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <3249074a-aefc-bc4a-b5d5-87f218594aa7@DancesWithMice.info>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
 <5DB0A517.9090407@sbcglobal.net>
 <3249074a-aefc-bc4a-b5d5-87f218594aa7@DancesWithMice.info>
Message-ID: <5DB1A5C0.3070108@sbcglobal.net>

Thank you for your reply.

Here is my code as formatted, with extraneous print statements removed:

> #!/usr/bin/env python3
> # -*- coding: utf-8 -*-
> """
> Created on Fri Oct 11 09:36:30 2019
>
> """
>
> import os
> import glob
> import numpy as np
>
> fileList = []
> filesList = []
>
> for files in glob.glob("*.log"):
>     fileName, fileExtension = os.path.splitext(files)
>     fileList.append(fileName)
>     filesList.append(files)
>
>
> fname = fileList
> for fname in fileList:
>     fname
>
> fname1 = fname+'.log'
> fname2 = fname+'-dG'
>
>
> def dG(filesList):
>     data = np.genfromtxt(fname1, usecols=(1), skip_header=27, 
> skip_footer=1, encoding=None)
>     np.savetxt(fname2, data, fmt='%.10g', header=fname)
>     return(data)
>
> data = dG(filesList)
>

Please see my additional comments interspaced below:



On 10/23/2019 05:52 PM, David L Neil via Tutor wrote:
> On 24/10/19 8:08 AM, Stephen P. Molnar wrote:
>
>
> > I have revised my script to make use of the def function:
>
> Back in FORTRAN we used to write:
>
>     FUNCTION FUNCNAME( args )
>     - specific code to implement some purpose
>
Lost in the mist of time (the early 1960's) I was barely proficient in 
FORTRAN II.
> This, in Python, is similar. Try 'translating' "def" as "define 
> function", to clarify: 'I am defining function dG'...
>
>
> Please copy-paste the exact code in-use and errmsg-received, because 
> what came-through doesn't make sense - likely re-formatted by the 
> email system.
>
>
> This is a problem:
>
> > fname = fileList
> > for fname in fname:
> >      fname
>
> - fname is first set to a list
> - then it is used as an iterator (right side)
>     AND as a (single) variable
> - finally it is used for something?what?
>
> Apparently the same varNM is being used and re-used, for quite 
> different purposes!
>
> Whereas fileList gives a clear impression that it is a collection of 
> items, "fname" suggests that it holds a single file's name.
>
> That said, why not?
>
>     for fname in fileList:
>         # do something with fname
>
> NB what followed the above (in the email listing) should likely be 
> indented (per criticism, above)
>
Yes
>
> Also:
>
> > where fileList = ['C-VX3', '15-7', '14-7']
>
> This is 'for our information' and not actually part of the 
> code-snippet - is it?
>
Correct
>
> Is the dG function designed to accept a single file-name at a time, eg 
> 'C-VX3' or all three at once?
>
One at a time
> > data = dG(filesList)
>
> is declaring all three/the entire list as parameters!
>
>
> The current design (it seems to me, reading-around any email 
> re-formatting issue)
> 1 (loop nr1) scan the currentDIR for .log files
> 2 add each .log file to a list [you advise that there are three]
> 3 (loop nr2) pick each fileNM in the (above) list, and
> 4 dG() it
>
> If you combine the two loops, many (apparent) problems should 
> 'disappear':
>
> 1 scan the currentDIR for .log files (existing)
> 2 manipulate the fileNM (existing)
> 3 dG() it (existing)
>
>
> Which brings me back to "naming":
>
> > for files in glob.glob("*.log"):
>
> <<<
>  glob.glob(pathname, *, recursive=False)
>
>     Return a possibly-empty list of path names that match pathname...
> >>>
>
> - is "files" a (single) file's *name* or a list of file-names?
> (the glob.glob part is indeed a list, but files is (a) singular and 
> (b) a file-name (actually, a "path-name").)
>
> Apologies, if seeming pedantic, but an incorrect choice of varNM may 
> introduce a confusion which prevents comprehension/debugging.
>
Well, I'm certainly  confused!! (I can be pedantic along with the best.)
>
> Good idea to use some 'debug prints'! Even better, that if you are 
> using r3.8 you can take advantage of a brand-new feature:
>
> > print('fname = ', fname)
>
> print( f"fname =" )
>
> NB the "f" preceding the quoted-string is deliberate and important - 
> we call these "f-strings".
>
> My ToDo list includes (continuing to research/check first, then) 
> upgrading to r3.8 - even as 'f-string debug printing' is the nr1 
> personal appeal to this lazy-boy!
>
I have enough problems iwth 3.7.
>
> To help with learning Python, are you aware that Python allows, even 
> enables, you to experiment and thus develop a program, line-by-line?
>
> - open a terminal window and start python3
> - try these two lines (abstracted from the code):
>
> import glob
> glob.glob("*.log")
>
So far, so good:

> #!/usr/bin/env python3
> # -*- coding: utf-8 -*-
> """
> Created on Thu Oct 24 08:48:59 2019
>
> """
>
> import glob
>
> ligands =[]
> ligands = glob.glob("*.log")


> NB the second statement is an implicit version of:
>
>     print( glob.glob("*.log") )
>
> - you should see something like (your):
>
>     ['C-VX3', '15-7', '14-7'] 

That's what was returned.

> Now, you have an exact illustration and on-screen evidence of what is 
> happening!
>
> You can continue adding (your) lines of code, one-at-a-time. (in which 
> case, at least initially, avoid loops and aim to get (only) 'the first 
> one' to work). Once you have learned the necessary Python syntax and 
> bent the code to your will, the pertinent/working parts can be copied 
> into a editor and saved as a file. Then you can install loops (and 
> indents!) and all the bells-and-whistles your little heart desires...
>
> Sage advice passed to a (much) younger me: "Make it work, before you 
> make it better". Python's "REPR" makes enacting such advice SO much 
> easier!
>
>
> Also, which editor are you using?
>
Spyder-3.6.6
>
> WebRef: https://docs.python.org/3.7/library/glob.html

-- 
Stephen P. Molnar, Ph.D.
www.molecular-modeling.net
614.312.7528 (c)
Skype:  smolnar1


From jf_byrnes at comcast.net  Thu Oct 24 09:48:30 2019
From: jf_byrnes at comcast.net (Jim)
Date: Thu, 24 Oct 2019 08:48:30 -0500
Subject: [Tutor] Tab key in tkinter
In-Reply-To: <271fe11c-87e5-4037-be83-8094332b36f5@email.android.com>
References: <271fe11c-87e5-4037-be83-8094332b36f5@email.android.com>
Message-ID: <2130cea0-9b66-6b17-13cf-772637104bd9@comcast.net>

On 10/24/19 7:25 AM, Alan G wrote:
> I am guessing but it is probably similar to the function keys _did you try them
> with your code? Look at the event driven programming page in my tutor to see how
> I dealt with those, something similar should be possible.
> 
> Alan g

Just tried the function keys. F1-F9 produces keycodes 67-75. F10 shows 
nothing. F11-F12 shows 95-96. Even stranger. Will look at your page 
later today.

Thanks,  Jim

> On 24 Oct 2019 03:20, Jim <jf_byrnes at comcast.net> wrote:
> 
>      I needed to know the keycodes for the tab and return keys. When I was
>      searching for them I came across this little program. I modified it to
>      give me the keycodes. It seems to work with every key I tried except the
>      tab key. I wonder why? The tab key does work in my editor.
> 
>      # bind and show a key press event with Tkinter
>      # tested with Python24      vegaseat     20nov2006
>      from tkinter import *
>      root = Tk()
>      prompt = '      Press any key      '
>      label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
>      label1.pack()
>      def key(event):
>            if event.char == event.keysym:
>                msg = 'Normal Key %r' % event.keycode #event.char
>            elif len(event.char) == 1:
>                msg = 'Punctuation Key %r (%r)' % (event.keycode, event.char)
>         #(event.keysym, event.char)
>                # added by me
>                if event.keycode == 23:
>                    print('tab')
>                else:
>                    print('nada')
>            else:
>                msg = 'Special Key %r' % event.keycode #event.keysym
>                # added by me
>                if event.keycode == 23:
>                    print('tab')
>                else:
>                    print('nada')
>            label1.config(text=msg)
>      root.bind_all('<Key>', key)
>      root.mainloop()
> 
>      Thanks,  Jim
> 
>      _______________________________________________
>      Tutor maillist  -  Tutor at python.org
>      To unsubscribe or change subscription options:
>      https://mail.python.org/mailman/listinfo/tutor
> 
> 


From edwinconnell at gmail.com  Thu Oct 24 11:51:13 2019
From: edwinconnell at gmail.com (Ed Connell)
Date: Thu, 24 Oct 2019 10:51:13 -0500
Subject: [Tutor] Single char input
In-Reply-To: <5e8edf44e9ca81f541207f41016b4d05@sonic.net>
References: <pykmdcqcorftel6u30x97gn1.1571867255283@email.android.com>
 <5e8edf44e9ca81f541207f41016b4d05@sonic.net>
Message-ID: <CADmpvFEts6yrn8d_KpMKzh-rsn5Kcm1Bk1dCZc0B5yUF4q0QVA@mail.gmail.com>

Awesome, thanks!

On Wed, Oct 23, 2019 at 6:15 PM Alex Kleider <akleider at sonic.net> wrote:

>
> > On 23 October 2019, at 22:25, Ed Connell <edwinconnell at gmail.com>
> > wrote:
> >
> >> Hi,
> >> How can I accept, evaluate, and act on a single keypress in python?
>
> This question rang bells in my head so I dug around and found something
> I came up with years (>5 to be precise) ago, probably based on help I
> got from this same tutor list so I pass it on with the proviso that Alan
> mentions: it is likely to work only on a Unix system (Linux and probably
> Mac OsX.) I'm running Ubuntu (GNU/Linux.) (On second thought, perhaps it
> could work on a MicroSoft platform since the work is really done by the
> imported modules and presumably they'd be custom for the OS on which
> they are installed.)
>
> import sys
> import tty
> import termios
>
> class ReadChar():
>      def __enter__(self):
>          self.fd = sys.stdin.fileno()
>          self.old_settings = termios.tcgetattr(self.fd)
>          tty.setraw(sys.stdin.fileno())
>          return sys.stdin.read(1)
>      def __exit__(self, type, value, traceback):
>          termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)
>
> def readchar():
>      with ReadChar() as rc:
>          return rc
>
> def testrc():
>      print\
>      ("Testing ReadChar: enter a character ('q' to quit.)")
>      while True:
>          char = readchar()
>          if ord(char) <= 32:
>              print("You entered character with ordinal {}, aka {}."\
>                          .format(ord(char), repr(char)))
>          else:
>              print("You entered character '{}'."\
>                          .format(char))
>              if char in "qQ":
>                  print("..which is the signal to quit testing
> readchar().")
>                  break
>
>

-- 
I have a right and a left brain, but there is nothing right in the left one
and there is nothing left in the right one!

From osaosemwe at yahoo.com  Thu Oct 24 09:35:24 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Thu, 24 Oct 2019 13:35:24 +0000 (UTC)
Subject: [Tutor] Running multiple python scripts from one python scripts
References: <2069143167.1510405.1571924124863.ref@mail.yahoo.com>
Message-ID: <2069143167.1510405.1571924124863@mail.yahoo.com>

Hello Alan,
I am having issues in running multiple python scripts in one same program. The reason is that, I am creating this mini scripts in the main (master) scripts, then at the end run them all sequentially.?
here is a sample.?



import osimport sys...............os.system('python /tmp/delete_line3.py')os.system('python /tmp/create_20lines.py')os.system('python /tmp/delete_ON2_.py')os.system('python /tmp/create_50.py')

when I tried this, only the first script "delete_line3.py" ran and quitted. The rest did not execute.
Next I tried this program.
import fileinputimport subprocess as sp............... extProc = sp.Popen(['python','/tmp/delete_line3.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/create_20lines.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/ delete_ON2_.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/ create_50.py'])sp.Popen.terminate(extProc)

it did not work at all.
is there anything that I can do to?


Thanks and regards,
Ose Micah.



From alan.gauld at btinternet.com  Tue Oct 15 11:17:33 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Oct 2019 16:17:33 +0100
Subject: [Tutor] Help on Python
In-Reply-To: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
References: <CAK__PGPmA2sVNz4giTbbbHxfyiQN-BtGj6fVPk8sKjXxi-Ue9Q@mail.gmail.com>
Message-ID: <f2ed57bd-cee9-3eee-d2bc-b4fe8c754b76@btinternet.com>

On 15/10/2019 01:07, Tyson Barber wrote:
> Hello Tutor,

Hi, and yes this is the right place.

> I am new to Python and had a question.

You don;t actually ask any question so we'll have to guess.
In future its best to be as specific as possible and always
include any error messages in full so we can see them - they
contain a lot of useful information (although it may not
seem like it at first!)

> incomevar = (input("Please enter the income: ")

Count the parens, they don;t match up.
You don't need the first opening paren.


>             income = int(incomevar)

Indentation is critical in Python. This line being indented
will result in an error.

Also you don;t need two vars there, just overwrite the original:

income = input(...)
income = int(income)

Or in one line:

income = int(input(...))

> costvar = int(input("Please enter the cost: ")
>             cost = int(costvar)

See above on indentation.
Plus you don't need the int conversion since you did
that in the line above.

>                 if income >= cost :
>                   print (income - cost == profit)

The stuff inside the parens is a boolean expression.
It will evaluate to True or False. So that's what will
get printed, just True or False.

>               else income < cost :

else doesn't take an expression it is just plain

else:
   # do something here
> I have tried many things for this to work, including changing the variable
> names, spacing issues. Nothing seems to work

"Nothing seems to work" doesn't help us debug the code.
You need to be specific. What doesn't work about it?
- Do you get an error? If so send the error text.
- Does it run but print the wrong thing? If so send the output and
  tell us what you expected.
- Does it crash your computer? - that shouldn't really happen often
  in Python but in some other languages is surprisingly common!

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


From mats at wichmann.us  Thu Oct 24 16:28:22 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Thu, 24 Oct 2019 14:28:22 -0600
Subject: [Tutor] Running multiple python scripts from one python scripts
In-Reply-To: <2069143167.1510405.1571924124863@mail.yahoo.com>
References: <2069143167.1510405.1571924124863.ref@mail.yahoo.com>
 <2069143167.1510405.1571924124863@mail.yahoo.com>
Message-ID: <765af557-df2c-25f5-3475-04e84c4836ea@wichmann.us>

On 10/24/19 7:35 AM, ose micah via Tutor wrote:
> Hello Alan,
> I am having issues in running multiple python scripts in one same program. The reason is that, I am creating this mini scripts in the main (master) scripts, then at the end run them all sequentially.
> here is a sample.
> 
> 
> 
> import osimport sys...............os.system('python /tmp/delete_line3.py')os.system('python /tmp/create_20lines.py')os.system('python /tmp/delete_ON2_.py')os.system('python /tmp/create_50.py')
> 
> when I tried this, only the first script "delete_line3.py" ran and quitted. The rest did not execute.
> Next I tried this program.
> import fileinputimport subprocess as sp............... extProc = sp.Popen(['python','/tmp/delete_line3.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/create_20lines.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/ delete_ON2_.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/ create_50.py'])sp.Popen.terminate(extProc)
> 
> it did not work at all.
> is there anything that I can do to

your formatting in the email is all mangled, rally hard to read.

you almost certainly don't want to be calling "terminate".
call "wait" to wait for the subprocess to finish, or "communicate" to 
interact with it (possibly send it data, plus collect back the output 
and error streams from it)



From osaosemwe at yahoo.com  Thu Oct 24 14:23:47 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Thu, 24 Oct 2019 18:23:47 +0000 (UTC)
Subject: [Tutor] Running multiple python scripts from one python scripts
In-Reply-To: <2069143167.1510405.1571924124863@mail.yahoo.com>
References: <2069143167.1510405.1571924124863.ref@mail.yahoo.com>
 <2069143167.1510405.1571924124863@mail.yahoo.com>
Message-ID: <1309389057.1678564.1571941427675@mail.yahoo.com>

 Hello Alan,?
I have not fully solved the problem. I have a temporary fix, which is using time and subprocess which works e.g. I used time, because the processes happens to run almost simultaneously.
import fileinputimport osimport sysimport timeimport subprocess as sp...............# running the scripts in processesextProc1 = sp.Popen([sys.executable, '/tmp/delete_line3.py'],? stdout=sp.PIPE)time.sleep(5)extProc2 = sp.Popen([ sys.executable,?'/tmp/create_20lines.py'], stdout=sp.PIPE)time.sleep(5)extProc3 = sp.Popen([sys.executable,'/tmp/?delete_ON2_.py'], stdout=sp.PIPE) time.sleep(5)
extProc = sp.Popen([sys.executable,'/tmp/?create_50.py'], stdout=sp.PIPE) time.sleep(5)

# closing the parent version of the pipesextProc1.close()extProc2.close()
extProc3.close()
extProc4.close()

# Waiting for the program to completeextProc1.wait()extProc2.wait()
extProc3.wait()
extProc4.wait()

This happens to work for me. If any have a better solution, please share.
Thanks and regards,
Ose Osamudiamen.?


    On Thursday, October 24, 2019, 09:35:24 AM EDT, ose micah <osaosemwe at yahoo.com> wrote:  
 
 Hello Alan,
I am having issues in running multiple python scripts in one same program. The reason is that, I am creating this mini scripts in the main (master) scripts, then at the end run them all sequentially.?
here is a sample.?



import osimport sys...............os.system('python /tmp/delete_line3.py')os.system('python /tmp/create_20lines.py')os.system('python /tmp/delete_ON2_.py')os.system('python /tmp/create_50.py')

when I tried this, only the first script "delete_line3.py" ran and quitted. The rest did not execute.
Next I tried this program.
import fileinputimport subprocess as sp............... extProc = sp.Popen(['python','/tmp/delete_line3.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/create_20lines.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/ delete_ON2_.py'])sp.Popen.terminate(extProc)extProc = sp.Popen(['python','/tmp/ create_50.py'])sp.Popen.terminate(extProc)

it did not work at all.
is there anything that I can do to?


Thanks and regards,
Ose Micah.


  

From bouncingcats at gmail.com  Thu Oct 24 18:48:05 2019
From: bouncingcats at gmail.com (David)
Date: Fri, 25 Oct 2019 09:48:05 +1100
Subject: [Tutor] Single char input
In-Reply-To: <CADmpvFFpoLAPpQNDNe6HmGzQ+XVpT=nGhxW3pC3x343FMgrpsA@mail.gmail.com>
References: <CADmpvFFpoLAPpQNDNe6HmGzQ+XVpT=nGhxW3pC3x343FMgrpsA@mail.gmail.com>
Message-ID: <CAMPXz=o3R-p-iZVfBMuUP-w0QdSnGZ1O0=64--14JR5tj=B8ag@mail.gmail.com>

On Thu, 24 Oct 2019 at 08:25, Ed Connell <edwinconnell at gmail.com> wrote:
>
> Hi,
> How can I accept, evaluate, and act on a single keypress in python?

Hi,
There is code to do this under the link "pykbhit" at:
https://simondlevy.academic.wlu.edu/software/

I tested it on python 2 and 3 on Debian stretch.

It appears to work except that, like most similar code, it does not
handle the keys that emit more than one character.

There are many such keys (for example the function keys and the cursor
movement keys) which all emit a short sequence of characters beginning
with the same character that the "escape" key emits.

How to see evidence of these codes depends on what operating system
you are using, which you have not yet told us. If you are on Debian Linux,
start a 'dash' shell (not bash). Then press some keys and the terminal will
show you the character sequences that the keys emit.

So this code just detects all those keys as an "escape" key, because
that is the first one in the sequence. With some work it could be
extended to detect those keys too, however it's not a simple job.

I searched for a simple explanation of this for you, but was unable to find
something appropriate. Maybe someone else knows of one.
If you need more information then ask again here, or try reading these
links which are the best I could find but unfortunately more complex
or domain-specific that I hoped to offer you:
https://unix.stackexchange.com/questions/103608/is-there-any-reason-why-i-get-a-when-i-press-up-arrow-at-the-console-login-sc
https://mywiki.wooledge.org/ReadingFunctionKeysInBash

From alan.gauld at yahoo.co.uk  Thu Oct 24 18:58:34 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 24 Oct 2019 23:58:34 +0100
Subject: [Tutor] Running multiple python scripts from one python scripts
Message-ID: <8habo6yngxc43ssdfg4l1nyh.1571957914051@email.android.com>



On 24 October 2019, at 19:23, ose micah <osaosemwe at yahoo.com> wrote:

>Hello Alan,?

Hello. But I should point out that you are sending these emails to the entire tutor mailing list - currently about 430 members - not just me!

>
>I 
>
># running the scripts in processes
>
>extProc1 = sp.Popen([sys.executable, '/tmp/delete_line3.py'],? stdout=sp.PIPE)
>
>time.sleep(5)


You are doing something incredibly weird here.
Why do you not run the python code directly within your program? Just import the file as a module and call it as needed. This is much simpler and an order of magnitude faster and more efficient. eg:

import mymodule

mymodule.main().

That's precisely what Python's import module system is for.

All you need to do is follow standard python practice of putting your module code inside a function. At the end of the module out the usual python mantra

If __name__ == "__main__" : main(),

If you also want to use the script as a stand alone
program.

If the function takes arguments then extract them from sys.argv in the if name clause and make main take an argument. Then in your code it becomes

Import mymodule
mymodule.main(argument)

It's so much simpler and more powerful than messing about with subprocesses and os.system.

Alan g.

From alan.gauld at yahoo.co.uk  Thu Oct 24 19:01:11 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 25 Oct 2019 00:01:11 +0100
Subject: [Tutor] Single char input
Message-ID: <khypf9m13cjv09wonai6irq0.1571958071303@email.android.com>

I should add that this is all much easier and portable in a GUI framework such as Tkinter. It handles all the weirdness for you.

Alan g

On 24 October 2019, at 23:48, David <bouncingcats at gmail.com> wrote:

On Thu, 24 Oct 2019 at 08:25, Ed Connell <edwinconnell at gmail.com> wrote:
>
> Hi,
> How can I accept, evaluate, and act on a single keypress in python?

Hi,
There is code to do this under the link "pykbhit" at:
https://simondlevy.academic.wlu.edu/software/

I tested it on python 2 and 3 on Debian stretch.

It appears to work except that, like most similar code, it does not
handle the keys that emit more than one character.

There are many such keys (for example the function keys and the cursor
movement keys) which all emit a short sequence of characters beginning
with the same character that the "escape" key emits.

How to see evidence of these codes depends on what operating system
you are using, which you have not yet told us. If you are on Debian Linux,
start a 'dash' shell (not bash). Then press some keys and the terminal will
show you the character sequences that the keys emit.

So this code just detects all those keys as an "escape" key, because
that is the first one in the sequence. With some work it could be
extended to detect those keys too, however it's not a simple job.

I searched for a simple explanation of this for you, but was unable to find
something appropriate. Maybe someone else knows of one.
If you need more information then ask again here, or try reading these
links which are the best I could find but unfortunately more complex
or domain-specific that I hoped to offer you:
https://unix.stackexchange.com/questions/103608/is-there-any-reason-why-i-get-a-when-i-press-up-arrow-at-the-console-login-sc
https://mywiki.wooledge.org/ReadingFunctionKeysInBash
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From mats at wichmann.us  Thu Oct 24 20:06:16 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Thu, 24 Oct 2019 18:06:16 -0600
Subject: [Tutor] Single char input
In-Reply-To: <CADmpvFFpoLAPpQNDNe6HmGzQ+XVpT=nGhxW3pC3x343FMgrpsA@mail.gmail.com>
References: <CADmpvFFpoLAPpQNDNe6HmGzQ+XVpT=nGhxW3pC3x343FMgrpsA@mail.gmail.com>
Message-ID: <d5488da5-ef83-679b-31d0-b90808a92a86@wichmann.us>

On 10/23/19 10:06 AM, Ed Connell wrote:
> Hi,
> How can I accept, evaluate, and act on a single keypress in python?
> Example:
> 
> Press A, B, or C
> 
> A. Do something
> 
> B. Do other thing
> 
> C. Skip to next section

As others have said, but maybe not in these words:  this is highly 
context-dependent.

Thousands of man-years have been spent on making this kind of stuff work 
in graphical frameworks, where react-to-a-keypress behavior is common - 
if you're not on a command-line, you don't need to wait for the Enter 
(aka Return) key to be pressed unless the context indicates it: if a 
single key entry will do, then make that work; if you need a word or 
sentence (or indeed an entire complaint letter to the bank who has just 
messed up your account) to be typed you need something to indicate the 
input is done, an that will typically be a submit button, or maybe an 
enter key as is often the model with a social media post.  So if a GUI 
is what you're after, the framework you choose will undoubtedly help 
with this. If it doesn't, pick a different framework (seriously: Python 
seems to have support for about 6 times as many GUI frameworks as makes 
any rational sense).

And if you're on the command line, the _convention_  is to wait for the 
user to press Enter, because that's the standard indication the input is 
done - y<Enter> is really not much more work than just pressing y by 
itself.

It's dirt-simple in Windows, but comes at a cost, something like:

from msvcrt import getch
while True:
     key = getch()
     # decide what to do with key: break or continue

that means if you're looking for a keypress and can't do anything else 
until it happens, you've not given anything up, but it's effectively a 
blocking read so if you expect to do something else in the meantime, you 
have to build a whole framework to handle that - see the GUI discussion! 
This is in the pykbhit link that was in another reply, but it's spread 
out in the multi-platform support so it's not as clear what it's doing.

As you'll have seen by the other answers it's quite a bit harder on 
non-Windows platforms.



From alan.gauld at yahoo.co.uk  Fri Oct 25 02:39:52 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 25 Oct 2019 07:39:52 +0100
Subject: [Tutor] Single char input
References: <2tau46n5oc9m542yqmf1neey.1571985592064.ref@email.android.com>
Message-ID: <2tau46n5oc9m542yqmf1neey.1571985592064@email.android.com>



On 25 October 2019, at 01:06, Mats Wichmann <mats at wichmann.us> wrote:


>As you'll have seen by the other answers it's quite a bit harder on 
>non-Windows platforms.

To be fair, if you can use curses, and most unlike OS support it, then it's almost as easy. Just use the getchar function after initializing the screen (and you should probably reset the screen afterwards too.)


Alan g

From deeppatel050 at gmail.com  Thu Oct 24 20:12:19 2019
From: deeppatel050 at gmail.com (Deep Patel)
Date: Thu, 24 Oct 2019 20:12:19 -0400
Subject: [Tutor] i need help with my python code.
Message-ID: <CAA3NxnKdnUZp65UqeY+ucz55UubPZmbOpyTpiYVox9v9Dm3H4A@mail.gmail.com>

hi my name is deep patel. i need help with my python code that i made.i am
unable to get the picture on my window. and when i try to run my
customer.py it doesn't run and shows me error message for PIL method. i did
instal a PIL module but still i don't get it what wrong with my code. can
you please help me out with checking my code. i am gonna attach my pdf
files that has instruction in it and also my image and my python code. if
you need any more information please let me know. thanks

From deeppatel050 at gmail.com  Thu Oct 24 20:15:33 2019
From: deeppatel050 at gmail.com (Deep Patel)
Date: Thu, 24 Oct 2019 20:15:33 -0400
Subject: [Tutor] Fwd: i need help with my python code.
In-Reply-To: <CAA3NxnKdnUZp65UqeY+ucz55UubPZmbOpyTpiYVox9v9Dm3H4A@mail.gmail.com>
References: <CAA3NxnKdnUZp65UqeY+ucz55UubPZmbOpyTpiYVox9v9Dm3H4A@mail.gmail.com>
Message-ID: <CAA3NxnLLQ2-1ADkn+S86J_xSn5wo2v6W4GrG8wftBiL4J9dKtw@mail.gmail.com>

---------- Forwarded message ---------
From: Deep Patel <deeppatel050 at gmail.com>
Date: Thu, Oct 24, 2019 at 8:12 PM
Subject: i need help with my python code.
To: <tutor at python.org>


hi my name is deep patel. i need help with my python code that i made.i am
unable to get the picture on my window. and when i try to run my
customer.py it doesn't run and shows me error message for PIL method. i did
instal a PIL module but still i don't get it what wrong with my code. can
you please help me out with checking my code. i am gonna attach my pdf
files that has instruction in it and also my image and my python code. if
you need any more information please let me know. thanks

From osaosemwe at yahoo.com  Thu Oct 24 22:27:35 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Fri, 25 Oct 2019 02:27:35 +0000 (UTC)
Subject: [Tutor] Running multiple python scripts from one python scripts
In-Reply-To: <8habo6yngxc43ssdfg4l1nyh.1571957914051@email.android.com>
References: <8habo6yngxc43ssdfg4l1nyh.1571957914051@email.android.com>
Message-ID: <401092395.1907637.1571970455981@mail.yahoo.com>

Hello,?
That was my very first deployment. Calling the scripts and running them. But, that would not work in my use case. As some of the scripts are been formed in the main scripts. As a result I cannot import a script that has not been formed.?
My regards,
Ose Micah.?


Sent from Yahoo Mail for iPhone


On Thursday, October 24, 2019, 6:58 PM, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:

 _filtered #yiv8536606287 {font-family:Calibri;panose-1:2 15 5 2 2 2 4 3 2 4;}


On 24 October 2019, at 19:23, ose micah <osaosemwe at yahoo.com> wrote:

>Hello Alan,?

Hello. But I should point out that you are sending these emails to the entire tutor mailing list - currently about 430 members - not just me!

>
>I 
>
># running the scripts in processes
>
>extProc1 = sp.Popen([sys.executable, '/tmp/delete_line3.py'],? stdout=sp.PIPE)
>
>time.sleep(5)


You are doing something incredibly weird here.
Why do you not run the python code directly within your program? Just import the file as a module and call it as needed. This is much simpler and an order of magnitude faster and more efficient. eg:

import mymodule

mymodule.main().

That's precisely what Python's import module system is for.

All you need to do is follow standard python practice of putting your module code inside a function. At the end of the module out the usual python mantra

If __name__ == "__main__" : main(),

If you also want to use the script as a stand alone
program.

If the function takes arguments then extract them from sys.argv in the if name clause and make main take an argument. Then in your code it becomes

Import mymodule
mymodule.main(argument)

It's so much simpler and more powerful than messing about with subprocesses and os.system.

Alan g.





From cs at cskk.id.au  Fri Oct 25 03:07:31 2019
From: cs at cskk.id.au (Cameron Simpson)
Date: Fri, 25 Oct 2019 18:07:31 +1100
Subject: [Tutor] i need help with my python code.
In-Reply-To: <CAA3NxnKdnUZp65UqeY+ucz55UubPZmbOpyTpiYVox9v9Dm3H4A@mail.gmail.com>
References: <CAA3NxnKdnUZp65UqeY+ucz55UubPZmbOpyTpiYVox9v9Dm3H4A@mail.gmail.com>
Message-ID: <20191025070731.GA77240@cskk.homeip.net>

On 24Oct2019 20:12, Deep Patel <deeppatel050 at gmail.com> wrote:
>hi my name is deep patel. i need help with my python code that i made.i am
>unable to get the picture on my window. and when i try to run my
>customer.py it doesn't run and shows me error message for PIL method. i did
>instal a PIL module but still i don't get it what wrong with my code. can
>you please help me out with checking my code. i am gonna attach my pdf
>files that has instruction in it and also my image and my python code. if
>you need any more information please let me know. thanks

We need to know:

- what platform your using Python on (eg Linux, Windows) and the version 
  of Python

- a transcript of your error message with the full traceback (all lines)

- the code you ran (your customer.py) to get that error message

- a clear description of what the code _should_ do

This is a text only list, and all attachments are discarded, so you 
can't attach a PDF or an image or a code file. Please paste the code and 
error messages directly into your message instead.

Finally, a godd subject line is useful to everyone. This is the tutor 
list, so "i need help with my python code" might be considered implicit.  
Something like "help with my PIL module program" is a bit more 
descriptive. There's no point changing it now, just something to keep in 
mind for a new topic if you have one later.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From PyTutor at DancesWithMice.info  Fri Oct 25 04:38:40 2019
From: PyTutor at DancesWithMice.info (David L Neil)
Date: Fri, 25 Oct 2019 21:38:40 +1300
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DB1A5C0.3070108@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
 <5DB0A517.9090407@sbcglobal.net>
 <3249074a-aefc-bc4a-b5d5-87f218594aa7@DancesWithMice.info>
 <5DB1A5C0.3070108@sbcglobal.net>
Message-ID: <60ed02f7-cf61-1bc3-3ea7-b1dbda28d59f@DancesWithMice.info>

On 25/10/19 2:23 AM, Stephen P. Molnar wrote:
> Thank you for your reply.
> 
> Here is my code as formatted, with extraneous print statements removed:

Thanks - much easier to read.

Don't forget to review solid advice given in several earlier responses!


> Please see my additional comments interspaced below:
> On 10/23/2019 05:52 PM, David L Neil via Tutor wrote:
>> On 24/10/19 8:08 AM, Stephen P. Molnar wrote:
>> Back in FORTRAN we used to write:
...

> Lost in the mist of time (the early 1960's) I was barely proficient in 
> FORTRAN II.

Evidently thought you were someone else, with a FORTRAN history.

Back then I had hundreds of 101-students who became "barely proficient" 
in F-II, but went-on to do great things!

>> Apparently the same varNM is being used and re-used, for quite 
>> different purposes!

This (and other earlier critique) still evident (but am assuming you've 
been addressing, pending this/further replies)


...

>> 1 scan the currentDIR for .log files (existing)
>> 2 manipulate the fileNM (existing)
>> 3 dG() it (existing)

(above retained because is expanded, below)


>> Apologies, if seeming pedantic, but an incorrect choice of varNM may 
>> introduce a confusion which prevents comprehension/debugging.
>>
> Well, I'm certainly? confused!! (I can be pedantic along with the best.)

We can see that, but are confident that as the 'rules' coalesce in your 
mind, what we are saying will become clear...


The solution is like any other problem in ComSc: break the larger 
problem down into smaller units, 'rinse and repeat', until the next unit 
before you is solvable...

Hence the idea that Python's REPR allows one to enter code line-by-line 
and observe immediate results - quickly proving or disproving a 
solution-attempt. However, please read on, gentle reader, read on...


>> Good idea to use some 'debug prints'! Even better, that if you are 
>> using r3.8 you can take advantage of a brand-new feature:
...

> I have enough problems iwth 3.7.

Few/no other 'upgrades' (such as I have found, to-date) are likely to 
bother you/us - but that one advantage is quite compelling. (IMHO)

That said, if you are using Anaconda or some similar tool-set, you will 
need to wait until they offer an r38 update (I don't know if/when).


>> To help with learning Python, are you aware that Python allows, even 
>> enables, you to experiment and thus develop a program, line-by-line?
>>
>> - open a terminal window and start python3
>> - try these two lines (abstracted from the code):
>>
>> import glob
>> glob.glob("*.log")
>>
> So far, so good:
> 
>> #!/usr/bin/env python3
>> # -*- coding: utf-8 -*-
>> """
>> Created on Thu Oct 24 08:48:59 2019
>>
>> """
>>
>> import glob
>>
>> ligands =[]
>> ligands = glob.glob("*.log")

Good work.

Referring back to the docs-snippet on glob (quoted previously), glob 
returns a *list*. Python does not require one to declare a variable as 
having a data-type and/or an initial value - known as "duck typing". In 
this case, the assignment takes the glob result/list and thus 'says' 
ligands is (now) a list.

This idea is both a massive advantage and time-save, but as you have 
read in many of the replies to this thread, also one which can trip-up 
the unwary and the learner - because one can say, and Python will 
cheerfully oblige:

	ligands = []	# making ligands a list
	ligands = "abc"	# making ligands (now) a string, and
	ligands = 3.14	# making ligands (now) numeric.

NB this would be illegal/rejected by many other languages.

Hence the advice about being careful in one's choice of variable-names, 
and suggesting that the chosen-name indicate both form and function. 
Thus (perhaps):

	files_list = glob...

However, most?many style conventions dislike explicit use of type-words, 
eg list, dict, int; despite it being common in other languages, eg MSFT 
'standards' - and the Zen of Python recommending "explicit over 
implicit". If it helps comprehension, I certainly won't call the 'style 
police' on you, and particularly not whilst learning!


>> - you should see something like (your):
>>
>> ??? ['C-VX3', '15-7', '14-7'] 
> 
> That's what was returned.

Proof!


 >> You can continue adding (your) lines of code, one-at-a-time. (in which
 >> case, at least initially, avoid loops and aim to get (only) 'the first
 >> one' to work). Once you have learned the necessary Python syntax and
 >> bent the code to your will, the pertinent/working parts can be copied
 >> into a editor and saved as a file. Then you can install loops (and
 >> indents!) and all the bells-and-whistles your little heart desires...
 >>
 >> Sage advice passed to a (much) younger me: "Make it work, before you
 >> make it better". Python's "REPR" makes enacting such advice SO much
 >> easier!

So, now you can move on to the next sub-problem:
- you have the (three) file names
- don't bother with a loop, try to solve the single problem first
- take the first fileNM
	
	ligands[ 0 ]
or
	glob.glob( "*.log" )[ 0 ]

- split the fileNM
(and prove (to yourself) that you have the base fileNM and the 
extension/suffix - see also PSL's os.path.split().)
- assemble the output fileNM
(per the idea of ignoring the loop, above, ignore the function and 
test/prove the code using the first fileNM, without thought of repetition)
- check the np.get
- attempt the output file-save
- inspect the results using your system's 'file manager'

Et voil?!


>> Now, you have an exact illustration and on-screen evidence of what is 
>> happening!

QED on the code-building, and QED on proving the algorithm!

Thereafter collect the working code (ignoring any side-trips, 
experiments, or misapprehensions) into a source-code file (document). 
Then, (having "made it work") you can think about adding loops, 
splitting functionality, etc (you can "make it better")!

However (at great risk to your sanity)...


>> Also, which editor are you using?
>>
> Spyder-3.6.6

I know you are climbing the I-must-absorb-enough-Python 
'learning-curve', but I recommend that you divert for a moment and take 
a look at two Spyder features:

[warning: I have long had intentions of reviewing Spyder, but have thus 
far only perused their web site - so am working from 'promises' (aka 
"vapor-ware") rather than hard-experience. All due apologies!]


1 Variable Explorer
- this shows you the contents of each variable in your code, and enables 
review as the values (should) change. So, it becomes possible to 
(literally) see when something contains more than one component, when it 
shouldn't; or to quickly notice if the result is otherwise not what you 
expected! (without those extra debug-prints)

2 Debugging
- this offers (pull down the eponymous top-menu or view web-ref) the 
ability to pause program execution at any stage and/or to step through 
the Python code instruction-by-instruction, watching closely for 
cause-and-effect.

Wonderful stuff. What I wouldn't have given for tools like this, 
back-when...!


The combination of these two facilities offers a powerful alternative 
mode of attack to the Python REPR approach outlined earlier, depending 
upon one's preferred approach.

I must admit, coming from the ?good, old days when we planned-out 
programs - first in flow-charts, and then by hand-writing the code, even 
on punched-card Coding Sheets; tools such as Spyder offer the 
opportunity to first 'solve' the entire problem, and then prove it - 
which feels 'natural' (actually learned/ingrained/beaten into us!), ie 
the approach you've been taking.

Whereas the REPR, as described, allows one to literally start from 
nothing and conjure a solution out of 'thin-air' (or perhaps in this 
case: learn by experimenting, line-by-line).


I think you've got the bit between your teeth (if you'll pardon the pun) 
and must be scenting victory...


Web-Refs:
https://docs.spyder-ide.org/variableexplorer.html
https://docs.spyder-ide.org/debugging.html
-- 
Regards =dn

From alan.gauld at yahoo.co.uk  Fri Oct 25 06:10:39 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 25 Oct 2019 11:10:39 +0100
Subject: [Tutor] Running multiple python scripts from one python scripts
References: <1ocawfle0gtmxiqa6jnxmtee.1571998239583.ref@email.android.com>
Message-ID: <1ocawfle0gtmxiqa6jnxmtee.1571998239583@email.android.com>

On 25 October 2019, at 07:46, ose micah via Tutor <tutor at python.org> wrote:

>That was my very first deployment. Calling the scripts and running them. But, that would not work in my use case. As some of the scripts are been formed in the main scripts.

Are you saying that you have a python program somewhere that is generating python code and you are then, in this program, running those dynamically created scripts?

If so, there is almost certainly a better way of doing things by creating permanent scripts and passing parameters and data to them.

Perhaps if we knew more about these script creation programs we could offer a cleaner solution.

Executing dynamically created code via os.system or subprocess is a big security hole but, if it's python code, you might as well use the exec function which is just as big a hole, but more efficient!

 One of the biggest issues with this kind of approach is the invisibility of any output, you need to rely on shared knowledge of output files or data tables. That implies a lot of checking to make sure that they exist before every access and that they are new versions and you are not reprocessing old data. It all gets very messy in any kind of real world environment.

Alan g.


From s.molnar at sbcglobal.net  Fri Oct 25 07:24:46 2019
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Fri, 25 Oct 2019 07:24:46 -0400
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <60ed02f7-cf61-1bc3-3ea7-b1dbda28d59f@DancesWithMice.info>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
 <5DB0A517.9090407@sbcglobal.net>
 <3249074a-aefc-bc4a-b5d5-87f218594aa7@DancesWithMice.info>
 <5DB1A5C0.3070108@sbcglobal.net>
 <60ed02f7-cf61-1bc3-3ea7-b1dbda28d59f@DancesWithMice.info>
Message-ID: <5DB2DB7E.8030001@sbcglobal.net>



On 10/25/2019 04:38 AM, David L Neil via Tutor wrote:
> On 25/10/19 2:23 AM, Stephen P. Molnar wrote:
>> Thank you for your reply.
>>
>> Here is my code as formatted, with extraneous print statements removed:
>
> Thanks - much easier to read.
>
> Don't forget to review solid advice given in several earlier responses!
>
>
>> Please see my additional comments interspaced below:
>> On 10/23/2019 05:52 PM, David L Neil via Tutor wrote:
>>> On 24/10/19 8:08 AM, Stephen P. Molnar wrote:
>>> Back in FORTRAN we used to write:
> ...
>
>> Lost in the mist of time (the early 1960's) I was barely proficient 
>> in FORTRAN II.
>
> Evidently thought you were someone else, with a FORTRAN history.
>
> Back then I had hundreds of 101-students who became "barely 
> proficient" in F-II, but went-on to do great things!
>
>>> Apparently the same varNM is being used and re-used, for quite 
>>> different purposes!
>
> This (and other earlier critique) still evident (but am assuming 
> you've been addressing, pending this/further replies)
>
>
> ...
>
>>> 1 scan the currentDIR for .log files (existing)
>>> 2 manipulate the fileNM (existing)
>>> 3 dG() it (existing)
>
> (above retained because is expanded, below)
>
>
>>> Apologies, if seeming pedantic, but an incorrect choice of varNM may 
>>> introduce a confusion which prevents comprehension/debugging.
>>>
>> Well, I'm certainly  confused!! (I can be pedantic along with the best.)
>
> We can see that, but are confident that as the 'rules' coalesce in 
> your mind, what we are saying will become clear...
>
>
> The solution is like any other problem in ComSc: break the larger 
> problem down into smaller units, 'rinse and repeat', until the next 
> unit before you is solvable...
>
> Hence the idea that Python's REPR allows one to enter code 
> line-by-line and observe immediate results - quickly proving or 
> disproving a solution-attempt. However, please read on, gentle reader, 
> read on...
>
>
>>> Good idea to use some 'debug prints'! Even better, that if you are 
>>> using r3.8 you can take advantage of a brand-new feature:
> ...
>
>> I have enough problems iwth 3.7.
>
> Few/no other 'upgrades' (such as I have found, to-date) are likely to 
> bother you/us - but that one advantage is quite compelling. (IMHO)
>
> That said, if you are using Anaconda or some similar tool-set, you 
> will need to wait until they offer an r38 update (I don't know if/when).
>
>
>>> To help with learning Python, are you aware that Python allows, even 
>>> enables, you to experiment and thus develop a program, line-by-line?
>>>
>>> - open a terminal window and start python3
>>> - try these two lines (abstracted from the code):
>>>
>>> import glob
>>> glob.glob("*.log")
>>>
>> So far, so good:
>>
>>> #!/usr/bin/env python3
>>> # -*- coding: utf-8 -*-
>>> """
>>> Created on Thu Oct 24 08:48:59 2019
>>>
>>> """
>>>
>>> import glob
>>>
>>> ligands =[]
>>> ligands = glob.glob("*.log")
>
> Good work.
>
> Referring back to the docs-snippet on glob (quoted previously), glob 
> returns a *list*. Python does not require one to declare a variable as 
> having a data-type and/or an initial value - known as "duck typing". 
> In this case, the assignment takes the glob result/list and thus 
> 'says' ligands is (now) a list.
>
> This idea is both a massive advantage and time-save, but as you have 
> read in many of the replies to this thread, also one which can trip-up 
> the unwary and the learner - because one can say, and Python will 
> cheerfully oblige:
>
>     ligands = []    # making ligands a list
>     ligands = "abc"    # making ligands (now) a string, and
>     ligands = 3.14    # making ligands (now) numeric.
>
> NB this would be illegal/rejected by many other languages.
>
> Hence the advice about being careful in one's choice of 
> variable-names, and suggesting that the chosen-name indicate both form 
> and function. Thus (perhaps):
>
>     files_list = glob...
>
> However, most?many style conventions dislike explicit use of 
> type-words, eg list, dict, int; despite it being common in other 
> languages, eg MSFT 'standards' - and the Zen of Python recommending 
> "explicit over implicit". If it helps comprehension, I certainly won't 
> call the 'style police' on you, and particularly not whilst learning!
>
>
>>> - you should see something like (your):
>>>
>>>     ['C-VX3', '15-7', '14-7'] 
>>
>> That's what was returned.
>
> Proof!
>
>
> >> You can continue adding (your) lines of code, one-at-a-time. (in which
> >> case, at least initially, avoid loops and aim to get (only) 'the first
> >> one' to work). Once you have learned the necessary Python syntax and
> >> bent the code to your will, the pertinent/working parts can be copied
> >> into a editor and saved as a file. Then you can install loops (and
> >> indents!) and all the bells-and-whistles your little heart desires...
> >>
> >> Sage advice passed to a (much) younger me: "Make it work, before you
> >> make it better". Python's "REPR" makes enacting such advice SO much
> >> easier!
>
> So, now you can move on to the next sub-problem:
> - you have the (three) file names
> - don't bother with a loop, try to solve the single problem first
> - take the first fileNM
>
>     ligands[ 0 ]
> or
>     glob.glob( "*.log" )[ 0 ]
>
> - split the fileNM
> (and prove (to yourself) that you have the base fileNM and the 
> extension/suffix - see also PSL's os.path.split().)
> - assemble the output fileNM
> (per the idea of ignoring the loop, above, ignore the function and 
> test/prove the code using the first fileNM, without thought of 
> repetition)
> - check the np.get
> - attempt the output file-save
> - inspect the results using your system's 'file manager'
>
> Et voil??!
>
>
>>> Now, you have an exact illustration and on-screen evidence of what 
>>> is happening!
>
> QED on the code-building, and QED on proving the algorithm!
>
> Thereafter collect the working code (ignoring any side-trips, 
> experiments, or misapprehensions) into a source-code file (document). 
> Then, (having "made it work") you can think about adding loops, 
> splitting functionality, etc (you can "make it better")!
>
> However (at great risk to your sanity)...
>
>
>>> Also, which editor are you using?
>>>
>> Spyder-3.6.6
>
> I know you are climbing the I-must-absorb-enough-Python 
> 'learning-curve', but I recommend that you divert for a moment and 
> take a look at two Spyder features:
>
> [warning: I have long had intentions of reviewing Spyder, but have 
> thus far only perused their web site - so am working from 'promises' 
> (aka "vapor-ware") rather than hard-experience. All due apologies!]
>
>
> 1 Variable Explorer
> - this shows you the contents of each variable in your code, and 
> enables review as the values (should) change. So, it becomes possible 
> to (literally) see when something contains more than one component, 
> when it shouldn't; or to quickly notice if the result is otherwise not 
> what you expected! (without those extra debug-prints)
>
> 2 Debugging
> - this offers (pull down the eponymous top-menu or view web-ref) the 
> ability to pause program execution at any stage and/or to step through 
> the Python code instruction-by-instruction, watching closely for 
> cause-and-effect.
>
> Wonderful stuff. What I wouldn't have given for tools like this, 
> back-when...!
>
>
> The combination of these two facilities offers a powerful alternative 
> mode of attack to the Python REPR approach outlined earlier, depending 
> upon one's preferred approach.
>
> I must admit, coming from the ?good, old days when we planned-out 
> programs - first in flow-charts, and then by hand-writing the code, 
> even on punched-card Coding Sheets; tools such as Spyder offer the 
> opportunity to first 'solve' the entire problem, and then prove it - 
> which feels 'natural' (actually learned/ingrained/beaten into us!), ie 
> the approach you've been taking.
>
> Whereas the REPR, as described, allows one to literally start from 
> nothing and conjure a solution out of 'thin-air' (or perhaps in this 
> case: learn by experimenting, line-by-line).
>
>
> I think you've got the bit between your teeth (if you'll pardon the 
> pun) and must be scenting victory...
>
>
> Web-Refs:
> https://docs.spyder-ide.org/variableexplorer.html
> https://docs.spyder-ide.org/debugging.html

What a great and gracious response.

Thanks to the help from this list, I have achieved success. Here is my code:

> #!/usr/bin/env python3
> # -*- coding: utf-8 -*-
> """
> Created on Fri Oct 11 09:36:30 2019
>
> """
>
> import os
> import glob
> import numpy as np
>
> fileList = []
>
>
> for files in glob.glob("*.log"):
>     fileName, fileExtension = os.path.splitext(files)
>     fileList.append(fileName)
>
> for filename in fileList:
>     data = np.genfromtxt(filename+'.log', usecols=(1), skip_header=27, 
> skip_footer=1, encoding=None)
>     np.savetxt(filename+'-dG', data, fmt='%.15g', header=filename)

Many, many thanks.

-- 
Stephen P. Molnar, Ph.D.
www.molecular-modeling.net
614.312.7528 (c)
Skype:  smolnar1


From mats at wichmann.us  Fri Oct 25 11:08:04 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Fri, 25 Oct 2019 09:08:04 -0600
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DB2DB7E.8030001@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
 <5DB0A517.9090407@sbcglobal.net>
 <3249074a-aefc-bc4a-b5d5-87f218594aa7@DancesWithMice.info>
 <5DB1A5C0.3070108@sbcglobal.net>
 <60ed02f7-cf61-1bc3-3ea7-b1dbda28d59f@DancesWithMice.info>
 <5DB2DB7E.8030001@sbcglobal.net>
Message-ID: <b070242e-fcd0-8a04-8909-d15829ae8f4e@wichmann.us>

On 10/25/19 5:24 AM, Stephen P. Molnar wrote:

> What a great and gracious response.
> 
> Thanks to the help from this list, I have achieved success. Here is my 
> code:

>> import os
>> import glob
>> import numpy as np
>>
>> fileList = []
>>
>>
>> for files in glob.glob("*.log"):
>> ??? fileName, fileExtension = os.path.splitext(files)
>> ??? fileList.append(fileName)
>>
>> for filename in fileList:
>> ??? data = np.genfromtxt(filename+'.log', usecols=(1), skip_header=27, 
>> skip_footer=1, encoding=None)
>> ??? np.savetxt(filename+'-dG', data, fmt='%.15g', header=filename)

Cool... and that code looks concise and expressive - easy to figure out 
what it's doing and why, congratulations!

=== ===

Now, just a few comments, which you can safely ingore since you've 
gotten where you want to.

1. If you use a code checker on this, it's probably going to complain 
about this line:

fileName, fileExtension = os.path.splitext(files)

because you unpack the returned tuple from splitext into two variables, 
but you never use fileExtension.  Python has some syntax for indicating 
that you don't care about a variable, that's the single underscore by 
itself. So if you rewrote the line as:

fileName, _ = os.path.splitext(files)

you would be telling the code checker that you'll intentionally not be 
using the second element.

2. There's a cool new-ish module called pathlib which aims to be more 
expressive in working with, well, file paths.  It has its own methods 
for doing a glob, and for extracting the stem part of a filename (that 
is, without the extension), so the first loop could be rewritten like 
this - again, there's no *need* to do this.

import pathlib

p = Path('.')   # create Path object for this directory
for path in p.glob("*.log"):
     fileList.append(path.stem)


and then, seeing you have a loop where all it does is append to a list, 
you could rewrite that as a list comprehension - some of us find that 
notation more readable, though I know when I first learned about it I 
admit I didn't at first see how it was an improvement, now I do.

fileList = [path.stem for path in p.glob("*.log")]


From osaosemwe at yahoo.com  Fri Oct 25 09:48:55 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Fri, 25 Oct 2019 13:48:55 +0000 (UTC)
Subject: [Tutor] Running multiple python scripts from one python scripts
In-Reply-To: <1ocawfle0gtmxiqa6jnxmtee.1571998239583@email.android.com>
References: <1ocawfle0gtmxiqa6jnxmtee.1571998239583.ref@email.android.com>
 <1ocawfle0gtmxiqa6jnxmtee.1571998239583@email.android.com>
Message-ID: <1364494679.2085812.1572011335639@mail.yahoo.com>

 Hello Alan,?
Here is my use case. I have a master scripts, that dynamically creates python scripts on the fly (from live feeds), at the end of the main script (the master script), This newly created scripts, must be deployed in less than 2 mins max, but, cannot be deployed simultaneously, cos the function each does could affect the other, as a result, they must be deployed sequentially
hence here is my use case.
import fileinputimport osimport sysimport timeimport subprocess as sp......# create script1with open (/tmp/delete_line3.py, 'w+' )?......# create script2with open (/tmp/create_20lines.py, 'w+' )?..........# create script3with open (/tmp/delete_ON2_.py, 'w+' )?..........# create script4with open (/tmp/create_50.py, 'w+' )?......# do? some other task...........# update memory?...........# running the newly created scripts in processesextProc1 = sp.Popen([sys.executable, '/tmp/delete_line3.py'],? stdout=sp.PIPE)time.sleep(5)extProc2 = sp.Popen([?sys.executable,?'/tmp/create_20lines.py'],?stdout=sp.PIPE)time.sleep(5)extProc3 = sp.Popen([sys.executable,'/tmp/?delete_ON2_.py'],?stdout=sp.PIPE)time.sleep(5)
extProc = sp.Popen([sys.executable,'/tmp/?create_50.py'],?stdout=sp.PIPE)time.sleep(5)

# closing the parent version of the pipesextProc1.close()extProc2.close()
extProc3.close()
extProc4.close()

# Waiting for the program to completeextProc1.wait()extProc2.wait()
extProc3.wait()
extProc4.wait()



    On Friday, October 25, 2019, 06:12:45 AM EDT, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:  
 
 
On 25 October 2019, at 07:46, ose micah via Tutor <tutor at python.org> wrote:

>That was my very first deployment. Calling the scripts and running them. But, that would not work in my use case. As some of the scripts are been formed in the main scripts.

Are you saying that you have a python program somewhere that is generating python code and you are then, in this program, running those dynamically created scripts?

If so, there is almost certainly a better way of doing things by creating permanent scripts and passing parameters and data to them.

Perhaps if we knew more about these script creation programs we could offer a cleaner solution.

Executing dynamically created code via os.system or subprocess is a big security hole but, if it's python code, you might as well use the exec function which is just as big a hole, but more efficient!

 One of the biggest issues with this kind of approach is the invisibility of any output, you need to rely on shared knowledge of output files or data tables. That implies a lot of checking to make sure that they exist before every access and that they are new versions and you are not reprocessing old data. It all gets very messy in any kind of real world environment.

Alan g.
  

From alan.gauld at yahoo.co.uk  Fri Oct 25 12:24:04 2019
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 25 Oct 2019 17:24:04 +0100
Subject: [Tutor] Running multiple python scripts from one python scripts
Message-ID: <whn64fxwgbsjp9sd2cl2r9ha.1572020301282@email.android.com>

On 25 October 2019, at 14:48, ose micah <osaosemwe at yahoo.com> wrote:

> dynamically creates python scripts on the fly (from live feeds), 

I'm not sure what you mean by live feeds but can you explain what different kinds of scripts you produce for the first case "delete_line3.py"?

Based on the name it doesn't sound too dynamic in nature? Could it not be turned into a function driven by some parameters?

> This newly created scripts, must be deployed in less than 2 mins max, but, cannot be deployed simultaneously, 

By deployed I assume you mean executed? If so executing the code directly will be much, much, faster than spinning up a subprocess or two for each task.

># create script1
>
>with open (/tmp/delete_line3.py, 'w+' )?
>
>...
>

This is the bit that is puzzling me. Why must this be dynamically created? What prevents it from being prewritten code?

>extProc1 = sp.Popen([sys.executable, '/tmp/delete_line3.py'],? stdout=sp.PIPE)
>

If you must execute dynamically created python code files then using exec(open(fn).read()) is probably preferable to starting a subprocess.



From robertvstepp at gmail.com  Fri Oct 25 14:42:38 2019
From: robertvstepp at gmail.com (boB Stepp)
Date: Fri, 25 Oct 2019 13:42:38 -0500
Subject: [Tutor] How can one know if a Python behavior is meant to be a
 maintained feature or just an implementation artifact?
Message-ID: <CANDiX9JtrjkMHixEMktu4Fsn9QUHaO==Ux7Giifem3qMYOTN8Q@mail.gmail.com>

I was at https://realpython.com/python-zip-function/ and read, "In
Python 3.6 and beyond, dictionaries are ordered collections, meaning
they keep their elements in the same order in which they were
introduced. If you take advantage of this feature, then you can use
the Python zip() function to iterate through multiple dictionaries in
a safe and coherent way: ..."  This immediately raised the question in
my mind:  How can I _know_ that I can rely on dictionary elements
being ordered in all future versions of Python >= 3.6?  And more
generally, how can I tell when a consistent behavior is simply an
implementation artifact or if it is an actual feature meant to be
maintained in all future Python versions?

-- 
boB

From mats at wichmann.us  Fri Oct 25 14:52:55 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Fri, 25 Oct 2019 12:52:55 -0600
Subject: [Tutor] How can one know if a Python behavior is meant to be a
 maintained feature or just an implementation artifact?
In-Reply-To: <CANDiX9JtrjkMHixEMktu4Fsn9QUHaO==Ux7Giifem3qMYOTN8Q@mail.gmail.com>
References: <CANDiX9JtrjkMHixEMktu4Fsn9QUHaO==Ux7Giifem3qMYOTN8Q@mail.gmail.com>
Message-ID: <4ac5235f-4933-ae44-c51e-6423982dc1f7@wichmann.us>

On 10/25/19 12:42 PM, boB Stepp wrote:
> I was at https://realpython.com/python-zip-function/ and read, "In
> Python 3.6 and beyond, dictionaries are ordered collections, meaning
> they keep their elements in the same order in which they were
> introduced. If you take advantage of this feature, then you can use
> the Python zip() function to iterate through multiple dictionaries in
> a safe and coherent way: ..."  This immediately raised the question in
> my mind:  How can I _know_ that I can rely on dictionary elements
> being ordered in all future versions of Python >= 3.6?  And more
> generally, how can I tell when a consistent behavior is simply an
> implementation artifact or if it is an actual feature meant to be
> maintained in all future Python versions?

The "implementation detail" was made a language feature in 3.7, so the 
documentation now says it's a guaranteed feature.

If you want to be more sure you can use an OrderedDict - that works for 
all versions.

Normally the official documentation will take pains to tell you - if 
some behavior should not be counted on; and for that which can be 
counted on, in which Python version it became official. Here's an 
example which is really old:

https://docs.python.org/3/library/functions.html#id

It may mean you need to check the docs for several versions, however. 
python.org docs have a drop-down to select the version, but only 
includes those versions that are considered "current".



From robertvstepp at gmail.com  Fri Oct 25 15:37:14 2019
From: robertvstepp at gmail.com (boB Stepp)
Date: Fri, 25 Oct 2019 14:37:14 -0500
Subject: [Tutor] How can one know if a Python behavior is meant to be a
 maintained feature or just an implementation artifact?
In-Reply-To: <4ac5235f-4933-ae44-c51e-6423982dc1f7@wichmann.us>
References: <CANDiX9JtrjkMHixEMktu4Fsn9QUHaO==Ux7Giifem3qMYOTN8Q@mail.gmail.com>
 <4ac5235f-4933-ae44-c51e-6423982dc1f7@wichmann.us>
Message-ID: <CANDiX9KymD+wo-9ykkptf0W70rvFis=dfQ6cX6yQOxiYa6GUDw@mail.gmail.com>

On Fri, Oct 25, 2019 at 1:54 PM Mats Wichmann <mats at wichmann.us> wrote:

> The "implementation detail" was made a language feature in 3.7, so the
> documentation now says it's a guaranteed feature.

So if a language behavior makes it into the official documentation,
the intent is to now maintain that behavior in all future versions?

Are there any examples of language behaviors making it into the
documentation only to be altered or deprecated a version or two later?

> If you want to be more sure you can use an OrderedDict - that works for
> all versions.

I am mildly surprised that this now remains in the standard library.
Is this solely for pre-version 3.6 compatibility concerns?  Is the
game plan to eventually deprecate OrderedDict and later remove it?

> Normally the official documentation will take pains to tell you - if
> some behavior should not be counted on; and for that which can be
> counted on, in which Python version it became official. ..

Hmm.  Seems there is room for some grayness here.  How many assumed
behaviors are there in Python that are not explicitly documented, but
have become second nature to developers?  I have no clue.  Just
speculating... ~(:>))


-- 
boB

From alan.gauld at yahoo.co.uk  Fri Oct 25 16:46:56 2019
From: alan.gauld at yahoo.co.uk (Alan G)
Date: Fri, 25 Oct 2019 21:46:56 +0100
Subject: [Tutor] New features(sorry lost the original subject!)
In-Reply-To: <CANDiX9KymD+wo-9ykkptf0W70rvFis=dfQ6cX6yQOxiYa6GUDw@mail.gmail.com>
Message-ID: <7938881c-2423-4de1-b48b-b986b7192c48@email.android.com>

   On 25 Oct 2019 20:37, boB Stepp <robertvstepp at gmail.com> wrote:

     ?Are there any examples of language behaviors making it into the
     documentation only to be altered or deprecated a version or two later?

   Generally new features that have any doubts about their future are
   described as experimental and carry the caveat that they may change or
   even be dropped in future versions.?
   Alan G?

From mats at wichmann.us  Fri Oct 25 17:36:27 2019
From: mats at wichmann.us (Mats Wichmann)
Date: Fri, 25 Oct 2019 15:36:27 -0600
Subject: [Tutor] How can one know if a Python behavior is meant to be a
 maintained feature or just an implementation artifact?
In-Reply-To: <CANDiX9KymD+wo-9ykkptf0W70rvFis=dfQ6cX6yQOxiYa6GUDw@mail.gmail.com>
References: <CANDiX9JtrjkMHixEMktu4Fsn9QUHaO==Ux7Giifem3qMYOTN8Q@mail.gmail.com>
 <4ac5235f-4933-ae44-c51e-6423982dc1f7@wichmann.us>
 <CANDiX9KymD+wo-9ykkptf0W70rvFis=dfQ6cX6yQOxiYa6GUDw@mail.gmail.com>
Message-ID: <e166a264-0664-223d-c428-a021e58b431e@wichmann.us>

On 10/25/19 1:37 PM, boB Stepp wrote:

>> If you want to be more sure you can use an OrderedDict - that works for
>> all versions.
> 
> I am mildly surprised that this now remains in the standard library.
> Is this solely for pre-version 3.6 compatibility concerns?  Is the
> game plan to eventually deprecate OrderedDict and later remove it?

I would assume so, but you can also just stop using it...

See:

https://twitter.com/raymondh/status/773978885092323328

>> Normally the official documentation will take pains to tell you - if
>> some behavior should not be counted on; and for that which can be
>> counted on, in which Python version it became official. ..
> 
> Hmm.  Seems there is room for some grayness here.  How many assumed
> behaviors are there in Python that are not explicitly documented, but
> have become second nature to developers?  I have no clue.  Just
> speculating... ~(:>))

It's a really good question (for any complex software system, not just 
Python).  In the case of Python, there are alternative implementations - 
and any time people try to "implement to the spec" it usually does a 
good job of flushing out assumptions vs. promises.  For Python, there 
have been quite a lot of these, this is not even a complete list:

- IronPython (Python running on .NET)
- Jython (Python running on the Java Virtual Machine)
- PyPy (A fast python implementation with a JIT compiler)
- Stackless Python (Branch of CPython supporting microthreads)
- MicroPython (Python running on micro controllers)

as well as in some ways Cython (wikipedia: Cython is a programming 
language that aims to be a superset of the Python programming language, 
designed to give C-like performance with code that is written mostly in 
Python with optional additional C-inspired syntax)

and it turns out that a good place to find out about such cases is to go 
to those projects' websites, because invariably somebody has done 
something that doesn't work there that did on good'ol CPython and then 
the research gets to happen on whether it's a bug or a CPython 
implementation detail.  And then the conclusion usually ends up in a FAQ 
or something.




From osaosemwe at yahoo.com  Fri Oct 25 12:55:27 2019
From: osaosemwe at yahoo.com (ose micah)
Date: Fri, 25 Oct 2019 16:55:27 +0000 (UTC)
Subject: [Tutor] Running multiple python scripts from one python scripts
In-Reply-To: <whn64fxwgbsjp9sd2cl2r9ha.1572020301282@email.android.com>
References: <whn64fxwgbsjp9sd2cl2r9ha.1572020301282@email.android.com>
Message-ID: <255622694.2207770.1572022527504@mail.yahoo.com>

 It is dynamic, because i would not know what the content of the python scripts is, The input is unpredictable, it changes randomly everyday (Hence the need for live feeds), based on this constantly changing value, this new python scripts must be created and executed to an endpoint infrastructure.?Do not look at the naming convention for the python scripts, based on the settings in the infrastructures' endpoint, the scripts must be run sequentially, else, one scripts could affects the running of another.
if not I would have ran each as a function. in the main script.?
    On Friday, October 25, 2019, 12:26:09 PM EDT, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:  
 
 On 25 October 2019, at 14:48, ose micah <osaosemwe at yahoo.com> wrote:

> dynamically creates python scripts on the fly (from live feeds), 

I'm not sure what you mean by live feeds but can you explain what different kinds of scripts you produce for the first case "delete_line3.py"?

Based on the name it doesn't sound too dynamic in nature? Could it not be turned into a function driven by some parameters?

> This newly created scripts, must be deployed in less than 2 mins max, but, cannot be deployed simultaneously, 

By deployed I assume you mean executed? If so executing the code directly will be much, much, faster than spinning up a subprocess or two for each task.

># create script1
>
>with open (/tmp/delete_line3.py, 'w+' )?
>
>...
>

This is the bit that is puzzling me. Why must this be dynamically created? What prevents it from being prewritten code?

>extProc1 = sp.Popen([sys.executable, '/tmp/delete_line3.py'],? stdout=sp.PIPE)
>

If you must execute dynamically created python code files then using exec(open(fn).read()) is probably preferable to starting a subprocess.


  

From PyTutor at DancesWithMice.info  Fri Oct 25 18:45:31 2019
From: PyTutor at DancesWithMice.info (David L Neil)
Date: Sat, 26 Oct 2019 11:45:31 +1300
Subject: [Tutor] Pass arguments from bash script to embedded python
 script
In-Reply-To: <5DB2DB7E.8030001@sbcglobal.net>
References: <5DADB66A.5000607@sbcglobal.net>
 <CAMPXz=pUeqDz7MQh-wB55AhugekR-y95pS2A_KfEe+Q-e25RHA@mail.gmail.com>
 <5DB0A517.9090407@sbcglobal.net>
 <3249074a-aefc-bc4a-b5d5-87f218594aa7@DancesWithMice.info>
 <5DB1A5C0.3070108@sbcglobal.net>
 <60ed02f7-cf61-1bc3-3ea7-b1dbda28d59f@DancesWithMice.info>
 <5DB2DB7E.8030001@sbcglobal.net>
Message-ID: <f67017ff-0ea0-09d3-7c24-ceb72194ef0a@DancesWithMice.info>

On 26/10/19 12:24 AM, Stephen P. Molnar wrote:
> Thanks to the help from this list, I have achieved success. Here is my 
> code:
> 
>> #!/usr/bin/env python3
>> # -*- coding: utf-8 -*-
>> """
>> Created on Fri Oct 11 09:36:30 2019
>>
>> """
>>
>> import os
>> import glob
>> import numpy as np
>>
>> fileList = []
>>
>>
>> for files in glob.glob("*.log"):
>> ??? fileName, fileExtension = os.path.splitext(files)
>> ??? fileList.append(fileName)
>>
>> for filename in fileList:
>> ??? data = np.genfromtxt(filename+'.log', usecols=(1), skip_header=27, 
>> skip_footer=1, encoding=None)
>> ??? np.savetxt(filename+'-dG', data, fmt='%.15g', header=filename)
> 
> Many, many thanks.


As @Mats has said: it's working so why mess with it!

For learning interest:

Examine the two loops. What are their purposes?

Consider these two lines:

 >>     fileList.append(fileName)
 >>
 >> for filename in fileList:

We start with fileName and list it. Then we take the list and process 
each element. Could the two loops be compressed into one?

Answer: split the fileName and pass the result directly into the np 
operations.

NB I can understand why one might prefer the two-step approach, if 
that's the way your mind breaks-down the problem, ie shorter code is not 
necessarily 'better' code!



Thanks for the personal note. Previous attempts to respond were blocked 
by SBC's email filter. I do have a (non-Python) question I'd like to 
pose but would be grossly OT 'here'...
-- 
Regards =dn

From alan.gauld at btinternet.com  Mon Oct 14 12:41:36 2019
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 14 Oct 2019 17:41:36 +0100
Subject: [Tutor] GC content: Help with if/else statements:
In-Reply-To: <97be14b8-1813-6f5c-9477-8715e31ed0fb@btinternet.com>
References: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
 <97be14b8-1813-6f5c-9477-8715e31ed0fb@btinternet.com>
Message-ID: <faca6512-1a48-96ff-9243-60221a1d01b4@btinternet.com>

On 13/10/2019 14:38, Alan Gauld via Tutor wrote:

> Python doesn't see this the way you do.
> It sees
> 
> if (character == 'A') or
>    ('T' == true) or
I should clarify that this is not actually what Python
evaluates, it is only intended to illustrate the point.
If you evaluate 'A'==True you will get False because
the character 'A' does not actually equal the boolean
value 'True', even though Python interprets it as
true(note lower case!)...

So what Python really sees is:

if (character == 'A') or
   ('T') or ('G') or ('C'):

Where it evaluates each character as a true boolean
value (but not the actual boolean object "True").

It just occurred to me after posting that I might have
caused (more?) confusion with my "simplification"!
Hopefully my explanation has helped rather than made
it worse.

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


From kharatemihir at gmail.com  Sat Oct 26 12:32:55 2019
From: kharatemihir at gmail.com (Mihir Kharate)
Date: Sat, 26 Oct 2019 11:32:55 -0500
Subject: [Tutor] GC content: Help with if/else statements:
In-Reply-To: <faca6512-1a48-96ff-9243-60221a1d01b4@btinternet.com>
References: <CAH3WxOMbQ3OG+5tK-WTFcVWnUPkW7ggP9wYEvomq6jExUpnZGg@mail.gmail.com>
 <97be14b8-1813-6f5c-9477-8715e31ed0fb@btinternet.com>
 <faca6512-1a48-96ff-9243-60221a1d01b4@btinternet.com>
Message-ID: <CAH3WxOO7VdYr0qJ19_aqEc_CNH+5TJEnEZYCvvHbKx6iutoB5Q@mail.gmail.com>

@Alan Gauld

Yes, I was quite confused. But I kept on working on my script and finally
figured the logic out and re-wrote my script like this:

def play_gc_count():
    for character in input_sequence:
        if character in ('A','T','G','C'):
            x = True
    for character in input_sequence:
        if character not in ('A','T','G','C'):
            x = False
    while x is False:
        w = print('Invalid Sequence')
        break
        w
    while x is True:
        z = gc_count()
        break
        z
play_gc_count()


Thanks for getting back tho! Appreciate it!
~Mihir


On Fri, Oct 25, 2019 at 7:58 PM Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 13/10/2019 14:38, Alan Gauld via Tutor wrote:
>
> > Python doesn't see this the way you do.
> > It sees
> >
> > if (character == 'A') or
> >    ('T' == true) or
> I should clarify that this is not actually what Python
> evaluates, it is only intended to illustrate the point.
> If you evaluate 'A'==True you will get False because
> the character 'A' does not actually equal the boolean
> value 'True', even though Python interprets it as
> true(note lower case!)...
>
> So what Python really sees is:
>
> if (character == 'A') or
>    ('T') or ('G') or ('C'):
>
> Where it evaluates each character as a true boolean
> value (but not the actual boolean object "True").
>
> It just occurred to me after posting that I might have
> caused (more?) confusion with my "simplification"!
> Hopefully my explanation has helped rather than made
> it worse.
>
> --
> 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 at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From jjk.saji at gmail.com  Sat Oct 26 23:55:01 2019
From: jjk.saji at gmail.com (Joseph John)
Date: Sun, 27 Oct 2019 07:55:01 +0400
Subject: [Tutor] Appreciating the time and effort
Message-ID: <CAKeuxjBiQp3YgY2nBD7DfiVE8etUO6Po0Y+bLsUMKBi6V-qYMA@mail.gmail.com>

Hi,
Good morning
I am member of the mailing list, but not active.
When I check tutor mailing list, I see so many active members traying to
clear the doubt and helping others
Like to give a big thanks to all those posts
I really appreciate  the way you are helping other through this mailing
list 0
Thanks
Joseph John