[Tutor] comparison on Types

2015-04-29 Thread Ian D
I was looking at the example code below. I am using python 2.7.

I am wondering why when I substitute the while n! = "guess" to while n!= guess 
(<-- no quotes) I get a problem?

The Type string is used for the first conditional comparison in the outer While 
loop, but afterwards the Type is an int.

I would have expected the guess variable to be used as Type int as it seems to 
be cast in the raw_input statement and would be comparable to another int 
that's stored in variable n. Thanks


import random
n = random.randint(1, 99)
guess = int(raw_input("Enter an integer from 1 to 99: "))
while n != "guess":
print
if guess < n:
print "guess is low"
guess = int(raw_input("Enter an integer from 1 to 99: "))
elif guess> n:
print "guess is high"
guess = int(raw_input("Enter an integer from 1 to 99: "))
else:
print "you guessed it!"
break
print 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comparison on Types

2015-04-29 Thread Ian D
Ok thanks. I thought it would be better with just a while True loop; for simple 
clarity.


> Date: Wed, 29 Apr 2015 21:14:06 +1000
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] comparison on Types
>
> On Wed, Apr 29, 2015 at 09:44:28AM +, Ian D wrote:
>
>> I was looking at the example code below. I am using python 2.7.
>>
>> I am wondering why when I substitute the while n! = "guess" to while
>> n!= guess (<-- no quotes) I get a problem?
>
> Really? What sort of problem? It looks okay to me, although I haven't
> run it.
>
>
>> The Type string is used for the first conditional comparison in the
>> outer While loop, but afterwards the Type is an int.
>>
>> I would have expected the guess variable to be used as Type int as it
>> seems to be cast in the raw_input statement and would be comparable to
>> another int that's stored in variable n. Thanks
>
> I'm having difficulty understanding your question. It might help if you
> explain what you think the code should do, versus what it actually does.
> Do you get an error? Then post the full error traceback, starting from
> the line "Traceback" to the end.
>
> It also might help to understand that in Python, *variables* don't have
> types, but values do. Variables can take any value, and take on the type
> of that value until such time as they change to a different value:
>
> py> x = "Hello"
> py> type(x)
> 
> py> x = 23
> py> type(x)
> 
>
>
>
>
> Looking at your code, I can see only one obvious (to me) problem:
>
>> import random
>> n = random.randint(1, 99)
>> guess = int(raw_input("Enter an integer from 1 to 99: "))
>> while n != "guess":
>
> By using the string "guess", you guarantee that n is *never* equal on
> the first test. That means that the loop will be entered. If you remove
> the quotation marks, and compare n != guess (here guess is the variable,
> not the literal string) then if your guess happens to be correct on the
> first time, the while loop will not be entered and the program will just
> end.
>
> print
>> if guess < n:
>> print "guess is low"
>> guess = int(raw_input("Enter an integer from 1 to 99: "))
>> elif guess> n:
>> print "guess is high"
>> guess = int(raw_input("Enter an integer from 1 to 99: "))
>> else:
>> print "you guessed it!"
>> break
>> print
>
>
> Try this instead:
>
>
> import random
> n = random.randint(1, 99)
> guess = 0 # Guaranteed to not equal n.
> while n != guess:
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> print
> if guess < n:
> print "guess is too low"
> elif guess> n:
> print "guess is too high"
> else:
> print "guessed correctly!"
>
>
>
>
> Does that help?
>
>
>
> --
> Steve
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Coordinates TK and Turtle

2014-01-28 Thread Ian D
Hello 

I have some weird results when I run my code which is meant to display a canvas 
and a turtle and some text with the turtles coordinates. 

Basically the turtle coordinates do not seem to correspond with the TK 
create_text coordinates. 


t1.goto(100,100) 

canvas_id = cv1.create_text(t1.xcor(), t1.ycor(), 
font=("Purisa",12),anchor="nw") 

cv1.insert(canvas_id, 0, t1.pos()) 

I end up with this output: 
http://i1025.photobucket.com/albums/y319/duxbuz/coord-issues_zps1fca6d2b.jpg 

Could anyone help please? 

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


[Tutor] importing my module imports only one function

2014-01-30 Thread Ian D
if I create a module called "modtest.py" like this:
 
import turtle
 
def square():
for i in range(4):
turtle.fd(100)
turtle.lt(90)
 
def tri():
for i in range(3):
turtle.fd(100)
turtle.lt(120)
 
 
if __name__ == "__main__":

tri()
 
And then call it like this:
 
import sys
sys.path.append("D:\python\modules")
import  modtest
 
modtest.square()
modtest.tri()
 
why would I just get ability to call the 'square()' function and not the 
'tri()' function.
 
I get a square and a trace back:
 
line 7, in 
modtest.tri()
AttributeError: 'module' object has no attribute 'tri'
 
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] is an alias a variable

2014-01-31 Thread Ian D
Hi
 
is 
import longModuleName  as lmn
 
or 
 
lmn = longModuleName
 
creating an alias or assigning to a variable. or both?
 
Thanks
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] creating Turtle() object using 2 different ways

2014-01-31 Thread Ian D
Hi
 
Another quickie.
 
I can create turtle objects (if that's the correct terminology) using 2 
different ways, both work.
 
t1 = turtle.Turtle()
 or
t2 = turtle
 
But which is the best practice... and why?
 
 
 
 
import turtle
 
t1 = turtle.Turtle()
 
t2 = turtle
 
t1.fd(100)
 
t2.goto(-100,100)
t2.fd(100)
 
 
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] auto completion before initially running program

2014-01-31 Thread Ian D
I notice that until a program has been run once, and I presume loaded its 
imports, I cannot use auto completion.
 
I don't suppose there is a way to have it load modules in a way that would give 
me access to the module functions straight away other than running the program
 
I presume there is no way around this.
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Best version for novice

2014-02-01 Thread Ian D
Hi 

Is it better to use python 3 as a newcomer who isn't really going to be writing 
any software as such just using it for learning?

Also in 2.7 I use no subprocess by giving my python exe a -n argument, 
otherwise my canvas program's freeze.

Is this needed also in version 3?

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


[Tutor] most useful ide

2014-02-02 Thread Ian D
Hi
 
Are there any recommendations for python ide's
 
currently I am using idle, which seems pretty decent but am open to any 
suggestions
 
 
cheers
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] most useful ide

2014-02-03 Thread Ian D
Thanks for all the responses
 
I was mainly looking for a more user friendly ide in a windows environment with 
things like command completion etc. Like something a novice might use. I 
suppose vi is simple and available for windows  but I don't suppose there would 
be command completion even in vim. I don't really use emacs much so not that.
 
I suppose idle will suffice, I just wondered if there was another ide simple 
like idle but a little more helpful like eclipse,  but not eclipse. ha ha.
 
Ok its a poor question
 
ps. I know idle has command completion, but just wondered if there is something 
with a few more bells and whistles. 
 
 
 

 
From: dux...@hotmail.com
To: tutor@python.org
Date: Sun, 2 Feb 2014 08:25:16 +
Subject: [Tutor] most useful ide




Hi
 
Are there any recommendations for python ide's
 
currently I am using idle, which seems pretty decent but am open to any 
suggestions
 
 
cheers
  

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


[Tutor] input python 3.3

2014-02-04 Thread Ian D
Hello
 
I used to use 2.7 and the input was pretty when inputting a numeric value, it 
would just get cast to an int.
 
Seems that 3.3 I have to cast each input so :
float(num1 = input("Enter a number")
 
Is this just they way it is now? Is there a way to get back to just typing:
 num1 = input("Enter a number ")
 in python 33.
 
Seems a backwards step unless (and am sure this is the case)it is beneficial in 
so many other ways?
 
Thanks
 
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] input syntax I just posted totally wrong

2014-02-04 Thread Ian D
 
 
 
num1 = float(input("enter a number "))
 
I meant
 
not
 
float(num1 = input("Enter a number"))
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] conditionals or comparison or expressions terminology

2014-02-04 Thread Ian D
Hi
 
Are:
 
<=
==
!=
 
simple conditionals statements, conditionals, comparison operators, conditional 
expressions or what?
 
I am looking at a few different pages and am unsure what I should be calling 
these expressions.
 
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html#simple-conditions
 
http://www.tutorialspoint.com/python/python_basic_operators.htm
 
http://docs.python.org/2/library/stdtypes.html#truth-value-testing
 
Thanks
 
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] sys.path.append import python3 not working

2014-02-05 Thread Ian D
Hi
 
 
Seem when I run a module I created with
import sys
sys.path.append("d:\modules")
 
import myMod
 
it works great in 2.7
but in 3.3 it doesn't 
 
I get an error in 3.3:
import myMod
ImportError: No module named 'myMod'
 
I have tried it with append("d:\\modules") append("d:/\modules")
 
Anyone help please?
 
Thanks
 
 
 
 
p.s. Apologies for poor etiquette so far as have been double posting and 
replying direct to replies. Will try and stop making these mistakes. 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sys.path.append import python3 not working

2014-02-05 Thread Ian D
Ok I seem to be having some success with it at the moment after moving the 
location of the module.
 
From: dux...@hotmail.com
To: tutor@python.org
Date: Wed, 5 Feb 2014 11:09:35 +
Subject: [Tutor] sys.path.append import python3 not working




Hi
 
 
Seem when I run a module I created with
import sys
sys.path.append("d:\modules")
 
import myMod
 
it works great in 2.7
but in 3.3 it doesn't 
 
I get an error in 3.3:
import myMod
ImportError: No module named 'myMod'
 
I have tried it with append("d:\\modules") append("d:/\modules")
 
Anyone help please?
 
Thanks
 
 
 
 
p.s. Apologies for poor etiquette so far as have been double posting and 
replying direct to replies. Will try and stop making these mistakes. 
  

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


Re: [Tutor] sys.path.append import python3 not working

2014-02-05 Thread Ian D
Ok even more strangely it is working in the original location.
 
Am now not 100% sure that I have the folder structure correct.
 
I will keep a eye on it.
 
Thanks
 
To: tutor@python.org
From: da...@davea.name
Date: Wed, 5 Feb 2014 06:32:46 -0500
Subject: Re: [Tutor] sys.path.append import python3 not working

 Ian D  Wrote in message:
>
 
 
> import sys
> sys.path.append("d:\modules")
 
> I have tried it with append("d:\\modules") append("d:/\modules")
 
The first form is not reasonable, you'd need to double the
 backslash. But your second try should have worked.  Here's what I
 would use:
 
"d:/modules"
or perhaps
r"d:\modules"
"d:\\modules"
 
I would suggest printing sys.path from your code,  just in case.
 
I would then check the actual directory name and module name, 
 especially for case. Windows may not usually care about case, but
 sometimes it does matter.
 
Finally I'd run the python with the -v switch,  and see what it
 tells you.
 
 
-- 
DaveA
 

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


[Tutor] my modules idle doesn't list functions python3.3

2014-02-05 Thread Ian D
Hi
 
In Python 2.7
 
If I create my own modules and call them with
 
import sys
sys.path.append("d:\modules")
 
import myMod
 
and use tab to autocomplete I get a list functions.
myMod.< if I tab this I get a list of my functions
 
(This only works if I have  ran program at least once, then it seems to have 
loaded the module and can display its functions)
 
But if I use Python 3.3
It does not display the functions using autocomplete
 
Anyone know if this is fixable?
 
Thanks
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sys.path.append import python3 not working

2014-02-05 Thread Ian D
The network dictates that it is the only way I can really do it as I cannot 
edit any files directly. I have to append the path on the fly
 
> Date: Wed, 5 Feb 2014 11:51:18 +
> From: m...@timgolden.me.uk
> To: tutor@python.org
> Subject: Re: [Tutor] sys.path.append import python3 not working
> 
> On 05/02/2014 11:46, Ian D wrote:
> > Ok even more strangely it is working in the original location.
> >  
> > Am now not 100% sure that I have the folder structure correct.
> >  
> > I will keep a eye on it.
> 
> You might want to consider whether your approach is the best. One
> usually appends to sys.path when there's something dynamic about the
> location of modules (eg for a plugin mechanism). If your library modules
> are always in, say, d:/modules then just set up a PYTHONPATH env var
> with that in it; or use a .pth file in your python directory. I do the
> latter, altho' it's frowned upon by some for reasons I've never entirely
> understood.
> 
> TJG
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] how can I exit a while loop in turtle graphics

2014-02-11 Thread Ian D
I am trying to exit a while loop whilst using turtle graphics.
I don't seem to have the logic correct at all.
I have tried a few different things

These might seem a bit illogical to you guys but to me they make some sense, 
sadly

I just don't really grasp these while loops and their usage.(obviously) 

I am trying to find a way to use a while loop with the turtle graphics

 
import turtle as t
import sys
def f():
sys.exit()
while True:
t.fd(1)
t.onkey(f, "Up")
t.listen()
 another go 
import turtle as t
import sys
def f():
 pass
while True:
t.fd(1)
 if t.onkey(f, "Up"):
sys.exit()
 t.listen()

 another go 

import turtle as t
import sys
def f():
pass

alive = True

while alive:
t.fd(1)
if t.onkey(f, "Up"):
alive = False

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


[Tutor] can I make a while loop true again

2014-02-11 Thread Ian D
Thanks for the help on the last one.

Is it possible to restart a while loop? This doesn't work at all (surprise 
surprise)

import turtle as t

def start():
global more
more = True

def stop():
global more
more = False

more = True

while True:
while more:

t.onkey(stop, "space")
t.onkey(start, "Up")
t.fd(1)
t.listen()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] can I make a while loop true again

2014-02-13 Thread Ian D
Hi 
It has taken me longer than I thought to get back to this topic. tut.
Anyway thanks. I wondered why array was being mentioned ha ha
So have I got this correct in that when I run a turtle program I am in fact 
using this forever loop, so I do not need to use a while True loop at all 
really in a turtle gui program?

 

> To: tutor@python.org
> From: __pete...@web.de
> Date: Tue, 11 Feb 2014 14:01:47 +0100
> Subject: Re: [Tutor] can I make a while loop true again
> 
> Ian D wrote:
> 
>> Thanks for the help on the last one.
>> 
>> Is it possible to restart a while loop? This doesn't work at all (surprise
>> surprise)
>> 
>> import turtle as t
>> 
>> def start():
>> global more
>> more = True
>> 
>> def stop():
>> global more
>> more = False
>> 
>> more = True
>> 
>> while True:
>> while more:
>> 
>> t.onkey(stop, "space")
>> t.onkey(start, "Up")
>> t.fd(1)
>> t.listen()
> 
> When you want your script to work like a typical GUI application you will 
> soon reach the limits with turtle. turtle tries hard to hide it, but GUIs 
> have an independent loop permanently running listening to user events and 
> small functions to respond these events. 
> 
> To have the turtle start and stop I came up with the following which looks 
> similar to normal GUI code. Instead of the explicit loop there is a function 
> `step_forward` that may or may not reschedule itself depending on the state 
> of the `running` flag.
> 
> 
> 
> import turtle
> 
> def step_forward():
> if running:
> turtle.forward(5)
> # call step_forward() again after 100 milliseconds:
> turtle.ontimer(step_forward, 100) 
> 
> def start():
> global running
> 
> if not running:
> running = True
> step_forward()
> 
> def turn_left():
> turtle.left(10)
> 
> def turn_right():
> turtle.right(10)
> 
> def stop():
> global running
> running = False
> 
> running = False
> 
> turtle.delay(0)
> turtle.onkey(start, "Up")
> turtle.onkey(turn_left, "Left")
> turtle.onkey(turn_right, "Right")
> turtle.onkey(stop, "space")
> 
> turtle.listen()
> turtle.mainloop()
> 
> As a bonus the turtle changes its direction when you hit the left or right 
> array.
> 
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] bit shifting

2014-05-01 Thread Ian D
I am trying to follow some code. It is basically a python scratch interfacing 
script.



Anyway part of the script has this code.



Searching google for >> greater than signs in code with python has its issues. 



Can anyone clarify this stuff.



I know its about 4 bytes of data. It looks like its setting all bits HIGH to 
me?   



n = len(cmd)
a = array('c')
a.append(chr((n>> 24) & 0xFF))
a.append(chr((n>> 16) & 0xFF))
a.append(chr((n>>  8) & 0xFF))
a.append(chr(n & 0xFF))





More code for context for python version 2.7:



from array import array
   import socket
   import time
   import sys
   
   from Tkinter import Tk
   from tkSimpleDialog import askstring
   root = Tk()
   root.withdraw()
   
   PORT = 42001
   HOST = askstring('Scratch Connector', 'IP:')
   if not HOST:
   sys.exit()
   
   print("Connecting...")
   scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   scratchSock.connect((HOST, PORT))
   print("Connected!")
   
   def sendScratchCommand(cmd):
   n = len(cmd)
   a = array('c')
   a.append(chr((n>> 24) & 0xFF))
   a.append(chr((n>> 16) & 0xFF))
   a.append(chr((n>>  8) & 0xFF))
   a.append(chr(n & 0xFF))
   scratchSock.send(a.tostring() + cmd)
   
   while True:
   msg = askstring('Scratch Connector', 'Send Broadcast:')
   if msg:
   sendScratchCommand('broadcast "' + msg + '"')



Another for Python 3:

import socket

HOST = 'localhost'
PORT = 42001

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

def sendCMD(cmd):
n = len(cmd)
a = []
a.append((n>> 24) & 0xFF)
a.append((n>> 16) & 0xFF)
a.append((n>> 8) & 0xFF)
a.append(n & 0xFF)
b = ''
for i in list(range(len(a))):
b  += a[i]
s.send(bytes(b+cmd,'UTF-8'))

sendCMD('broadcast"hello"')   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] 2s complement binary for negative

2014-05-01 Thread Ian D
Can anyone clarify please?


Just reading this:

https://wiki.python.org/moin/BitwiseOperators


The section on 2's complement binary for negative integers.


It states:


"Thus the number -5 is treated by bitwise operators as if it were written 
"...111011". "


I am wondering why would this not be -4?


I though -5 would be written ..1010


5 being 101b


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


Re: [Tutor] bit shifting

2014-05-01 Thread Ian D
Ok I am getting somewhere with this now.


A bitshift followed by ANDing the result of the shift!


So I think n>> 24 & 0xFF


is 


shift n 3 bytes right, save results in n and then AND n with 255 decimal?


> From: dux...@hotmail.com
> To: tutor@python.org
> Date: Thu, 1 May 2014 08:08:17 +
> Subject: [Tutor] bit shifting
>
> I am trying to follow some code. It is basically a python scratch interfacing 
> script.
>
>
>
> Anyway part of the script has this code.
>
>
>
> Searching google for>> greater than signs in code with python has its issues.
>
>
>
> Can anyone clarify this stuff.
>
>
>
> I know its about 4 bytes of data. It looks like its setting all bits HIGH to 
> me?
>
>
>
> n = len(cmd)
> a = array('c')
> a.append(chr((n>> 24) & 0xFF))
> a.append(chr((n>> 16) & 0xFF))
> a.append(chr((n>> 8) & 0xFF))
> a.append(chr(n & 0xFF))
>
>
>
>
>
> More code for context for python version 2.7:
>
>
>
> from array import array
> import socket
> import time
> import sys
>
> from Tkinter import Tk
> from tkSimpleDialog import askstring
> root = Tk()
> root.withdraw()
>
> PORT = 42001
> HOST = askstring('Scratch Connector', 'IP:')
> if not HOST:
> sys.exit()
>
> print("Connecting...")
> scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> scratchSock.connect((HOST, PORT))
> print("Connected!")
>
> def sendScratchCommand(cmd):
> n = len(cmd)
> a = array('c')
> a.append(chr((n>> 24) & 0xFF))
> a.append(chr((n>> 16) & 0xFF))
> a.append(chr((n>> 8) & 0xFF))
> a.append(chr(n & 0xFF))
> scratchSock.send(a.tostring() + cmd)
>
> while True:
> msg = askstring('Scratch Connector', 'Send Broadcast:')
> if msg:
> sendScratchCommand('broadcast "' + msg + '"')
>
>
>
> Another for Python 3:
>
> import socket
>
> HOST = 'localhost'
> PORT = 42001
>
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect((HOST, PORT))
>
> def sendCMD(cmd):
> n = len(cmd)
> a = []
> a.append((n>> 24) & 0xFF)
> a.append((n>> 16) & 0xFF)
> a.append((n>> 8) & 0xFF)
> a.append(n & 0xFF)
> b = ''
> for i in list(range(len(a))):
> b += a[i]
> s.send(bytes(b+cmd,'UTF-8'))
>
> sendCMD('broadcast"hello"')
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bit shifting

2014-05-01 Thread Ian D
But what is the purpose of ANDing with 255?


Would this not just return the same value?


eg 1010 and with  would just return 1010 or 1010





> From: dux...@hotmail.com
> To: tutor@python.org
> Date: Thu, 1 May 2014 09:53:15 +
> Subject: Re: [Tutor] bit shifting
>
> Ok I am getting somewhere with this now.
>
>
> A bitshift followed by ANDing the result of the shift!
>
>
> So I think n>> 24 & 0xFF
>
>
> is
>
>
> shift n 3 bytes right, save results in n and then AND n with 255 decimal?
>
> 
>> From: dux...@hotmail.com
>> To: tutor@python.org
>> Date: Thu, 1 May 2014 08:08:17 +
>> Subject: [Tutor] bit shifting
>>
>> I am trying to follow some code. It is basically a python scratch 
>> interfacing script.
>>
>>
>>
>> Anyway part of the script has this code.
>>
>>
>>
>> Searching google for>> greater than signs in code with python has its issues.
>>
>>
>>
>> Can anyone clarify this stuff.
>>
>>
>>
>> I know its about 4 bytes of data. It looks like its setting all bits HIGH to 
>> me?
>>
>>
>>
>> n = len(cmd)
>> a = array('c')
>> a.append(chr((n>> 24) & 0xFF))
>> a.append(chr((n>> 16) & 0xFF))
>> a.append(chr((n>> 8) & 0xFF))
>> a.append(chr(n & 0xFF))
>>
>>
>>
>>
>>
>> More code for context for python version 2.7:
>>
>>
>>
>> from array import array
>> import socket
>> import time
>> import sys
>>
>> from Tkinter import Tk
>> from tkSimpleDialog import askstring
>> root = Tk()
>> root.withdraw()
>>
>> PORT = 42001
>> HOST = askstring('Scratch Connector', 'IP:')
>> if not HOST:
>> sys.exit()
>>
>> print("Connecting...")
>> scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>> scratchSock.connect((HOST, PORT))
>> print("Connected!")
>>
>> def sendScratchCommand(cmd):
>> n = len(cmd)
>> a = array('c')
>> a.append(chr((n>> 24) & 0xFF))
>> a.append(chr((n>> 16) & 0xFF))
>> a.append(chr((n>> 8) & 0xFF))
>> a.append(chr(n & 0xFF))
>> scratchSock.send(a.tostring() + cmd)
>>
>> while True:
>> msg = askstring('Scratch Connector', 'Send Broadcast:')
>> if msg:
>> sendScratchCommand('broadcast "' + msg + '"')
>>
>>
>>
>> Another for Python 3:
>>
>> import socket
>>
>> HOST = 'localhost'
>> PORT = 42001
>>
>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>> s.connect((HOST, PORT))
>>
>> def sendCMD(cmd):
>> n = len(cmd)
>> a = []
>> a.append((n>> 24) & 0xFF)
>> a.append((n>> 16) & 0xFF)
>> a.append((n>> 8) & 0xFF)
>> a.append(n & 0xFF)
>> b = ''
>> for i in list(range(len(a))):
>> b += a[i]
>> s.send(bytes(b+cmd,'UTF-8'))
>>
>> sendCMD('broadcast"hello"')
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] array('c')

2014-05-01 Thread Ian D
Hi


I have this part of code and am unsure as to the effect of the array('c') part.


Is it creating an array and adding 'c' as its first value?


This does not seem to be the case.


Thanks


n = len(cmd)
   a = array('c')
   a.append(chr((n>> 24) & 0xFF))
   a.append(chr((n>> 16) & 0xFF))
   a.append(chr((n>>  8) & 0xFF))
   a.append(chr(n & 0xFF))
   scratchSock.send(a.tostring() + cmd) 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] array('c')

2014-05-01 Thread Ian D
Thanks

> To: tutor@python.org
> From: breamore...@yahoo.co.uk
> Date: Thu, 1 May 2014 16:40:54 +0100
> Subject: Re: [Tutor] array('c')
> 
> On 01/05/2014 15:38, Ian D wrote:
> > Hi
> >
> > I have this part of code and am unsure as to the effect of the array('c') 
> > part.
> >
> > Is it creating an array and adding 'c' as its first value?
> >
> > This does not seem to be the case.
> >
> > Thanks
> >
> > n = len(cmd)
> > a = array('c')
> > a.append(chr((n>> 24) & 0xFF))
> > a.append(chr((n>> 16) & 0xFF))
> > a.append(chr((n>>  8) & 0xFF))
> > a.append(chr(n & 0xFF))
> > scratchSock.send(a.tostring() + cmd)
> > 
> 
> The 'c' is actually a type code see 
> https://docs.python.org/2/library/array.html#module-array but note that 
> this does *NOT* exist in Python 3.
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask 
> what you can do for our language.
> 
> Mark Lawrence
> 
> ---
> This email is free from viruses and malware because avast! Antivirus 
> protection is active.
> http://www.avast.com
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] While truth

2014-05-20 Thread Ian D
I was reading a tutorial that had these examples in it:


>>> while False:

  print("False is the new True.")


>>> while 6:

  print("Which numbers are True?")


while -1:

  print("Which numbers are True?")


while 0:

  print("Which numbers are True?")



Unfortunately the author never explained these statements.


I was wondering if the gist of a while statement could be explained in the 
context of these examples.


e.g. while False:


means while True is False, which is never True because True is of course True 
not False.


but while 6:


means. err while 6 is True? and this is True because... err.


Anyway I am a  bit lost with this.


Can anyone shed any light please?


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


Re: [Tutor] While truth

2014-05-20 Thread Ian D
Or should I have said While False is True, which is never True, because False 
is False not True


> From: dux...@hotmail.com
> To: tutor@python.org
> Date: Tue, 20 May 2014 08:25:48 +
> Subject: [Tutor] While truth
>
> I was reading a tutorial that had these examples in it:
>
>
 while False:
>
> print("False is the new True.")
>
>
 while 6:
>
> print("Which numbers are True?")
>
>
> while -1:
>
> print("Which numbers are True?")
>
>
> while 0:
>
> print("Which numbers are True?")
>
>
>
> Unfortunately the author never explained these statements.
>
>
> I was wondering if the gist of a while statement could be explained in the 
> context of these examples.
>
>
> e.g. while False:
>
>
> means while True is False, which is never True because True is of course True 
> not False.
>
>
> but while 6:
>
>
> means. err while 6 is True? and this is True because... err.
>
>
> Anyway I am a bit lost with this.
>
>
> Can anyone shed any light please?
>
>
> Thanks.
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] python libraries online

2014-06-19 Thread Ian D
A while back some one linked to the python source and I was able to view the 
whole of its libraries and class files something like this java api site 
http://docs.oracle.com/javase/7/docs/api/


But I cant seem to find what I want now.


I wanted to be able to look at the classes etc


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


Re: [Tutor] python libraries online

2014-06-19 Thread Ian D
Ok Thanks.


I will look on the computer, it seems that the online repository is not so easy 
to search.


i.e If I search csv I get all the changes all the merges... but I just want the 
class file


> Date: Thu, 19 Jun 2014 22:23:01 +1000
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] python libraries online
>
> On Thu, Jun 19, 2014 at 12:18:35PM +, Ian D wrote:
>
>> A while back some one linked to the python source and I was able to
>> view the whole of its libraries and class files something like this
>> java api site http://docs.oracle.com/javase/7/docs/api/
>
> http://hg.python.org/cpython/file/cf70f030a744/Lib/
>
>
> Don't forget that if you have Python installed on your computer, the
> standard library (at least the parts written in Python) will be
> installed on your computer too, and readable.
>
>
>
> --
> Steven
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python libraries online

2014-06-19 Thread Ian D
And I wondered what 'cpython' was when I came across it. I thought they might 
have called it python


> Date: Thu, 19 Jun 2014 22:23:01 +1000
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] python libraries online
>
> On Thu, Jun 19, 2014 at 12:18:35PM +, Ian D wrote:
>
>> A while back some one linked to the python source and I was able to
>> view the whole of its libraries and class files something like this
>> java api site http://docs.oracle.com/javase/7/docs/api/
>
> http://hg.python.org/cpython/file/cf70f030a744/Lib/
>
>
> Don't forget that if you have Python installed on your computer, the
> standard library (at least the parts written in Python) will be
> installed on your computer too, and readable.
>
>
>
> --
> Steven
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python libraries online

2014-06-19 Thread Ian D
What does top post mean?


> To: tutor@python.org
> From: breamore...@yahoo.co.uk
> Date: Thu, 19 Jun 2014 13:46:03 +0100
> Subject: Re: [Tutor] python libraries online
>
> On 19/06/2014 13:37, Ian D wrote:
>> And I wondered what 'cpython' was when I came across it. I thought they 
>> might have called it python
>>
>
> Cpython because it's written in C. Look closely at the repository
> you'll find Jython there as well, it's written in Java. There are
> umpteen other Python versions, IronPython for .Net amongst others.
>
> Please don't top post on this list, it's extremely irritating following
> long threads when this is done.
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> ---
> This email is free from viruses and malware because avast! Antivirus 
> protection is active.
> http://www.avast.com
>
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python libraries online

2014-06-19 Thread Ian D



> Date: Fri, 20 Jun 2014 00:30:49 +1000
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] python libraries online
>
> On Thu, Jun 19, 2014 at 12:59:58PM +, Ian D wrote:
>> What does top post mean?
>
> It means posting at the top of the reply, just as you have done here.
>
> When you reply to an email, the comments you are replying to are quoted
> with greater-than signs> at the start of each line. There are three
> basic places to insert your replies to the comments being quoted: at the
> top, at the bottom, and interleaved through the middle.
>
> Here is an example. Suppose I write an email asking two questions:
>
> Hello, how long should I boil a soft-boiled egg?
> And how many eggs in a dozen?
>
>
> (I didn't say they were *good* questions.) You reply, and my comments are 
> quoted:
>
> === This is top-posting ===
>
> Oh, about 3 minutes, depending on the size of the egg.
> Twelve eggs.
>
> Steven asked:
>> Hello, how long should I boil a soft-boiled egg?
>> And how many eggs in a dozen?
>
>
> === This is bottom-posting ===
>
> Steven asked:
>> Hello, how long should I boil a soft-boiled egg?
>> And how many eggs in a dozen?
>
> Oh, about 3 minutes, depending on the size of the egg.
> Twelve eggs.
>
>
> === This is interleaved posting ===
>
> Steven asked:
>> Hello, how long should I boil a soft-boiled egg?
>
> Oh, about 3 minutes, depending on the size of the egg.
>
>> And how many eggs in a dozen?
>
> Twelve eggs.
>
> ===
>
>
> For detailed, complicated discussions where people are replying to
> multiple points, interleaved posting is by far the best. It is like
> carrying on a conversation:
>
>> Question
> Answer
>> Question
> Answer
>> Point
> Counter-point
>> Question
> Answer
>
>
> The context for each answer is right there, next to the answer. It makes
> the email *much* easier to follow when things get technical and
> complicated.
>
> Top-posting and bottom-posting are okay for short, trivial responses
> where the context is not very important, but sadly they also get used by
> lazy writers who don't care about the people reading the email.
>
> (I hope I do not offend, but I've been dealing with email for close to
> 20 years and in my experience there are a lot of lazy writers. If you've
> ever asked somebody four questions in an email, and they've fired off a
> reply answering one of them and ignoring the other three, you will know
> what I mean.)
>
> Top-posting encourages short, snappy responses, where the context can
> be inferred from the subject line or the first few sentences of the
> quoted comments:
>
>
> Okay see you there.
>> Hey Bill, meet us at the pub tonight?
>
>
> 2pm
>> Sue, what time is the meeting today?
>
>
> Yes.
>> Do you want the 2TB hard drive or a 1TB hard drive?
>
>
> But for technical discussions, short, snappy responses are often not
> very good. A *discussion* may go back and forth over many different
> points, not just one or two sentence replies. For this reason, in
> technical forums like this one, interleaved posting is MUCH preferred.
>
>
>
> --
> Steven
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


Ok and do I leave all this rubbish at the bottom? or edit it. Or is it bad 
practice to edit someone's text
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] write dictionary to file

2014-06-19 Thread Ian D
When trying to write my dictionary to a file I get:


f.write(output)
TypeError: 'tuple' does not support the buffer interface


using this example:




#so far this should read a file
#using dictreader and take a column and join some text onto it


import csv


csvfile= open('StudentListToSort.csv', newline='')
spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|')


#open a file to write to later
f = open('output.csv', 'wb+')


#iterate through dictreader object
for row in spamreader:
if row['year'] == '40': 
username = row['user'] #I put stuff in variables for ease of 
viewing/debugging
email = "".join([username,'@email.com]) # join text


#put output for file in variable first
output = email, row['first'],row['last'],row['password']

#change tuple to list
#outputlist= list(output)

#write results to file   
f.write(output)
print(output)


I then tried to cast the tuple to a list thinking that would help like this:


#change tuple to list
#outputlist= list(output)

#write results to file   
f.write(outputlist)
print(outputlist)


same problem:


f.write(outputlist)
TypeError: 'list' does not support the buffer interface


So is it the csv.DictWriter that is needed here?
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-20 Thread Ian D
This is driving me nuts.


I have tried many different things, but I just do not understand this csv 
library. 


I have tried passing various parameters to the writerow method and I am really 
getting nowhere fast.


I just want to read from a file, join text to column and write to file. 


The writerow section I really do not understand, I copied an example as it 
seems to make zero sense when looking at examples or reading documentation.


I thought the csv library would simplify the task but it seems to complicate 
it. I do not remember having this problem with sed/awk or perl.


#so far this should read a file
#using dictreader and take a column and join some text onto it

import csv

csvfile= open('StudentListToSort.csv', newline='')
spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|')

#open a file to write to later
fields = ['user','first','last','password','year']
csvoutput = open('output.csv', 'wb+')
spamwriter = csv.DictWriter(csvoutput,fieldnames=fields, delimiter=' ')



for row in spamreader:
if row['year'] == '40': 
username = row['user'] 
email = "".join([username,'@email.com]) 

output = row['user'], 
row['first'],row['last'],row['password'],row['year']
spamwriter.writerow([spamreader[fields] for fieldnames in fields])
print(output) 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-20 Thread Ian D
Thanks for your help


I am not much closer in understanding this so I am going to try and start with 
a simpler example for myself.


I will try and write some values to a file as I am struggling even doing this.


TypeError: 'str' does not support the buffer interface

TypeError: 'tuple' does not support the buffer interface


these are the errors I tend to hit.


So until I can write a list or a tuple to a file I will not try and get to 
adventurous.   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-20 Thread Ian D
Thanks


>
> Nonetheless, having re-read your question and having googled a bit, it
> seems that your problem might be related to Python 2 vs. Python 3, see
> here:
> http://stackoverflow.com/questions/24294457/python-typeerror-str-does-not-support-the-buffer-interface
>
> In short: In Python 2 you are expected to open the CSV file in binary
> mode ('wb'). In Python 3 this should be text mode as per the above
> question, else you'll only be able to write "bytes" streams, hence the
> "buffer" interface errors. If you've perhaps been cribbing/using
> Python 2.x examples and documentation while in fact using using Python
> 3, then that would help explain the confusion...?


Ok I see this error and the example shows a different type of syntax.


Rather than a file open for writing:

outfile = open('output.csv', 'wb')


it uses

with open('data.csv', 'w', newline='') as out:



now is this written differently in order to implement this text mode thing or 
is it just the omission of the 'b' on the 'wb' that causes text mode?



and if so could it be written:

outfile = open('output.csv', 'w')



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


Re: [Tutor] write dictionary to file

2014-06-20 Thread Ian D
Ok making some progress by changing the 'wb' to 'w'


>
> Ok I see this error and the example shows a different type of syntax.
>
>
> Rather than a file open for writing:
>
> outfile = open('output.csv', 'wb')
>
>
> it uses
>
> with open('data.csv', 'w', newline='') as out:
>
>
>
> now is this written differently in order to implement this text mode thing or 
> is it just the omission of the 'b' on the 'wb' that causes text mode?
>
>
>
> and if so could it be written:
>
> outfile = open('output.csv', 'w')
>
>
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-20 Thread Ian D

>
> Ok making some progress by changing the 'wb' to 'w'
>


err no.


unstuck again.



import csv

csvfile= open('StudentListToSort.csv', newline='')
spamreader = csv.reader(csvfile,delimiter=',',quotechar='|')
outfile = open('outfile.csv','w')

for row in spamreader:

if row[4] == '6':
print("".join([row[0],'@email.com']),row[1])
email = "".join([row[0],'@email.com'])
output = email,row[1]
outfile.write(output)


outfile.close()


when I start to concatenate the results, it ends up as a Tuple and the write to 
file stuff doesn't like Tuples


TypeError: must be str, not tuple



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


Re: [Tutor] write dictionary to file

2014-06-23 Thread Ian D
Thanks a lot this is really helpful as have been the other posts.


>
> Have you tried reading the documentation? It sounds like you're just
> throwing random bits of code at it and hoping something works.
>
> A better approach is to slow down and try to understand what the csv is
> doing, what it expects from you, and how you can best use it. Ask
> *focused* questions, rather than just blast us with blobs of code over
> and over again.
>



I do actually try and read this stuff and understand it, but when its new it 
really is not so simple.


When you already have a sound footing and experience it becomes elementary and 
its hard to understand why you could not understand it in the first place.


Admittedly I do usually try and botch together code from examples. When working 
for solutions sometimes time becomes an issue, and sometimes shortcuts pay off, 
but in the long run they never really do.


I appreciate your patience and your help I am going to try this example now 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-23 Thread Ian D

>>
>> import csv
>>
>> csvfile= open('StudentListToSort.csv', newline='')
>> spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|')
>
> Are you sure that your input file uses | as a quote character and , as
> the field delimiter?


No I overlooked this


>
>
>> #open a file to write to later
>> fields = ['user','first','last','password','year']
>> csvoutput = open('output.csv', 'wb+')
>
> I'm pretty sure you don't want to use "wb+" mode. Since you're using
> Python 3, I think you should just use "w" mode.
>
> The "b" turns on binary mode, and in Python 3 you don't want that. The
> "+" turns on either "read/write" mode or "append" mode, I don't remember
> which, but either way I don't think it's necessary for what you are
> doing.


Yes I came across this python 3 idiosyncrasy



>
>
>> spamwriter = csv.DictWriter(csvoutput,fieldnames=fields, delimiter=' ')
>
> Now you're turning every , delimiter into a space. Are you sure you want
> that?
>
>


Overlooked this



>> for row in spamreader:
>> if row['year'] == '40':
>> username = row['user']
>> email = "".join([username,'@email.com])
>
> Syntax error: you left out the closing single quote. You need:
>
> email = "".join([username,'@email.com'])
>


I think I may have messed that up editing code for public viewing.




On to your example.



>
> import csv
>
> # Open the file we're reading from.
> csvfile= open('StudentListToSort.csv', newline='')
> # Open a file to write to.
> csvoutput = open('output.csv', 'w', newline='')
>
> fields = ['user', 'first', 'last', 'password', 'year']
>
> # Are you sure you want | as the quote character?
> spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='|')

>
>
> # Still using , as a delimiter, not space.
> spamwriter = csv.DictWriter(csvoutput, fieldnames=fields, delimiter=',')
>
> for row in spamreader:
> if row['year'] == '40':
> email = row['user'] + '@email.com'
> output = [ row[fieldname] for fieldname in fields ]


I am unsure about this syntax [ row[fieldname] for fieldname in fields ]

 

The FOR loop is not in any context I have used before. I have seen 
examples(recently) so its obviously standard practice, but not something I 
would ever think to type. 



> print(output)
> # DictWriter needs a dict, not a list.
> spamwriter.writerow({name: row[name] for name in fields})
> print("Warning: email calculated but never used:", email)


 

And this writerow syntax is something new for me, as are dictionaries( which I 
have tried to read up and understand.)

 

>spamwriter.writerow({name: row[name] for name in fields})

 

This looks like the same loop as the one above but a dictionary using curly 
braces(for dict), its the same unfamiliar way of writing a FOR loop for me.


 

So if I wanted multiple rows in the output csv file I would try:


({name: row[name], row[email, row[first] for name in fields})


which doesn't work as the syntax is invalid, so what would I need to change to 
allow spamwriter.writerow to generate multiple fields?  
   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-23 Thread Ian D
Ok I used :


spamwriter.writerow({'user':email,'first':row['first'],'last':row['last'], 
'password':row['password'] })


Seems to be almost finished thanks


> From: dux...@hotmail.com
> To: tutor@python.org
> Date: Mon, 23 Jun 2014 09:17:44 +
> Subject: Re: [Tutor] write dictionary to file
>
>
>>>
>>> import csv
>>>
>>> csvfile= open('StudentListToSort.csv', newline='')
>>> spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|')
>>
>> Are you sure that your input file uses | as a quote character and , as
>> the field delimiter?
>
>
> No I overlooked this
>
>
>>
>>
>>> #open a file to write to later
>>> fields = ['user','first','last','password','year']
>>> csvoutput = open('output.csv', 'wb+')
>>
>> I'm pretty sure you don't want to use "wb+" mode. Since you're using
>> Python 3, I think you should just use "w" mode.
>>
>> The "b" turns on binary mode, and in Python 3 you don't want that. The
>> "+" turns on either "read/write" mode or "append" mode, I don't remember
>> which, but either way I don't think it's necessary for what you are
>> doing.
>
>
> Yes I came across this python 3 idiosyncrasy
>
>
>
>>
>>
>>> spamwriter = csv.DictWriter(csvoutput,fieldnames=fields, delimiter=' ')
>>
>> Now you're turning every , delimiter into a space. Are you sure you want
>> that?
>>
>>
>
>
> Overlooked this
>
>
>
>>> for row in spamreader:
>>> if row['year'] == '40':
>>> username = row['user']
>>> email = "".join([username,'@email.com])
>>
>> Syntax error: you left out the closing single quote. You need:
>>
>> email = "".join([username,'@email.com'])
>>
>
>
> I think I may have messed that up editing code for public viewing.
>
>
>
>
> On to your example.
>
>
>
>>
>> import csv
>>
>> # Open the file we're reading from.
>> csvfile= open('StudentListToSort.csv', newline='')
>> # Open a file to write to.
>> csvoutput = open('output.csv', 'w', newline='')
>>
>> fields = ['user', 'first', 'last', 'password', 'year']
>>
>> # Are you sure you want | as the quote character?
>> spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='|')
>
>>
>>
>> # Still using , as a delimiter, not space.
>> spamwriter = csv.DictWriter(csvoutput, fieldnames=fields, delimiter=',')
>>
>> for row in spamreader:
>> if row['year'] == '40':
>> email = row['user'] + '@email.com'
>> output = [ row[fieldname] for fieldname in fields ]
>
>
> I am unsure about this syntax [ row[fieldname] for fieldname in fields ]
>
>
>
> The FOR loop is not in any context I have used before. I have seen 
> examples(recently) so its obviously standard practice, but not something I 
> would ever think to type.
>
>
>
>> print(output)
>> # DictWriter needs a dict, not a list.
>> spamwriter.writerow({name: row[name] for name in fields})
>> print("Warning: email calculated but never used:", email)
>
>
>
>
> And this writerow syntax is something new for me, as are dictionaries( which 
> I have tried to read up and understand.)
>
>
>
>>spamwriter.writerow({name: row[name] for name in fields})
>
>
>
> This looks like the same loop as the one above but a dictionary using curly 
> braces(for dict), its the same unfamiliar way of writing a FOR loop for me.
>
>
>
>
> So if I wanted multiple rows in the output csv file I would try:
>
>
> ({name: row[name], row[email, row[first] for name in fields})
>
>
> which doesn't work as the syntax is invalid, so what would I need to change 
> to allow spamwriter.writerow to generate multiple fields?
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-23 Thread Ian D
I will read this when I get a minute, but I must say thanks for the explanation.
 
tutor@python really is the most helpful mailing list EVER!
 
> Date: Tue, 24 Jun 2014 00:54:30 +1000
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] write dictionary to file
> 
> On Mon, Jun 23, 2014 at 09:17:44AM +, Ian D wrote:
> 
> > > for row in spamreader:
> > > if row['year'] == '40':
> > > email = row['user'] + '@email.com'
> > > output = [ row[fieldname] for fieldname in fields ]
> > 
> > I am unsure about this syntax [ row[fieldname] for fieldname in fields ]
> 
> 
> That's called a "list comprehension". It is a way of building up a list 
> as a single expression. Let's start with the old-fashioned way to build 
> a list:
> 
> output = []
> for fieldname in fields:
> output.append( row[fieldname] )
> 
> 
> Or, we can do exactly the same thing, in a single line, with a list 
> comprehension, and get rid of the temporary variables:
> 
> output = [row[fieldname] for fieldname in fields]
> 
> If you remember your high school maths classes, the form of the list 
> comp is rather close to that of mathematical set builder notation:
> 
> http://www.mathsisfun.com/sets/set-builder-notation.html
> 
> Here is a set builder notation, and its English translation:
> 
> {2n+1 : n ∈ {1,2,3,4}}
> 
> This reads as "the set of 2n plus 1, such that n is an element of 
> {1,2,3,4}". Don't be confused by the fact that there is a set inside a 
> set -- this just tells us how to build a new set from an old set.
> 
> So we start with a set {1,2,3,4}, and let n equal each of those numbers 
> in turn. Then we calculate 2n+1, and use that inside the new set we're 
> creating:
> 
> n = 1, so 2n+1 => 3
> n = 2, so 2n+1 => 5
> n = 3, so 2n+1 => 7
> n = 4, so 2n+1 => 9
> 
> and so the final result is the set {3, 5, 7, 9}.
> 
> Enough about sets and mathematics! Now we're going to talk about Python! 
> Python uses the same sort of expression, except it builds a list, not a 
> set, and calls it a "list comprehension" instead of a "list builder". 
> (Don't blame me for that, blame the Haskell programming language which 
> invented this.)
> 
> So, we start with the mathematical set builder:
> 
> {2n+1 : n ∈ {1,2,3,4}}
> 
> 
> Turn the sets into lists:
> 
> [2n+1 : n ∈ [1,2,3,4]]
> 
> 
> Use Python syntax for the formula:
> 
> [2*n+1 : n ∈ [1,2,3,4]]
> 
> 
> Replace the "such that" and "element of" with "for" "in":
> 
> [2*n+1 for n in [1,2,3,4]]
> 
> 
> and now you have a Python list comprehension. If you copy and paste that 
> into a Python interpreter, you'll see this:
> 
> py> [2*n+1 for n in [1,2,3,4]]
> [3, 5, 7, 9]
> 
> 
> 
> > > # DictWriter needs a dict, not a list.
> > > spamwriter.writerow({name: row[name] for name in fields})
> > 
> > And this writerow syntax is something new for me, as are dictionaries
> > (which I have tried to read up and understand.)
> 
> List comprehensions were added to Python in, I think, version 2.2, which 
> was about ten years ago. They turned out to be so useful and popular 
> that now, in Python 3, we have FOUR different kinds of "comprehensions" 
> or builder syntax:
> 
> List comprehensions:
> [2*n+1 for n in [1,2,3,4]]
> 
> Generator expressions (like a list comp, except values are created 
> lazily on demand, rather than all at once):
> (x+1 for x in [2, 4, 6, 8])
> 
> Set comprehensions (like a list comp, except it builds a set rather than 
> a list):
> {char.lower() for char in "Hello World!"}
> 
> Dict comprehensions (like a list comp, except it builds a dictionary of 
> key:value pairs):
> {char: char.lower() for char in "Hello World!"}
> 
> 
> So what is a dict? A dict, short for dictionary, is a table of keys with 
> associated values. Think of them as being like words and definitions:
> 
> words = { 
>   "cat": "a small mammal that purrs",
>   "dog": "man's best friend",
>   "snake": "a lizard with no legs",
>   "ostrich": "biggest bird in the world"
>   }
> 
> 
> The first part, before the colon, is the key. The part after the colon 
> is the value associated with that key. If you want to know the meaning 
> of a word, you look it up in the dictionary:
> 
> py> print(w

[Tutor] Tuple indexing

2015-03-11 Thread Ian D
Hi



I have seen some examples that seem to use a tuple with a method called index()


The original code I was looking at had this sort of thing:



SENSORS =  ('sensor1', 'sensor2')



pin_index = SENSORS.index("sensor1")


so the result is that pin_index the is equal to 0


I then read that a Tuple has no attribute index on this site 
http://www.diveintopython.net/native_data_types/tuples.html


>>> t.index("example") 
Traceback (innermost last): File "", line 1, in ? 
AttributeError: 'tuple' object has no attribute 'index'



The example seems to work with 2.7 and 3.3 for me.





But I don't find much documentation on indexing Tuples using this method.



I am just wondering if there is more specific documentation on using Tuples 
this way



Thanks.



I am using Python 2.7 at moment.



   

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


Re: [Tutor] Tuple indexing

2015-03-12 Thread Ian D
Thanks.


My original approach was to use a list as it seemed to lend itself to that. But 
as I referred back to the code I was adapting from I ended up using that 
example with a Tuple. I may look at changing it again, but for now I need the 
thing to work asap.


> To: tutor@python.org
> From: __pete...@web.de
> Date: Wed, 11 Mar 2015 16:35:09 +0100
> Subject: Re: [Tutor] Tuple indexing
>
> Ian D wrote:
>
>> Hi
>>
>>
>>
>> I have seen some examples that seem to use a tuple with a method called
>> index()
>>
>>
>> The original code I was looking at had this sort of thing:
>>
>>
>>
>
> Hi Ian! Please don't use that much whitespace. It makes your post hard and
> unpleasant to read. Thank you.
>
>
>> SENSORS = ('sensor1', 'sensor2')
>>
>>
>>
>> pin_index = SENSORS.index("sensor1")
>>
>>
>> so the result is that pin_index the is equal to 0
>>
>>
>> I then read that a Tuple has no attribute index on this site
>> http://www.diveintopython.net/native_data_types/tuples.html
>
> Dive into Python is quite old.
>
>>>>> t.index("example")
>> Traceback (innermost last): File "", line 1, in ?
>> AttributeError: 'tuple' object has no attribute 'index'
>>
>>
>>
>> The example seems to work with 2.7 and 3.3 for me.
>
> The tuple.index() method has been added in Python 2.6:
>
> https://docs.python.org/2.6/whatsnew/2.6.html
>
> """
> Tuples now have index() and count() methods matching the list type’s index()
> and count() methods:
>
>>>> t = (0,1,2,3,4,0,1,2)
>>>> t.index(3)
> 3
>>>> t.count(0)
> 2
> (Contributed by Raymond Hettinger)
> """
>
>> But I don't find much documentation on indexing Tuples using this method.
>> I am just wondering if there is more specific documentation on using
>> Tuples this way
>
> Many Python coders don't use tuples to look up an item index; the
> traditional application is to pass multiple values around, e. g.
>
> def extent(thing):
> x = calculate_width(thing)
> y = calculate_height(thing)
> return x, y
>
> width, height = extent(picture)
>
> portrait = width < height
>
> In the example you have to know the index beforehand, by reading the code or
> its documentation rather than going through all items for a matching item.
>
> When you want to treat all items in a tuple uniformly in most cases using a
> tuple is a premature optimisation; use a list or set unless you can name a
> compelling reason not to.
>
> Your sensors example could be solved with a dict:
>
> sensors = {"sensor1": 0, "sensor2": 1}
>
> pin_index = sensors["sensor1"]
>
> This approach will still work well for huge numbers of sensors (constant
> time or O(1)), unlike tuple/list.index() where the average lookup time grows
> with the number of items in the tuple or list (O(n)).
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] escape character regex

2015-03-28 Thread Ian D
Hi


I  run a regex like this:

>pchars = re.compile('\x00\x00\x00') #with or without 'r' for raw

on a string like this:

>data = "['broadcast', 'd8on\x00\x00\x00\x11broadcast', 'd11on']"

>print "found pchars :",pchars.findall(data)

which returns: 

>found pchars : ['\x00\x00\x00']


But if I try to match the extra digits at the end like this:

>pchars = re.compile('\x00\x00\x00\x\d+')

I get an error:

>ValueError: invalid \x escape

Or if I use another ide than idle it actually flags it as an "illegal 
hexadecimal escape sequence"


How could I match the \x00\x00\x00\x11 portion of the string?

I have tried escape sequence \\x

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


Re: [Tutor] escape character regex

2015-03-29 Thread Ian D
Ha ha thanks Danny for the hex message!


I am looking to basically match  2 unknown hex values or a byte at the end of 
the 4 byte sequence.

I realise now I am trying to use a numeric \d expression when it needs to be 
matching 2 nibbles or a byte.


Is there a way to match using some sort of wildcard for the last byte as it 
changes?


Thanks 


> Date: Sat, 28 Mar 2015 20:21:09 -0400
> From: da...@davea.name
> To: tutor@python.org
> Subject: Re: [Tutor] escape character regex
>
> On 03/28/2015 03:37 PM, Ian D wrote:
>> Hi
>>
>>
>> I run a regex like this:
>>
>>> pchars = re.compile('\x00\x00\x00') #with or without 'r' for raw
>
> Which one did you actually want? The 3 byte sequence consisting of
> nulls, or the 12 byte one containing zeroes and backslashes? I'm going
> to assume the former, in which case you cannot use 'r' for raw. Unless
> you've got a null key on your keyboard.
>
>>
>> on a string like this:
>>
>>> data = "['broadcast', 'd8on\x00\x00\x00\x11broadcast', 'd11on']"
>>
>>> print "found pchars :",pchars.findall(data)
>>
>> which returns:
>>
>>> found pchars : ['\x00\x00\x00']
>>
>>
>> But if I try to match the extra digits at the end like this:
>>
>>> pchars = re.compile('\x00\x00\x00\x\d+')
>>
>> I get an error:
>>
>>> ValueError: invalid \x escape
>
> The \x escape sequence must be followed by exactly two hex digits, and
> forms a single byte from them. What did you want that byte to be, and
> why didn't you specify it?
>
>>
>> Or if I use another ide than idle it actually flags it as an "illegal 
>> hexadecimal escape sequence"
>>
>
> The question is not what the various IDE's produce, but what the Python
> compiler produces. So once you started getting errors, you really
> should have just run it in the interactive interpreter, without IDE's
> second-guessing you. Anyway, in 2.7.6's interactive interpreter, I get:
>
>>>> a = '\x00\x00\x00\x\d+'
> ValueError: invalid \x escape
>>>>
>
> So it has nothing to do with re, and is simply the result of trying an
> invalid string literal.
>
> What string were you hoping to get? You mention you wanted to match
> digits at the end (end of what?). Perhaps you wanted a real backslash
> followed by the letter d. In that case, since you cannot use a raw
> string (see my first response paragraph), you need to double the backslash.
>
>>>> a = '\x00\x00\x00\\d+'
>>>> print a
> \d+
>
>
> Your data is funny, too, since it almost looks like it might be a string
> representation of a Python list. But assuming you meant it exactly like
> it is, there is a funny control character following the nulls.
>>
>> How could I match the \x00\x00\x00\x11 portion of the string?
>>
>
> There are no digits in that portion of the string, so I'm not sure why
> you were earlier trying to match digits.
>
> Perhaps you meant you were trying to match the single control character
> x'11'. In that case, you'd want
>
> a = '\x00\x00\x00\x11'
> pchars = re.compile(a)
>
>
> But if you wanted to match an arbitrary character following the nulls,
> you'd want something different.
>
> I think you'd better supply several strings to match against, and show
> which ones you'd expect a match for.
>
> --
> DaveA
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] escape character regex

2015-03-29 Thread Ian D
Ok I got it. 

pchars = re.compile(b'\x00\x00\x00[\0-\xff]')

preceeding b and [0-\xff]






> From: dux...@hotmail.com
> To: tutor@python.org
> Date: Sun, 29 Mar 2015 07:55:01 +
> Subject: Re: [Tutor] escape character regex
>
> Ha ha thanks Danny for the hex message!
>
>
> I am looking to basically match 2 unknown hex values or a byte at the end of 
> the 4 byte sequence.
>
> I realise now I am trying to use a numeric \d expression when it needs to be 
> matching 2 nibbles or a byte.
>
>
> Is there a way to match using some sort of wildcard for the last byte as it 
> changes?
>
>
> Thanks
>
> 
>> Date: Sat, 28 Mar 2015 20:21:09 -0400
>> From: da...@davea.name
>> To: tutor@python.org
>> Subject: Re: [Tutor] escape character regex
>>
>> On 03/28/2015 03:37 PM, Ian D wrote:
>>> Hi
>>>
>>>
>>> I run a regex like this:
>>>
>>>> pchars = re.compile('\x00\x00\x00') &with or without 'r' for raw
>>
>> Which one did you actually want? The 3 byte sequence consisting of
>> nulls, or the 12 byte one containing zeroes and backslashes? I'm going
>> to assume the former, in which case you cannot use 'r' for raw. Unless
>> you've got a null key on your keyboard.
>>
>>>
>>> on a string like this:
>>>
>>>> data = "['broadcast', 'd8on\x00\x00\x00\x11broadcast', 'd11on']"
>>>
>>>> print "found pchars :",pchars.findall(data)
>>>
>>> which returns:
>>>
>>>> found pchars : ['\x00\x00\x00']
>>>
>>>
>>> But if I try to match the extra digits at the end like this:
>>>
>>>> pchars = re.compile('\x00\x00\x00\x\d+')
>>>
>>> I get an error:
>>>
>>>> ValueError: invalid \x escape
>>
>> The \x escape sequence must be followed by exactly two hex digits, and
>> forms a single byte from them. What did you want that byte to be, and
>> why didn't you specify it?
>>
>>>
>>> Or if I use another ide than idle it actually flags it as an "illegal 
>>> hexadecimal escape sequence"
>>>
>>
>> The question is not what the various IDE's produce, but what the Python
>> compiler produces. So once you started getting errors, you really
>> should have just run it in the interactive interpreter, without IDE's
>> second-guessing you. Anyway, in 2.7.6's interactive interpreter, I get:
>>
>>>>> a = '\x00\x00\x00\x\d+'
>> ValueError: invalid \x escape
>>>>>
>>
>> So it has nothing to do with re, and is simply the result of trying an
>> invalid string literal.
>>
>> What string were you hoping to get? You mention you wanted to match
>> digits at the end (end of what?). Perhaps you wanted a real backslash
>> followed by the letter d. In that case, since you cannot use a raw
>> string (see my first response paragraph), you need to double the backslash.
>>
>>>>> a = '\x00\x00\x00\\d+'
>>>>> print a
>> \d+
>>
>>
>> Your data is funny, too, since it almost looks like it might be a string
>> representation of a Python list. But assuming you meant it exactly like
>> it is, there is a funny control character following the nulls.
>>>
>>> How could I match the \x00\x00\x00\x11 portion of the string?
>>>
>>
>> There are no digits in that portion of the string, so I'm not sure why
>> you were earlier trying to match digits.
>>
>> Perhaps you meant you were trying to match the single control character
>> x'11'. In that case, you'd want
>>
>> a = '\x00\x00\x00\x11'
>> pchars = re.compile(a)
>>
>>
>> But if you wanted to match an arbitrary character following the nulls,
>> you'd want something different.
>>
>> I think you'd better supply several strings to match against, and show
>> which ones you'd expect a match for.
>>
>> --
>> DaveA
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Dynamic naming of lists

2015-03-31 Thread Ian D
Hi

I have a list that I am splitting into pairs of values. But the list is dynamic 
in size. It could have 4 values or 6 or more.

I originally split the list into pairs, by using a new list and keep a pair in 
the old list by just popping 2 values. But if the list is longer than 4 values. 
I cannot do this. I can only envision I would need to dynamically create lists. 
How would I do this?

while returned_list_of_items:
for i in range(1):
new_list.append(returned_list_of_items.pop(0)) #pop first value and 
append
new_list.append(returned_list_of_items.pop(0)) #pop second value and 
append

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


Re: [Tutor] Dynamic naming of lists

2015-03-31 Thread Ian D
Thanks I will look into these. The data going in is a list like 
this:['broadcast', '"d8on"', 'broadcast', '"d11on"']

With the output beng something like this.

lst_0 = ['broadcast', '"d8on"']

lst_0 = ['broadcast', '"d11on"']

I have managed to use a dictionary as advised in a post on StackOverflow; not 
quite completed it as I am overwriting my lists each time. From your experience 
is it better to pursue the dictionary route or the zip tuple option. I am in 
python2.7


> Date: Tue, 31 Mar 2015 10:30:04 -0400
> From: da...@davea.name
> To: tutor@python.org
> Subject: Re: [Tutor] Dynamic naming of lists
>
> On 03/31/2015 10:00 AM, Ian D wrote:
>> Hi
>>
>> I have a list that I am splitting into pairs of values. But the list is 
>> dynamic in size. It could have 4 values or 6 or more.
>>
>> I originally split the list into pairs, by using a new list and keep a pair 
>> in the old list by just popping 2 values. But if the list is longer than 4 
>> values. I cannot do this. I can only envision I would need to dynamically 
>> create lists. How would I do this?
>>
>> while returned_list_of_items:
>> for i in range(1):
>> new_list.append(returned_list_of_items.pop(0)) #pop first value and append
>> new_list.append(returned_list_of_items.pop(0)) #pop second value and append
>>
>
> It'd really be a lot clearer if you gave one or more examples of input
> and output data. Like you want list [1,2,3,4] to become [ (1,2), (3,4) ]
>
> I'll guess you want a list of two-tuples. It so happens there's a nice
> built-in for the purpose.
>
> https://docs.python.org/3/library/functions.html#zip
>
>>>> s = [1,2,3,4,5,6,7,8]
>>>> list(zip(*[iter(s)]*2))
> [(1, 2), (3, 4), (5, 6), (7, 8)]
>
>
>
> --
> DaveA
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic naming of lists

2015-03-31 Thread Ian D
Ok Thanks a lot. And sadly not a typo, my bad logic overwriting values!


> To: tutor@python.org
> From: __pete...@web.de
> Date: Tue, 31 Mar 2015 17:50:01 +0200
> Subject: Re: [Tutor] Dynamic naming of lists
>
> Ian D wrote:
>
>> Thanks I will look into these. The data going in is a list like
>> this:['broadcast', '"d8on"', 'broadcast', '"d11on"']
>>
>> With the output beng something like this.
>>
>> lst_0 = ['broadcast', '"d8on"']
>>
>> lst_0 = ['broadcast', '"d11on"']
>
> Is that a typo, did you mean
>
> lst_1 = ['broadcast', '"d11on"']
>
> ? If so us a list. Complete example:
>
>>>> flat_pairs = ['broadcast', '"d8on"', 'broadcast', '"d11on"']
>>>> it = iter(flat_pairs)
>>>> pairs = list(zip(it, it))
>>>> pairs
> [('broadcast', '"d8on"'), ('broadcast', '"d11on"')]
>
> You can then access individual pairs by providing an index into the pairs
> list:
>
>>>> pairs[0]
> ('broadcast', '"d8on"')
>>>> pairs[1]
> ('broadcast', '"d11on"')
>
>> I have managed to use a dictionary as advised in a post on StackOverflow;
>> not quite completed it as I am overwriting my lists each time. From your
>> experience is it better to pursue the dictionary route or the zip tuple
>> option. I am in python2.7
>
> A dictionary is typically used when the keys are not as regular as a
> sequence of integers, e. g. to map a user name to an email address or a word
> to a list of the positions where it occurs in a text.
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor