Re: [Tutor] HELP PLEASE

2019-08-13 Thread Alan Gauld via Tutor
On 13/08/2019 12:09, Sithembewena L. Dube wrote:
> Hi Marissa,
> 
> I really think that you could consider doing an introductory Python
> tutorial and then venture back into solving this problem.

>>> This is the output of my updated code:
>>> Traceback (most recent call last):
>>>  File "/Applications/Python 3.7/exercises .py", line 37, in 
>>>main()

Based on the file name I suspect she is already doing some kind of
tutorial. However, you are right about needing to review some of the
basic concepts.

As a plug I'll just mention my own tutorial linked in my .sig below :-)

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


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


Re: [Tutor] HELP PLEASE

2019-08-13 Thread Sithembewena L. Dube
Hi Marissa,

I really think that you could consider doing an introductory Python
tutorial and then venture back into solving this problem.

Understanding concepts like data types, function syntax and loops makes all
the difference in approaching programming challenges.

Here is a decent and free online Python tutorial to get you going:
https://www.learnpython.org/


Kind regards,
Sithembewena Dube


*Sent with Shift
*

On Tue, Aug 13, 2019 at 12:47 PM Cameron Simpson  wrote:

> On 12Aug2019 15:11, Marissa Russo  wrote:
> >This is my code:
>
> Thank you.
>
> >This is the output of my updated code:
> >Traceback (most recent call last):
> >  File "/Applications/Python 3.7/exercises .py", line 37, in 
> >main()
> >  File "/Applications/Python 3.7/exercises .py", line 33, in main
> >m = mean(data[0])
> >  File "/Applications/Python 3.7/exercises .py", line 29, in mean
> >return(sum(nums)/len(nums))
> >TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> Thank you for this as well, it makes things much clearer.
>
> So, to your code:
>
> >import math
>
> Just a remark: you're not using anything from this module. I presume you
> intend to later.
>
> >def get_numbers():
> >print("This program will compute the mean and standard deviation")
> >file1 = input("Please enter the first filename: ")
> >file2 = input("Please enter the second filename: ")
> >x = open(file1, "r")
> >y = open(file2, "r")
> >nums = x.readlines()
> >nums2 = y.readlines()
>
> As has been mentioned in another reply, readlines() returns a list of
> strings, one for each line of text in the file.
>
> In order to treat these as numbers you need to convert them.
>
> >return nums, nums2
> >
> >def to_ints(strings):
> >num_copy = []
> >for num in nums:
> >num_copy.append(float(num))
> >return num_copy
>
> This returns a list of floats. You might want to rename this function to
> "to_floats". Just for clarity.
>
> >return to_ints(nums), to_ints(nums2)
>
> This isn't reached. I _think_ you need to put this line at the bottom of
> the get_numbers function in order to return two lists of numbers. But it
> is down here, not up there.
>
> >def mean(nums):
> >_sum = 0
> >return(sum(nums)/len(nums))
>
> This is the line raising your exception. The reference to "+" is because
> sum() does addition. It starts with 0 and adds the values you give it,
> but you're handing it "nums".
>
> Presently "nums" is a list of strings, thus the addition of the initial
> 0 to a str in the exception message.
>
> If you move your misplaced "return to_ints(nums), to_ints(nums2)"
> statement up into the get_numbers function you should be better off,
> because then it will return a list of numbers, not strings.
>
> Cheers,
> Cameron Simpson 
> ___
> 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] HELP PLEASE

2019-08-13 Thread Cameron Simpson

On 12Aug2019 15:11, Marissa Russo  wrote:

This is my code:


Thank you.


This is the output of my updated code:
Traceback (most recent call last):
 File "/Applications/Python 3.7/exercises .py", line 37, in 
   main()
 File "/Applications/Python 3.7/exercises .py", line 33, in main
   m = mean(data[0])
 File "/Applications/Python 3.7/exercises .py", line 29, in mean
   return(sum(nums)/len(nums))
TypeError: unsupported operand type(s) for +: 'int' and 'str'


Thank you for this as well, it makes things much clearer.

So, to your code:


import math


Just a remark: you're not using anything from this module. I presume you 
intend to later.



def get_numbers():
   print("This program will compute the mean and standard deviation")
   file1 = input("Please enter the first filename: ")
   file2 = input("Please enter the second filename: ")
   x = open(file1, "r")
   y = open(file2, "r")
   nums = x.readlines()
   nums2 = y.readlines()


As has been mentioned in another reply, readlines() returns a list of 
strings, one for each line of text in the file.


In order to treat these as numbers you need to convert them.


   return nums, nums2

def to_ints(strings):
   num_copy = []
   for num in nums:
   num_copy.append(float(num))
   return num_copy


This returns a list of floats. You might want to rename this function to 
"to_floats". Just for clarity.



   return to_ints(nums), to_ints(nums2)


This isn't reached. I _think_ you need to put this line at the bottom of 
the get_numbers function in order to return two lists of numbers. But it 
is down here, not up there.



def mean(nums):
   _sum = 0
   return(sum(nums)/len(nums))


This is the line raising your exception. The reference to "+" is because 
sum() does addition. It starts with 0 and adds the values you give it, 
but you're handing it "nums".


Presently "nums" is a list of strings, thus the addition of the initial 
0 to a str in the exception message.


If you move your misplaced "return to_ints(nums), to_ints(nums2)" 
statement up into the get_numbers function you should be better off, 
because then it will return a list of numbers, not strings.


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


Re: [Tutor] HELP PLEASE

2019-08-13 Thread David L Neil

On 13/08/19 7:11 AM, Marissa Russo wrote:

This is my code:

import math

def get_numbers():
 print("This program will compute the mean and standard deviation")
 file1 = input("Please enter the first filename: ")
 file2 = input("Please enter the second filename: ")
 x = open(file1, "r")
 y = open(file2, "r")
 nums = x.readlines()
 nums2 = y.readlines()

 return nums, nums2



Do you understand the concept of a "loop" - Code which is repeated as 
many times as necessary?


How many files must be opened, read, and then averaged?



def to_ints(strings):
 num_copy = []
 for num in nums:
 num_copy.append(float(num))
 return num_copy

 return to_ints(nums), to_ints(nums2)


What is the purpose of this line, given that the previous line has 
returned to the calling code?


Have I missed something? When is to_ints() used?



def mean(nums):
 _sum = 0
 return(sum(nums)/len(nums))

def main():
 data = get_numbers()
 m = mean(data[0])


Do you know what data[ 0 ] (or [ 1 ]) contains?
Might this knowledge be helpful?



 m2 = mean(data[1])
 print("The mean of the first file is: ", m)
 print("The mean of the second file is: ", m2)
main()


This is the output of my updated code:

Traceback (most recent call last):
   File "/Applications/Python 3.7/exercises .py", line 37, in 
 main()
   File "/Applications/Python 3.7/exercises .py", line 33, in main
 m = mean(data[0])
   File "/Applications/Python 3.7/exercises .py", line 29, in mean
 return(sum(nums)/len(nums))
TypeError: unsupported operand type(s) for +: 'int' and 'str'


What do you think "TypeError" means? Do you know the difference between 
an "int" and a "str[ing]"?


Given that both sum() and len() return numbers, what do you think is the 
"str"? Might this refer back to the earlier suggestion that you need to 
'see' the data being read?


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


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Marissa Russo
This is my code:

import math

def get_numbers():
print("This program will compute the mean and standard deviation")
file1 = input("Please enter the first filename: ")
file2 = input("Please enter the second filename: ")
x = open(file1, "r")
y = open(file2, "r")
nums = x.readlines()
nums2 = y.readlines()

return nums, nums2

def to_ints(strings):
num_copy = []
for num in nums:
num_copy.append(float(num))
return num_copy

return to_ints(nums), to_ints(nums2)

def mean(nums):
_sum = 0
return(sum(nums)/len(nums))

def main():
data = get_numbers()
m = mean(data[0])
m2 = mean(data[1])
print("The mean of the first file is: ", m)
print("The mean of the second file is: ", m2)
main()


This is the output of my updated code:

Traceback (most recent call last):
  File "/Applications/Python 3.7/exercises .py", line 37, in 
main()
  File "/Applications/Python 3.7/exercises .py", line 33, in main
m = mean(data[0])
  File "/Applications/Python 3.7/exercises .py", line 29, in mean
return(sum(nums)/len(nums))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
> On Aug 12, 2019, at 12:54 PM, Marissa Russo  wrote:
> 
> Hello,
> 
> I am trying to figure out what is going on and why my output is saying 
> “” instead of giving me a number. Please let me know if 
> you see the error in my code!!
> 
> import math
> 
> def get_numbers():
>print("This program will compute the mean and standard deviation")
>file1 = input("Please enter the first filename: ")
>file2 = input("Please enter the second filename: ")
>x = open(file1, "r")
>y = open(file2, "r")
>nums = x.readlines()
>nums2 = y.readlines()
> 
>return nums, nums2
> 
> def mean(nums):
>for num in nums:
>_sum += num
>return _sum / len(nums)
> 
> def mean2(nums2):
>for num in nums2:
>_sum += nums2
>return _sum / len(nums2)
> 
> def main():
>data = get_numbers()
> 
>print("The mean of the first file is: ", mean)
>print("The mean of the second file is: ", mean2)
> main()
> 

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


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Mats Wichmann
On 8/12/19 10:54 AM, Marissa Russo wrote:
> Hello,
> 
> I am trying to figure out what is going on and why my output is saying 
> “” instead of giving me a number. Please let me know if 
> you see the error in my code!!

to quickly illustrate the specific question you asked - you got comments
on other stuff already:


>>> def foo():
... return "string from foo()"
...
>>> print(foo)

>>> print(foo())
string from foo()
>>>


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


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Alan Gauld via Tutor
On 12/08/2019 17:54, Marissa Russo wrote:

> def mean(nums):
> for num in nums:
> _sum += num
> return _sum / len(nums)
> 
> def mean2(nums2):
> for num in nums2:
> _sum += nums2
> return _sum / len(nums2)
> 
> def main():
> data = get_numbers()
> 
> print("The mean of the first file is: ", mean)
> print("The mean of the second file is: ", mean2)

Notice that in the print statement you use the names
of the functions.
Python therefore evaluates those names and discovers
that they are functions, so that's what it tells you.

To get the values you need to call the functions,
which you do by adding parens to the name:

 print("The mean of the first file is: ", mean(data[0]) )
 print("The mean of the second file is: ", mean2(data[1]) )

That will then execute the functions

Which leads us to the next problem.
In both functions you have a line like:

_sum += num

But that expands to

_sum = _sum + num

Which means you are trying to get a value from _sum
before assigning any value. You need to initialize
_sum before using it like that.

_sum = 0

But better still would be to use the builtin sum method:

sum(nums)

So your mean function turns into:

def mean(nums):
   return( sum(nums)/len(nums))

But that leads to the next problem which is that your data
is still in string format, which is what you read from the
file with getlines().
You can convert it to integers using a list comprehension
inside your get_numbers function:

nums = [int(s) for s in nums]

which assumes the file is a list of numbers each on one line?

If you are not familiar with the list comprehension shortcut
you can do it longhand like this:

num_copy = []
for num in nums:
num_copy.append(int(num))
nums = num_copy

Incidentally, the two mean functions look identical
to me. What do you think is different other than
the names?

Finally, you could just use the mean() function defined in
the statistics library of the standard library.

import statistics as stats
...
 print("The mean of the first file is: ", stats.mean(data[0]) )
 ...

That should be enough to be getting on with.

Once you get those things done you could post again and
we might suggest some ways to tidy the code up a little.

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


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


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Sithembewena L. Dube
In your calls to the `*print*` function, you  are not calling the `*mean*`
and `*mean2*` functions that you declared to calculate averages. So Python
sees you trying to concatenate two function objects to strings and is not
happy. That's one thing.

Secondly, your code could be refactored to define one `*mean*` function as
your functions do virtually the same thing. Then, you could just call it as
needed.

Thirdly, you could use the `*with*` keyword. See "7.2. Reading and Writing
Files" at https://docs.python.org/3/tutorial/inputoutput.html


Kind regards,
Sithembewena Dube


*Sent with Shift
*

On Mon, Aug 12, 2019 at 7:24 PM Marissa Russo 
wrote:

> Hello,
>
> I am trying to figure out what is going on and why my output is saying
> “” instead of giving me a number. Please let me know
> if you see the error in my code!!
>
> import math
>
> def get_numbers():
> print("This program will compute the mean and standard deviation")
> file1 = input("Please enter the first filename: ")
> file2 = input("Please enter the second filename: ")
> x = open(file1, "r")
> y = open(file2, "r")
> nums = x.readlines()
> nums2 = y.readlines()
>
> return nums, nums2
>
> def mean(nums):
> for num in nums:
> _sum += num
> return _sum / len(nums)
>
> def mean2(nums2):
> for num in nums2:
> _sum += nums2
> return _sum / len(nums2)
>
> def main():
> data = get_numbers()
>
> print("The mean of the first file is: ", mean)
> print("The mean of the second file is: ", mean2)
> main()
>
> ___
> 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] HELP PLEASE

2019-08-12 Thread Joel Goldstick
On Mon, Aug 12, 2019 at 1:22 PM Marissa Russo  wrote:
>
> Hello,
>
> I am trying to figure out what is going on and why my output is saying 
> “” instead of giving me a number. Please let me know if 
> you see the error in my code!!
>

Marissa, you have lots of problems here.  First, you should copy and
paste the complete traceback instead of the snippet you showed.
> import math
>
> def get_numbers():
> print("This program will compute the mean and standard deviation")
> file1 = input("Please enter the first filename: ")
> file2 = input("Please enter the second filename: ")
> x = open(file1, "r")
> y = open(file2, "r")
> nums = x.readlines()
> nums2 = y.readlines()
>
> return nums, nums2
>

Above. You are returning a string of all the data in your files.. is
that what you want?

> def mean(nums):
> for num in nums:
> _sum += num
> return _sum / len(nums)
>
Your traceback probably is complaining about _sum +=.  You can't add
to a variable that doesn't exists.  Maybe try _sum = 0 above your for
loop


> def mean2(nums2):
> for num in nums2:
> _sum += nums2
> return _sum / len(nums2)
>
> def main():
> data = get_numbers()

Ok, so you call a function which will return a tuple with two values
into data.  But you don't do anything with data

You might put this here:

m = mean(data[0])
m2 = mean2(data[1])

then print m and m2
>
> print("The mean of the first file is: ", mean)
> print("The mean of the second file is: ", mean2)
> main()
>

So, first, show the complete error message here.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



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


[Tutor] HELP PLEASE

2019-08-12 Thread Marissa Russo
Hello,

I am trying to figure out what is going on and why my output is saying 
“” instead of giving me a number. Please let me know if 
you see the error in my code!!

import math

def get_numbers():
print("This program will compute the mean and standard deviation")
file1 = input("Please enter the first filename: ")
file2 = input("Please enter the second filename: ")
x = open(file1, "r")
y = open(file2, "r")
nums = x.readlines()
nums2 = y.readlines()

return nums, nums2

def mean(nums):
for num in nums:
_sum += num
return _sum / len(nums)

def mean2(nums2):
for num in nums2:
_sum += nums2
return _sum / len(nums2)

def main():
data = get_numbers()

print("The mean of the first file is: ", mean)
print("The mean of the second file is: ", mean2)
main()

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


Re: [Tutor] Help request ERROR installing beautifulsoup

2019-04-29 Thread Mats Wichmann
On 4/29/19 1:44 AM, Alan Gauld via Tutor wrote:
> On 28/04/2019 17:11, Dr. Luca T wrote:
> ^
>> SyntaxError: Missing parentheses in call to 'print'. Did you mean 
>> print("Unit tests have failed!")?
>> 
> 
>> I use windows 10, python 3.7.3 ...
> 
> The problem is you are running python 2 code using python 3.
> You need to find a python 3 version of your package.
> 

You definitely want beautifulsoup4, not just because the version 3 one
doesn't work with Python 3, but also because the authors tell you not to
use it:

"This package is OBSOLETE. It has been replaced by the beautifulsoup4
package. You should use Beautiful Soup 4 for all new projects."

By the way, if you are using pip to install, it is recommended to use it
through the Python interpreter you intend to use.  Since you're on
Windows, hopefully you've let your install set up the Python Launcher
and then it would look like:

py -m pip install beautifulsoup4


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


Re: [Tutor] Help request ERROR installing beautifulsoup

2019-04-29 Thread Alan Gauld via Tutor
On 28/04/2019 17:11, Dr. Luca T wrote:
^
> SyntaxError: Missing parentheses in call to 'print'. Did you mean 
> print("Unit tests have failed!")?
> 

> I use windows 10, python 3.7.3 ...

The problem is you are running python 2 code using python 3.
You need to find a python 3 version of your package.

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


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


Re: [Tutor] Help request ERROR installing beautifulsoup

2019-04-29 Thread Peter Otten
Dr. Luca T wrote:

> Hi,
> i'm new in python, i tried to install beautifulsoup but i had back this
> error:
> 
> ERROR: Complete output from command python setup.py egg_info:
> ERROR: Traceback (most recent call last):
>   File "", line 1, in 
>   File
>   "C:\Users\Luca\AppData\Local\Temp\pip-install-
u6zd808q\beautifulsoup\setup.py",
>   line 22
> print "Unit tests have failed!"
>   ^
> SyntaxError: Missing parentheses in call to 'print'. Did you mean
> print("Unit tests have failed!")?
> 
> ERROR: Command "python setup.py egg_info" failed with error code 1 in
> C:\Users\Luca\AppData\Local\Temp\pip-install-u6zd808q\beautifulsoup\
> 
> I use windows 10, python 3.7.3 and a minipc with 32-bit technology inside,
> can you help me telling me where i'm wrong please? 

Try installing bs4 instead of beautifulsoup to get a version that works with 
Python 3.

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


[Tutor] Help request ERROR installing beautifulsoup

2019-04-29 Thread Dr. Luca T
Hi,
i'm new in python, i tried to install beautifulsoup but i had back this error:

ERROR: Complete output from command python setup.py egg_info:
ERROR: Traceback (most recent call last):
  File "", line 1, in 
  File 
"C:\Users\Luca\AppData\Local\Temp\pip-install-u6zd808q\beautifulsoup\setup.py", 
line 22
print "Unit tests have failed!"
  ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean 
print("Unit tests have failed!")?

ERROR: Command "python setup.py egg_info" failed with error code 1 in 
C:\Users\Luca\AppData\Local\Temp\pip-install-u6zd808q\beautifulsoup\

I use windows 10, python 3.7.3 and a minipc with 32-bit technology inside, can 
you help me telling me where i'm wrong please? 

Thanks.

Luca Tartufari


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


Re: [Tutor] help with colormode

2019-04-25 Thread Alan Gauld via Tutor
On 25/04/2019 11:54, Mark Alderson wrote:

> tried screen.colormode(255)

Peter has shown you how to make that work but
there is a wee issue below I need to point out.

> -code-
> from turtle import Turtle
> t = Turtle()
> t.speed(0)
> 
> b = 180
> a = 35
> 
> colormode(255)
> 
> t.color((55,55,55))
> for i in range(200):
> t.circle(i,a)
> t.right(b)
> t.circle(i,a)
> 
> 
> #input('Press any key to continue...')
> 
> -
> 
> ===error===
> Traceback (most recent call last):
>   File "H:\python\snowflake.py", line 9, in 
> screen.colormode(255)
> NameError: name 'screen' is not defined
> ===

The error message clearly does not reflect the code above.
In this case its not too bad but in more complex questions
it is very important that you send the actual code that
generates the error. Otherwise we wind up just guessing
at what might be the problem.

Just something for future reference.

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


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


Re: [Tutor] help with colormode

2019-04-25 Thread Peter Otten
Mark Alderson wrote:

> hi
> 
> Ihave a very small program.  I want to cycle colours.  I cant set the
> colormode from 1 to 255
> 
> tried screen.colormode(255)
> 
> tells me screen is not defined.  the program works without the colormode,
> but i want to use it.
> 
> I just change the a and b variable values to generate new art.
> 
> -code-
> from turtle import Turtle
> t = Turtle()
> t.speed(0)
> 
> b = 180
> 
> a = 35
> 
> colormode(255)
> 
> t.color((55,55,55))
> for i in range(200):
> t.circle(i,a)
> t.right(b)
> t.circle(i,a)
> 
> 
> #input('Press any key to continue...')
> 
> -
> 
> ===error===
> Traceback (most recent call last):
>   File "H:\python\snowflake.py", line 9, in 
> screen.colormode(255)
> NameError: name 'screen' is not defined
> ===

The only name you import is Turtle, so you only have that (and the built-
ins). Fortunately you can get the screen from the Turtle, so:

from turtle import Turtle

ninja = Turtle()
ninja.speed(0)

screen = ninja.screen
screen.colormode(255)

b = 180
a = 35

for i in range(200):
ninja.color((i + 55, 55, 55))
ninja.circle(i, a)
ninja.right(b)
ninja.circle(i, a)

screen.exitonclick()


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


[Tutor] help with colormode

2019-04-25 Thread Mark Alderson
hi

Ihave a very small program.  I want to cycle colours.  I cant set the colormode 
from 1 to 255

tried screen.colormode(255)

tells me screen is not defined.  the program works without the colormode, but i 
want to use it.

I just change the a and b variable values to generate new art.

-code-
from turtle import Turtle
t = Turtle()
t.speed(0)

b = 180

a = 35

colormode(255)

t.color((55,55,55))
for i in range(200):
t.circle(i,a)
t.right(b)
t.circle(i,a)


#input('Press any key to continue...')

-

===error===
Traceback (most recent call last):
  File "H:\python\snowflake.py", line 9, in 
screen.colormode(255)
NameError: name 'screen' is not defined
===

any help would be appreciated,
thanks

Mark

City of Glasgow College | Scottish Charity Number SCO36198 | VAT Number 
59677128DISCLAIMER :- This email, together with any attachments, may be 
confidential and the subject of legal privilege. If you are not the intended 
recipient, please notify the sender of this email immediately, delete this 
message and note that you are not permitted to print, copy, disclose or use the 
content in any way. City of Glasgow College does not accept any legal 
responsibility of liability (including in negligence) for the contents of this 
communication, nor does it endorse or accept any personal views represented 
herein. Email communications may be subject to interception by third parties or 
possible data corruption and City of Glasgow College accepts no responsibility 
whatsoever for the content of communications altered after transmission from 
the college network.


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


Re: [Tutor] Help

2019-04-18 Thread fatima butt
Hi Peter,
Thanks soo much ...Its solved...have a nice day !

On Wed, 17 Apr 2019 at 22:48, Peter Otten <__pete...@web.de> wrote:

> fatima butt wrote:
>
> > hi Peter,
> > hope you are well.I am getting the following error when i am running the
> > pygame shell script.I am using Acer SWIFT computer.my python version is
> > 3.7.3 and pygame version is pygame 1.9.5
> >
> > Traceback (most recent call last):
> >   File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line
> >   166, in 
> > draw_text(screen, str(score),18, WIDTH/2,10)
> >   File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line
> 28,
> >   in draw_text
> > font = pygame.font.Font(font_name, size)
> > pygame.error: font not initialized
>
> OK, you now have a different script, with a different error. Does that
> mean
> you resolved your previous problem?
>
> Fine.
>
> Regarding the new error I found the following hint
>
> https://stackoverflow.com/questions/28517979/pygame-font-error
>
> i. e. use
>
> pygame.init()
>
> by entering the error message into a popular search engine ;)
>
> ___
> 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] Help

2019-04-17 Thread Peter Otten
fatima butt wrote:

> hi Peter,
> hope you are well.I am getting the following error when i am running the
> pygame shell script.I am using Acer SWIFT computer.my python version is
> 3.7.3 and pygame version is pygame 1.9.5
> 
> Traceback (most recent call last):
>   File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line
>   166, in 
> draw_text(screen, str(score),18, WIDTH/2,10)
>   File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line 28,
>   in draw_text
> font = pygame.font.Font(font_name, size)
> pygame.error: font not initialized

OK, you now have a different script, with a different error. Does that mean 
you resolved your previous problem?

Fine.

Regarding the new error I found the following hint

https://stackoverflow.com/questions/28517979/pygame-font-error

i. e. use 

pygame.init()

by entering the error message into a popular search engine ;)

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


[Tutor] Help

2019-04-17 Thread fatima butt
hi Peter,
hope you are well.I am getting the following error when i am running the pygame 
shell script.I am using Acer SWIFT computer.my python version is 3.7.3 and 
pygame version is pygame 1.9.5

Traceback (most recent call last):
  File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line 166, in 

draw_text(screen, str(score),18, WIDTH/2,10)
  File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line 28, in 
draw_text
font = pygame.font.Font(font_name, size)
pygame.error: font not initialized
>>> 

my code is as following:
# Pygame template - skeleton for a new pygame project
import pygame
import random
from os import path

img_dir = path.dirname(__file__)


WIDTH = 480
HEIGHT = 600
FPS = 60

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255,255,0)

pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text.surface.get_rect()
text_rect.midtop =(x,y)
surf.blit(text_surface, text_rect)

class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(player_img,(50,38))
self.image.set_colorkey(BLACK)
self.rect =self.image.get_rect()
self.radius = 20
#pygame.draw.circle(self.image, RED,self.rect.center, self.radius)
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT -10
self.speedx = 0

def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = 5
if keystate[pygame.K_RIGHT]:
self.speedx = -5
self.rect.x += self.speedx

def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)

class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_orig = meteor_img
self.image_orig = random.choice(meteor_images)
self.image_orig.set_colorkey(BLACK)
self.image = self.image_orig.copy()
self.rect = self.image.get_rect()
self.radius = int(self.rect.width *.9 / 2)
#pygame.draw.circle(self.image, RED,self.rect.center, self.radius)
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-150,-100)
self.speedy=random.randrange(1,8)
self.speedx=random.randrange(-3,3)
self.rot = 0
self.rot_speed = random.randrange(-8,8)
self.last_update = pygame.time.get_ticks()

def rotate(self):
now = pygame.time.get_ticks()
if now - self.last_update > 50:
self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360
new_image = pygame.transform.rotate(self.image_orig, self.rot)
old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect()
self.rect.center = old_center

def update(self):
self.rotate()
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT +10:
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(1,8)

class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = bullet_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10

def update(self):
self.rect.y += self.speedy
if self.rect.bottom<0:
self.kill()

#Load all game graphics
background = pygame.image.load(path.join(img_dir,"purple.png")).convert()
background_rect = background.get_rect()
player_img = 
pygame.image.load(path.join(img_dir,"playerShip1_blue.png")).convert()
meteor_img = 
pygame.image.load(path.join(img_dir,"meteorBrown_big1.png")).convert()
bullet_img = pygame.image.load(path.join(img_dir,"laserGreen01.png")).convert()
meteor_images = []
meteor_list = 
['meteorBrown_big1.png','meteorBrown_big2.png','meteorBrown_med1.png',
   
'meteorBrown_med1.png','meteorBrown_small1.png','meteorBrown_small2.png',
   'meteorBrown_big1.png']
for img in meteor_list:
meteor_images.append(pygame.image.load(path.join(img_dir,img)).convert())
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m 

[Tutor] Help

2019-04-17 Thread fatima butt
hi Peter,
hope you are well.I am getting the following error when i am running the pygame 
shell script.I am using Acer SWIFT computer.my python version is 3.7.3 and 
pygame version is pygame 1.9.5

Traceback (most recent call last):
  File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line 166, in 

draw_text(screen, str(score),18, WIDTH/2,10)
  File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line 28, in 
draw_text
font = pygame.font.Font(font_name, size)
pygame.error: font not initialized
>>> 

my code is as following:
# Pygame template - skeleton for a new pygame project
import pygame
import random
from os import path

img_dir = path.dirname(__file__)


WIDTH = 480
HEIGHT = 600
FPS = 60

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255,255,0)

pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text.surface.get_rect()
text_rect.midtop =(x,y)
surf.blit(text_surface, text_rect)

class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(player_img,(50,38))
self.image.set_colorkey(BLACK)
self.rect =self.image.get_rect()
self.radius = 20
#pygame.draw.circle(self.image, RED,self.rect.center, self.radius)
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT -10
self.speedx = 0

def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = 5
if keystate[pygame.K_RIGHT]:
self.speedx = -5
self.rect.x += self.speedx

def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)

class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_orig = meteor_img
self.image_orig = random.choice(meteor_images)
self.image_orig.set_colorkey(BLACK)
self.image = self.image_orig.copy()
self.rect = self.image.get_rect()
self.radius = int(self.rect.width *.9 / 2)
#pygame.draw.circle(self.image, RED,self.rect.center, self.radius)
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-150,-100)
self.speedy=random.randrange(1,8)
self.speedx=random.randrange(-3,3)
self.rot = 0
self.rot_speed = random.randrange(-8,8)
self.last_update = pygame.time.get_ticks()

def rotate(self):
now = pygame.time.get_ticks()
if now - self.last_update > 50:
self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360
new_image = pygame.transform.rotate(self.image_orig, self.rot)
old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect()
self.rect.center = old_center

def update(self):
self.rotate()
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT +10:
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(1,8)

class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = bullet_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10

def update(self):
self.rect.y += self.speedy
if self.rect.bottom<0:
self.kill()

#Load all game graphics
background = pygame.image.load(path.join(img_dir,"purple.png")).convert()
background_rect = background.get_rect()
player_img = 
pygame.image.load(path.join(img_dir,"playerShip1_blue.png")).convert()
meteor_img = 
pygame.image.load(path.join(img_dir,"meteorBrown_big1.png")).convert()
bullet_img = pygame.image.load(path.join(img_dir,"laserGreen01.png")).convert()
meteor_images = []
meteor_list = 
['meteorBrown_big1.png','meteorBrown_big2.png','meteorBrown_med1.png',
   
'meteorBrown_med1.png','meteorBrown_small1.png','meteorBrown_small2.png',
   'meteorBrown_big1.png']
for img in meteor_list:
meteor_images.append(pygame.image.load(path.join(img_dir,img)).convert())
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m 

Re: [Tutor] Help with code

2019-03-28 Thread Alan Gauld via Tutor
On 28/03/2019 21:12, lucasbreault2...@gmail.com wrote:
> I’m trying to make a password that must contain a number in it. 

I assume you mean you want to check whether a password
has a number in it? Does it need to be a single digit
or can there be multiple?

> Which method do I use for that?

There is a string method called isdigit() that will
test for a number. You can loop over each character
in the password and apply that method.

This smells a bit like homework so I won't go any further
than that, but if you get stuck send us your code and
we'll try to help some more.



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


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


[Tutor] Help with code

2019-03-28 Thread lucasbreault2400
I’m trying to make a password that must contain a number in it. Which method do 
I use for that?

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


Re: [Tutor] Help

2019-03-20 Thread Alan Gauld via Tutor

On 20/03/19 14:30, Eric Oh Yeah Yeah wrote:

How do I make Python 3 pick a random variable out of a set of variables I
give it?


There are several options but if you look in the random module you 
should find one that suits your particular needs.


choice() or randrange() may be good options.

If that's not enough of a hint come back with more specific details 
about what kind of "set of variables" you are using.


Alan G.


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


[Tutor] Help

2019-03-20 Thread Eric Oh Yeah Yeah
How do I make Python 3 pick a random variable out of a set of variables I
give it?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help Please

2019-02-21 Thread DL Neil

Mario,

On 21/02/19 3:30 AM, Mario Ontiveros wrote:

Hello,
 I am new to python and have been stuck on this for a while. What I am 
trying to do is to remove rows with void, disconnected, and error on lines. The 
code I have does that, the only problem is that it removes my header because 
void is in header. I need to keep header.
with open("PSS.csv","r+") as f:
 new_f = f.readlines()
 f.seek(0)
 for line in new_f:
 if "Void" not in line:
 if "Disconnected" not in line:
 if "Error" not in line:
  f.write(line)
 f.truncate()



Would it be 'safer' to create a separate output file?

Rather than reading the entire file (easily managed if short, but 
unwieldy and RAM-hungry if thousands of records!), consider that a file 
object is an iterable and process it one line/record at a time.


with open( ... ) as f:
header = f.readline()
# deal with the header record
for record in f:
function_keep_or_discard( record )
#etc


In case it helps you to follow the above, and possibly to learn other 
applications of this thinking, herewith:-


An iterable matches a for-each-loop very neatly (by design). It consists 
of two aspects: next() ie give me the next value (thus for each value in 
turn), and the StopIteration exception (when next() asks for another 
value after they have all been processed). The for 'swallows' the 
exception because it is expected. Hence, you don't need to try...except!


Something a lot of pythonistas don't stop to consider, is that once code 
starts iterating an object, the iteration does not 'reset' until 
"exhausted" (unlike your use of f.seek(0) against the output file). 
Accordingly, we can use a 'bare' next() to pick-out the first (header) 
record and then pass the rest of the job (all the other next()s) to a 
for-each-loop:


with open( ... ) as f:
header = next( f )  # grab the first record
# deal with the header record
for record in f:# iterate through the remaining records
#etc

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


Re: [Tutor] Help Please

2019-02-20 Thread Alex Kleider

On 2019-02-20 06:30, Mario Ontiveros wrote:

Hello,
I am new to python and have been stuck on this for a while. What I
am trying to do is to remove rows with void, disconnected, and error
on lines. The code I have does that, the only problem is that it
removes my header because void is in header. I need to keep header.

Any help will be greatly appreciated.

with open("PSS.csv","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "Void" not in line:
if "Disconnected" not in line:
if "Error" not in line:
 f.write(line)
f.truncate()



Mario Ontiveros


Since your file seems to be a csv file, can we assume your 'header' line 
is really a comma separated list of column names?


If so, then using the csv module and specifically csv.DictReader (+/- 
DictWriter) might make things easier for you.

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


Re: [Tutor] Help Please

2019-02-20 Thread Alan Gauld via Tutor
On 20/02/2019 14:30, Mario Ontiveros wrote:
> Hello,
> I am new to python and have been stuck on this for a while. What I am 
> trying to do is to remove rows with void, disconnected, and error on lines. 
> The code I have does that, the only problem is that it removes my header 
> because void is in header. I need to keep header.
> 
> Any help will be greatly appreciated.
> 
> with open("PSS.csv","r+") as f:
> new_f = f.readlines()
> f.seek(0)
> for line in new_f:

I don't know how long your header is but assuming it is
only 1 line you can simply use slicing to remove the first
line:

  for line in new_f[1:]:

If the header is multi line simply change to the first line you need to
process, for example to remove 3 lines use new_f[3:]

> if "Void" not in line:
> if "Disconnected" not in line:
> if "Error" not in line:
>f.write(line)

This only writes the line if all three terms are present. Assuming thats
what you want it might be more obviously written as

if ("Void" in line and
   "Disconnected in line and
   "Error" in line):
  f.write(line)

You could also use a regex to search for all three and if its
a long file that will probably be faster since it only traverses
the list once. The snag is the regex gets complex if you need
all three in any order. But if you know the order in which
the terms arise it's probably the best option.

> f.truncate()

While overwriting the original file works, it's slightly dangerous
in that you lose the original data if anything goes wrong.
The more usual way to do things is to create a new file for writing
then rename it to the original if, and only if, everything works.
You might even rename the original to .bak first to be really safe.

The other advantage of this approach is that you don't need the
readlines)() call but can just process the file line by line
directly which should also be faster.

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


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


Re: [Tutor] Help Please

2019-02-20 Thread Mark Lawrence

On 20/02/2019 14:30, Mario Ontiveros wrote:

Hello,
 I am new to python and have been stuck on this for a while. What I am 
trying to do is to remove rows with void, disconnected, and error on lines. The 
code I have does that, the only problem is that it removes my header because 
void is in header. I need to keep header.

Any help will be greatly appreciated.

with open("PSS.csv","r+") as f:
 new_f = f.readlines()
 f.seek(0)
 for line in new_f:
 if "Void" not in line:
 if "Disconnected" not in line:
 if "Error" not in line:
  f.write(line)
 f.truncate()



Mario Ontiveros



Something like (completely from memory so untested) :-

with open("PSS.csv","r") as inf:
   lines = inf.readlines()

with open("PSS.csv","w") as outf:
   fiter = iter(lines)
   line = next(fiter)
   outf.write(line)
   for line in fiter:
  if "Void" not in line and "Disconnected" not in line and "Error" 
not in line: # probably a simpler way of writing this but I'm knackered :-)

   outf.write(line)
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[Tutor] Help Please

2019-02-20 Thread Mario Ontiveros
Hello,
I am new to python and have been stuck on this for a while. What I am 
trying to do is to remove rows with void, disconnected, and error on lines. The 
code I have does that, the only problem is that it removes my header because 
void is in header. I need to keep header.

Any help will be greatly appreciated.

with open("PSS.csv","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "Void" not in line:
if "Disconnected" not in line:
if "Error" not in line:
 f.write(line)
f.truncate()



Mario Ontiveros


---
Confidentiality Warning: This message and any attachments are intended only for 
the 
use of the intended recipient(s), are confidential, and may be privileged. If 
you are 
not the intended recipient, you are hereby notified that any review, 
retransmission, 
conversion to hard copy, copying, circulation or other use of all or any 
portion of 
this message and any attachments is strictly prohibited. If you are not the 
intended 
recipient, please notify the sender immediately by return e-mail, and delete 
this 
message and any attachments from your system.
---
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help

2019-02-05 Thread Alan Gauld via Tutor
On 05/02/2019 14:15, Peter Otten wrote:

>> Error:
>> ./python2.py: line 1: syntax error near unexpected token `('
> 
> That is not a Python error, that's a complaint of your shell.

Oh, good catch Peter.
I never noticed the start of the line I just read the text and saw the
weird backtick...


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


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


Re: [Tutor] help

2019-02-05 Thread Mats Wichmann


>> Error:
>> ./python2.py: line 1: syntax error near unexpected token `('
> 
> That is not a Python error, that's a complaint of your shell.
> If you make a Python script executable you also have to insert the proper 
> hash-bang line. In the case of Python 2
> 
> #!/usr/bin/python2
> 
> will probably work. Example shell session:
> 
> $ cat tmp.py
> def  demo():
> print "heureka"
> 
> demo()
> $ ./tmp.py
> ./tmp.py: line 1: syntax error near unexpected token `('
> ./tmp.py: line 1: `def  demo():'
or, of course, run it with python explicitly:

$ python tmp.py

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


Re: [Tutor] help

2019-02-05 Thread Peter Otten
Sonia Miglani wrote:

> Hi Team,
> 
> I am learning puthon and trying the following code.
> 
> But getting the following error.
> 
> Please help me in knowing the code in better way.
> 
> 
> OS Linux
> Python version 2.7.13
> 
> 
> 
> def  demo(s, exclaim):
> #"""
>  #   Returns the string 's' repeated 3 times.
>   #  If exclaim is true, add exclamation marks.
> 
> 
> result = s + s + s
> if exclaim:
> result = result + '!!!'
> return result
> 
> 
> def main():
> print demo('Yay', False)  ## YayYayYay
> print demo('Woo Hoo', True)   ## Woo HooWoo HooWoo Hoo!!!
> 
> 
> Error:
> ./python2.py: line 1: syntax error near unexpected token `('

That is not a Python error, that's a complaint of your shell.
If you make a Python script executable you also have to insert the proper 
hash-bang line. In the case of Python 2

#!/usr/bin/python2

will probably work. Example shell session:

$ cat tmp.py
def  demo():
print "heureka"

demo()
$ ./tmp.py
./tmp.py: line 1: syntax error near unexpected token `('
./tmp.py: line 1: `def  demo():'
$ cat tmp2.py
#!/usr/bin/python2

def  demo():
print "heureka"

demo()
$ ./tmp2.py
heureka
$ 


> ./python2.py: line 1: `def  demo(s,exclaim):
> 
> 
> 
> 
> 
> Regards
> Sonia
> ___
> 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] help

2019-02-05 Thread Alan Gauld via Tutor
On 05/02/2019 12:32, Sonia Miglani wrote:

> OS Linux
> Python version 2.7.13

Can you tell us how you are creating the file?
Which editor are you using? It looks like there may be
some spurious characters in your file.

> def  demo(s, exclaim):
> #"""
>  #   Returns the string 's' repeated 3 times.
>   #  If exclaim is true, add exclamation marks.
> 
> 
> result = s + s + s
> if exclaim:
> result = result + '!!!'
> return result
> 
> 
> def main():
> print demo('Yay', False)  ## YayYayYay
> print demo('Woo Hoo', True)   ## Woo HooWoo HooWoo Hoo!!!

It all works perfectly for me.

> Error:
> ./python2.py: line 1: syntax error near unexpected token `('
> ./python2.py: line 1: `def  demo(s,exclaim):

Notice the odd backtick (`) characters?
They aren't in your code above, did you retype it or
actually copy/paste your real code? It is important that
you post the actual code you get the error from.


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


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


[Tutor] help

2019-02-05 Thread Sonia Miglani
Hi Team,

I am learning puthon and trying the following code.

But getting the following error.

Please help me in knowing the code in better way.


OS Linux
Python version 2.7.13



def  demo(s, exclaim):
#"""
 #   Returns the string 's' repeated 3 times.
  #  If exclaim is true, add exclamation marks.


result = s + s + s
if exclaim:
result = result + '!!!'
return result


def main():
print demo('Yay', False)  ## YayYayYay
print demo('Woo Hoo', True)   ## Woo HooWoo HooWoo Hoo!!!


Error:
./python2.py: line 1: syntax error near unexpected token `('
./python2.py: line 1: `def  demo(s,exclaim):





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


Re: [Tutor] Help please

2018-10-12 Thread Alan Gauld via Tutor
On 12/10/18 04:31, Adam Eyring wrote:

> Also, it looks better to use " + " instead of a comma:
> print("Combining these foods will you," + new_food)

It may "look better" but be aware that they don't do
the same thing and the plus sign is a lot less efficient
computationally since it creates a new string for
each addition.

For a simple case like this it won't matter but if
you had a lot of short strings being added together
in a loop it could slow things down quite a bit.

The other problem with the plus sign is that it
requires all arguments to be strings whereas the
comma separated list gets automatically converted
to a string by Python (by calling str(x) ) so is
in general more reliable.

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


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


Re: [Tutor] Help please

2018-10-12 Thread Mark Lawrence

On 12/10/18 04:31, Adam Eyring wrote:

The program works as is in Python3. For Python2, change input to raw_input
and see if that makes it work (I know it worked for me when I had Python2).
Also, it looks better to use " + " instead of a comma:
print("Combining these foods will you," + new_food)

Also, colons and spaces are good practices when using input boxes, such as
food_1=raw_input("Sushi: ")



Please don't top post as it makes reading long threads really irritating.

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

Mark Lawrence

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


Re: [Tutor] Help please

2018-10-12 Thread Adam Eyring
The program works as is in Python3. For Python2, change input to raw_input
and see if that makes it work (I know it worked for me when I had Python2).
Also, it looks better to use " + " instead of a comma:
print("Combining these foods will you," + new_food)

Also, colons and spaces are good practices when using input boxes, such as
food_1=raw_input("Sushi: ")


On Thu, Oct 11, 2018 at 1:23 PM Carlton Banks  wrote:

> https://www.w3schools.com/python/ref_func_input.asp
>
> tor. 11. okt. 2018 18.51 skrev Carlton Banks :
>
> > What are you trying to do?
> >
> > tor. 11. okt. 2018 18.33 skrev Holly Jo :
> >
> >>
> >> I have no clue what I’m doing wrong, I’m a new student
> >>
> >> food_1=input("Sushi")
> >> food_2=input("Quesdilla")
> >> new_food=food_1+food_2
> >> print("Combining these foods will you,",new_food)
> >> input("Press enter to continue")
> >>
> >>
> >> Sent from Mail for Windows 10
> >>
> >> ___
> >> Tutor maillist  -  Tutor@python.org
> >> To unsubscribe or change subscription options:
> >> https://mail.python.org/mailman/listinfo/tutor
> >>
> >
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help please

2018-10-11 Thread Carlton Banks
https://www.w3schools.com/python/ref_func_input.asp

tor. 11. okt. 2018 18.51 skrev Carlton Banks :

> What are you trying to do?
>
> tor. 11. okt. 2018 18.33 skrev Holly Jo :
>
>>
>> I have no clue what I’m doing wrong, I’m a new student
>>
>> food_1=input("Sushi")
>> food_2=input("Quesdilla")
>> new_food=food_1+food_2
>> print("Combining these foods will you,",new_food)
>> input("Press enter to continue")
>>
>>
>> Sent from Mail for Windows 10
>>
>> ___
>> 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] Help please

2018-10-11 Thread Carlton Banks
What are you trying to do?

tor. 11. okt. 2018 18.33 skrev Holly Jo :

>
> I have no clue what I’m doing wrong, I’m a new student
>
> food_1=input("Sushi")
> food_2=input("Quesdilla")
> new_food=food_1+food_2
> print("Combining these foods will you,",new_food)
> input("Press enter to continue")
>
>
> Sent from Mail for Windows 10
>
> ___
> 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] Help please

2018-10-11 Thread Alan Gauld via Tutor
On 11/10/18 04:19, Holly Jo wrote:
> 
> I have no clue what I’m doing wrong, I’m a new student 
> 
> food_1=input("Sushi")
> food_2=input("Quesdilla")
> new_food=food_1+food_2
> print("Combining these foods will you,",new_food)
> input("Press enter to continue")


Please always tell us what has gone wrong. What you
expected and what you got. If there is an error message
send the full error text.

It also helps if you tell us which Python version
and OS you are using.

Based on the above I'm guessing you may be running
this Python v3 code using Python v2. One of the changes
between 3 and 2 is how input() works.

If that's not the case then you need to provide
more details, as requested above.


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


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


[Tutor] Help please

2018-10-11 Thread Holly Jo

I have no clue what I’m doing wrong, I’m a new student 

food_1=input("Sushi")
food_2=input("Quesdilla")
new_food=food_1+food_2
print("Combining these foods will you,",new_food)
input("Press enter to continue")


Sent from Mail for Windows 10

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


Re: [Tutor] help please

2018-10-10 Thread Mirage Web Studio
You are using the same variable name twice.
You may use "rivers" for the dict and "river" for values.
Also use descriptive names for variables. For eg if you correct the above
mistake, the next one will be this line

for rivers in rivers.values():
print (rivers)


and sorry for top positing.


On Wed 10 Oct, 2018, 12:38 Michael Schmitt, 
wrote:

> To whom it may concern:
>
>
> I am trying to teach myself Python and ran into a problem. This is my code
>
>
> # name of rivers and country
>
> rivers = {'nile' : 'egypt', 'ohio' : 'US', 'rhine' : 'germany' }
>
> # prints river name
> for rivers in rivers.keys():
> print (rivers)
>
> #prints country
> for rivers in rivers.values():
> print (rivers)
>
> # prints statement " The (river) is in the country of (country)
> for rivers in rivers:
> print ("The " + rivers.keys() + "is in the country of " +
> rivers.vaules())
>
> I am getting the following error
>  for rivers in rivers.values():
> AttributeError: 'str' object has no attribute 'values'
>
> Thanks for the help.
>
> Sincerely,
>
> Michael S. Schmitt
>
>
> [
> https://ipmcdn.avast.com/images/icons/icon-envelope-tick-round-orange-animated-no-repeat-v1.gif
> ]<
> https://www.avast.com/sig-email?utm_medium=email_source=link_campaign=sig-email_content=webmail_term=icon>
>   Virus-free. www.avast.com<
> https://www.avast.com/sig-email?utm_medium=email_source=link_campaign=sig-email_content=webmail_term=link
> >
> ___
> 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] help please

2018-10-10 Thread Deepak Dixit
On Wed, Oct 10, 2018, 12:37 PM Michael Schmitt 
wrote:

> To whom it may concern:
>
>
> I am trying to teach myself Python and ran into a problem. This is my code
>
>
> # name of rivers and country
>
> rivers = {'nile' : 'egypt', 'ohio' : 'US', 'rhine' : 'germany' }
>
> # prints river name
> for rivers in rivers.keys():
> print (rivers)
>
> #prints country
> for rivers in rivers.values():
> print (rivers)
>
> # prints statement " The (river) is in the country of (country)
>

  Why are you using "for rivers in rivers".
  Replace this for loop with :-

  for river in rivers:
 print ("The " + river + "is in the country of " + rivers.get(river))

for rivers in rivers:
> print ("The " + rivers.keys() + "is in the country of " +
> rivers.vaules())
>
> I am getting the following error
>  for rivers in rivers.values():
> AttributeError: 'str' object has no attribute 'values'
>
> Thanks for the help.
>
> Sincerely,
>
> Michael S. Schmitt
>
>
> [
> https://ipmcdn.avast.com/images/icons/icon-envelope-tick-round-orange-animated-no-repeat-v1.gif
> ]<
> https://www.avast.com/sig-email?utm_medium=email_source=link_campaign=sig-email_content=webmail_term=icon>
>   Virus-free. www.avast.com<
> https://www.avast.com/sig-email?utm_medium=email_source=link_campaign=sig-email_content=webmail_term=link
> >
> ___
> 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] help please

2018-10-10 Thread Abdur-Rahmaan Janhangeer
i think it should have been

for river in rivers instead of
for rivers in rivers

Abdur-Rahmaan Janhangeer
https://github.com/Abdur-rahmaanJ
Mauritius
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help please

2018-10-10 Thread Peter Otten
Michael Schmitt wrote:

> To whom it may concern:
> 
> 
> I am trying to teach myself Python and ran into a problem. This is my code

> I am getting the following error
>  for rivers in rivers.values():
> AttributeError: 'str' object has no attribute 'values'

> # prints river name
> for rivers in rivers.keys():
> print (rivers)

Look closely at the loop above. What is the value of the "rivers" variable 
after the first iteration?

To resolve the problem simply use a different name as the loop variable.

Pro tip: When you loop over a dict you get the keys by default. So:

for river in rivers:
print(river)

> # prints statement " The (river) is in the country of (country)
> for rivers in rivers:
> print ("The " + rivers.keys() + "is in the country of " + 
rivers.vaules())
> 

Here's a logic (and a spelling) error: rivers.keys() comprises all rivers 
and rivers.values() all countries in the dict. You want to loop over 
rivers.items() which gives you (river, country) pairs.

Tip: print() automatically inserts spaces between its arguments. So:

for river, country in rivers.items():
print("River", river, "is in", country)

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


[Tutor] help please

2018-10-10 Thread Michael Schmitt
To whom it may concern:


I am trying to teach myself Python and ran into a problem. This is my code


# name of rivers and country

rivers = {'nile' : 'egypt', 'ohio' : 'US', 'rhine' : 'germany' }

# prints river name
for rivers in rivers.keys():
print (rivers)

#prints country
for rivers in rivers.values():
print (rivers)

# prints statement " The (river) is in the country of (country)
for rivers in rivers:
print ("The " + rivers.keys() + "is in the country of " + rivers.vaules())

I am getting the following error
 for rivers in rivers.values():
AttributeError: 'str' object has no attribute 'values'

Thanks for the help.

Sincerely,

Michael S. Schmitt


[https://ipmcdn.avast.com/images/icons/icon-envelope-tick-round-orange-animated-no-repeat-v1.gif]
Virus-free. 
www.avast.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help understanding base64 decoding

2018-09-13 Thread Cameron Simpson

On 13Sep2018 08:23, Ryan Smith  wrote:

[...] I'm still getting familiar with all of the
different encodings at play. For example the way I currently
understand things is that python supports unicode which ultimately
defaults to being encoded in UTF-8. Hence I'm guessing is  the reason
for converting strings to a bytes object in the first place.


Yeah. "str" is text, using Unicode code points.

To store this in a file, the text must be transcribed in some encoding. The 
default encoding in Python is UTF-8, which has some advantages: the bottom 128 
values are one to one with ASCII, and it is fairly compact when the source text 
live in or near that range.


Windows often works with UTF-16, which is why your source bytes look the way 
they do.


So the path is:

 base64 text (which fits in a conservative subset of ASCII)
 => bytes holding a UTF-16 encoding of your target text
 => decode to a Python str

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


Re: [Tutor] Help understanding base64 decoding

2018-09-13 Thread Ryan Smith
Hi Peter,

Thank you for the explanation! I have been banging my head around this
for almost two days. I'm still getting familiar with all of the
different encodings at play. For example the way I currently
understand things is that python supports unicode which ultimately
defaults to being encoded in UTF-8. Hence I'm guessing is  the reason
for converting strings to a bytes object in the first place. Again
thank you for the assistance!

Ryan

On Thu, Sep 13, 2018 at 2:57 AM, Peter Otten <__pete...@web.de> wrote:
> Ryan Smith wrote:
>
>> Hello All,
>>
>> I am currently working on a small utility that finds any base64
>> encoded strings in files and decodes them. I am having issue
>> understanding how the Base64 module actually works. The regular
>> expression that I am using correctly matches on the encoded strings. I
>> simply want to be able to convert the match of the encoded ascii
>> string to it's decoded ascii equivalent. For example the base64
>> encoded ascii string 'UwB5AHMAdABlAG0ALgBkAGwAbAA=' will decode to
>> 'System.dll' if I use an online base64 decoder. However I get a
>> completely different output when trying to codify this using python
>> 3.6.5:
>>
>import base64
>import binascii
>>
>test_str = 'UwB5AHMAdABlAG0ALgBkAGwAbAA='
> base64.b64decode(test_str)
>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'
>>
>temp = base64.b64decode(test_str)
>binascii.b2a_base64(temp)
>> b'UwB5AHMAdABlAG0ALgBkAGwAbAA=\n'
>>
>> I understand that when decoding and encoding you have to use bytes
>> objects but what I don't understand is why I can't get the proper
>> conversion of the original ascii string. Can someone please point me
>> in the right direction?
>
> Look closely at the odd bytes in
>
>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'
>
> or just do
>
 b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'[::2]
> b'System.dll'
>
> The even bytes are all NUL:
>
 b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'[1::2]
> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>
> This means that your byte string already *is* the original string, encoded
> as UTF-16. You can convert it into a string with
>
 b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'.decode("utf-16")
> 'System.dll'
>
> which will handle non-ascii characters correctly, too.
>
> ___
> 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] Help understanding base64 decoding

2018-09-13 Thread Peter Otten
Ryan Smith wrote:

> Hello All,
> 
> I am currently working on a small utility that finds any base64
> encoded strings in files and decodes them. I am having issue
> understanding how the Base64 module actually works. The regular
> expression that I am using correctly matches on the encoded strings. I
> simply want to be able to convert the match of the encoded ascii
> string to it's decoded ascii equivalent. For example the base64
> encoded ascii string 'UwB5AHMAdABlAG0ALgBkAGwAbAA=' will decode to
> 'System.dll' if I use an online base64 decoder. However I get a
> completely different output when trying to codify this using python
> 3.6.5:
> 
import base64
import binascii
> 
test_str = 'UwB5AHMAdABlAG0ALgBkAGwAbAA='
 base64.b64decode(test_str)
> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'
> 
temp = base64.b64decode(test_str)
binascii.b2a_base64(temp)
> b'UwB5AHMAdABlAG0ALgBkAGwAbAA=\n'
> 
> I understand that when decoding and encoding you have to use bytes
> objects but what I don't understand is why I can't get the proper
> conversion of the original ascii string. Can someone please point me
> in the right direction?

Look closely at the odd bytes in 

> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'

or just do

>>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'[::2]
b'System.dll'

The even bytes are all NUL:

>>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'[1::2]
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

This means that your byte string already *is* the original string, encoded 
as UTF-16. You can convert it into a string with

>>> b'S\x00y\x00s\x00t\x00e\x00m\x00.\x00d\x00l\x00l\x00'.decode("utf-16")
'System.dll'

which will handle non-ascii characters correctly, too.

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


Re: [Tutor] Help with building bytearray arrays

2018-09-11 Thread Peter Otten
Chip Wachob wrote:

> Peter,
> 
> I see that clue "[[".
> 
> The thread history pretty much sums up what is going on up to this point.
> 
> I'll cover it once more:

[snip]

> I hope this helps.

Unfortunately it doesn't as the problem is in my_transfer.
 
> I'm beginning to wonder if Python was the right choice for this
> project.. 

You mean you'd rather debug a segfault in C than an exception with a 
traceback and an error message that is spot on in Python?

You have an error in your program logic, and you'll eventually run into 
those no matter what language you choose.
 
> Thanks to everyone for your comments and patience.

If you are too frustrated to look into the actual problem at the moment you 
can change the following loop

> Earlier discussions here indicated that the best way was to :
> 
> results = []
> 
> for i in range (0, slice_size):
>results.append(transfer(data_out))

by replacing the append() with the extend() method

results = []
for i in range (0, slice_size):
results.extend(transfer(data_out))

for now.



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


Re: [Tutor] Help with building bytearray arrays

2018-09-10 Thread Alan Gauld via Tutor
On 10/09/18 19:15, Chip Wachob wrote:

> So I see why my .join() isn't working.  I'm not sure how to fix it though.

I already showed you the sum() function.

It can take a list of lists and add them together

end_array = sum(results,[])

> My background is in C and other 'historical' languages, so I'm trying
> to get a hold of the way Python handles arrays, which is different
> that the way I've thought for 20+ years.. :)

Yes, as per my other message, Python data structures are
very powerful. They are not just bare chunks of memory.

> I'm beginning to wonder if Python was the right choice for this
> project.. but it's too late for me to switch now.

Looks like a very good choice to me. Almost any other language
would be much more work. :-)


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


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


Re: [Tutor] Help with building bytearray arrays

2018-09-10 Thread Cameron Simpson

On 10Sep2018 10:23, Chip Wachob  wrote:

So, without all the fluff associated with wiggling lines, my function
now looks like this:

def RSI_size_the_loop():
  results = []
  all_together = []   # not certain if I need this, put it in in an
attempt to fix the incompatibility if it existed


You don't need this. all_together doesn't need to be mentioned until you 
initiate it with your bytearray.join.



  for x in range (0, MAX_LOOP_COUNT, slice_size):
 results.append(my_transfer(disp, data_out, slice_size)

 print " results ", x, " = ", results  # show how results grows
on each iteration

  all_together = bytearray().join(results)

  print " all together ", all_together

I can observe results increasing in size and the last time through the loop:

results  48  =
[[bytearray(b'\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')]]


Peter has pointed out that you have a list of list-of-bytearray instead of a 
flat list-of-bytearray.


The inference here is that your my_transfer function is returning a single 
element list-of-bytearray.



So, now when I hit the line:
all_together = bytearray().join(results)

I'm getting the Traceback :

[...]

Traceback (most recent call last):
 File "SW8T_5.py", line 101, in   # this is my main script
   loop_size = RSI_size_the_loop(Print)
 File "/home/temp/Python_Scratch/examples/RSI.py", line 359, in
RSI_size_the_loop
   all_together = bytearray().join(results)
TypeError: can only join an iterable of bytes (item 0 has type 'list')


So because you have a list-of-list, item[0] is indeed a list, not a bytearray.

If you change this:

 results.append(my_transfer(disp, data_out, slice_size)

into:

 result = my_transfer(disp, data_out, slice_size)
 print("result =", repr(result))
 results.append(result)

this should be apparent. So this issue lies with your my_transfer function; the 
main loop above now looks correct.



I've even added in print statements for the types, so I could double
check, and I get:

results returns 
all_together returns 

So both are type 'list' which is referred to here :

https://infohost.nmt.edu/tcc/help/pubs/python/web/sequence-types.html

as a valid sequence type but apparently there's a detail I'm still missing...


Yeah. bytearray().join wants bytes or bytearrays in the list/iterable you hand 
it. You've got lists, with the bytearrays further in.


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


Re: [Tutor] Help with building bytearray arrays

2018-09-10 Thread Chip Wachob
Peter,

I see that clue "[[".

The thread history pretty much sums up what is going on up to this point.

I'll cover it once more:


I'm using Adafruit FT232H Breakout board and Adafruit's library.

https://github.com/adafruit/Adafruit_Python_GPIO

Per Adafruit's example code, I create an SPI interface:

https://learn.adafruit.com/adafruit-ft232h-breakout?view=all

I can access this interface with the spi.transfer() spi.write() and
spi.read() functions.

The transfer() function (see link above) accepts and returns bytearray
objects data.

My application requires me to send a large payload down the SPI port
to my circuit, and read back the same in full duplex.

Due to a limitation of the part, I can't send my whole bytearray at
one time.  It crashes out.

So, my solution was to send as large of a chunk of data at one time as
I can inside a loop until I get to the end of the data to be sent.

Meanwhile, the transfer() function is returning 'chunks' of bytearrays.

Earlier discussions here indicated that the best way was to :

results = []

for i in range (0, slice_size):
   results.append(transfer(data_out))

Then, concatenate the results into a long bytearray so I can use it
elsewhere in my code.

all_together = bytearray().join(results)

I _thought_ that this was going to create a concatenated list of all
the returned results:

all_together = [results[0] + results[1] + results [2] + results[3]]
-- for example

but, as you point out, I got:

all_together = [[results[0]], [results[1]], [results[2]]. [results[3]]
 -- I'm sure that the brackets and braces are not syntactically
correct, but I think you get the idea.

So I see why my .join() isn't working.  I'm not sure how to fix it though.


Related to this, but I'm not yet at that point until I get this
resolved, I need to walk through the all_together data and find where
the data changes from one value to another..

My background is in C and other 'historical' languages, so I'm trying
to get a hold of the way Python handles arrays, which is different
that the way I've thought for 20+ years.. :)

I hope this helps.

I'm beginning to wonder if Python was the right choice for this
project.. but it's too late for me to switch now.

Thanks to everyone for your comments and patience.



On Mon, Sep 10, 2018 at 1:42 PM, Peter Otten <__pete...@web.de> wrote:
> Chip Wachob wrote:
>
>> Cameron,
>>
>> Thank you again for the insight.
>>
>> Yes, data_out is an equivalently-sized 'chunk' of a larger array.
>>
>> I'm 'getting' this now..
>>
>> So, without all the fluff associated with wiggling lines, my function
>> now looks like this:
>>
>> def RSI_size_the_loop():
>>results = []
>>all_together = []   # not certain if I need this, put it in in an
>> attempt to fix the incompatibility if it existed
>>
>>for x in range (0, MAX_LOOP_COUNT, slice_size):
>>   results.append(my_transfer(disp, data_out, slice_size)
>>
>>   print " results ", x, " = ", results  # show how results grows
>> on each iteration
>>
>>all_together = bytearray().join(results)
>>
>>print " all together ", all_together
>>
>>
>> I can observe results increasing in size and the last time through the
>> loop:
>>
>>  results  48  =
>>
> [[bytearray(b'\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
>
> Note that there are two '[' at the start of the list. This means that the
> first list item is another list. In fact you seem to have a list of single
> item lists like
>
> [["foo"], ["bar"], ...]
>
> when you need
>
> ["foo", "bar", ...]
>
> Of course join will fail with that:
>
 "".join(["foo", "bar"])
> 'foobar'
 "".join([["foo"], ["bar"]])
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: sequence item 0: expected string, list found
>
> I think the error message is pretty clear ;)
>
> Have a look into your my_transfer() function to find out why it returns a
> list (or show us the code).
>
> ___
> 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] Help with building bytearray arrays

2018-09-10 Thread Peter Otten
Chip Wachob wrote:

> Cameron,
> 
> Thank you again for the insight.
> 
> Yes, data_out is an equivalently-sized 'chunk' of a larger array.
> 
> I'm 'getting' this now..
> 
> So, without all the fluff associated with wiggling lines, my function
> now looks like this:
> 
> def RSI_size_the_loop():
>results = []
>all_together = []   # not certain if I need this, put it in in an
> attempt to fix the incompatibility if it existed
> 
>for x in range (0, MAX_LOOP_COUNT, slice_size):
>   results.append(my_transfer(disp, data_out, slice_size)
> 
>   print " results ", x, " = ", results  # show how results grows
> on each iteration
> 
>all_together = bytearray().join(results)
> 
>print " all together ", all_together
> 
> 
> I can observe results increasing in size and the last time through the
> loop:
> 
>  results  48  =
> 
[[bytearray(b'\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],

Note that there are two '[' at the start of the list. This means that the 
first list item is another list. In fact you seem to have a list of single 
item lists like

[["foo"], ["bar"], ...]

when you need

["foo", "bar", ...]

Of course join will fail with that:

>>> "".join(["foo", "bar"])
'foobar'
>>> "".join([["foo"], ["bar"]])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: sequence item 0: expected string, list found

I think the error message is pretty clear ;)

Have a look into your my_transfer() function to find out why it returns a 
list (or show us the code).

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


Re: [Tutor] Help with building bytearray arrays

2018-09-10 Thread Chip Wachob
Cameron,

Thank you again for the insight.

Yes, data_out is an equivalently-sized 'chunk' of a larger array.

I'm 'getting' this now..

So, without all the fluff associated with wiggling lines, my function
now looks like this:

def RSI_size_the_loop():
   results = []
   all_together = []   # not certain if I need this, put it in in an
attempt to fix the incompatibility if it existed

   for x in range (0, MAX_LOOP_COUNT, slice_size):
  results.append(my_transfer(disp, data_out, slice_size)

  print " results ", x, " = ", results  # show how results grows
on each iteration

   all_together = bytearray().join(results)

   print " all together ", all_together


I can observe results increasing in size and the last time through the loop:

 results  48  =
[[bytearray(b'\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')]]

So, now when I hit the line:

all_together = bytearray().join(results)

I'm getting the Traceback :

Traceback (most recent call last):
  File "SW8T_5.py", line 101, in   # this is my main script
loop_size = RSI_size_the_loop(Print)
  File "/home/temp/Python_Scratch/examples/RSI.py", line 359, in
RSI_size_the_loop
all_together = bytearray().join(results)
TypeError: can only join an iterable of bytes (item 0 has type 'list')

I looked this up, and there's very few search engine results on this
type of TypeError.

I wanted to clarify my understanding of iterable, and looked that up here:

https://infohost.nmt.edu/tcc/help/pubs/python/web/iterable.html

And, as far as I can tell I'm using a compatible sequence type.

I've even added in print statements for the types, so I could double
check, and I get:

results returns 
all_together returns 

So both are type 'list' which is referred to here :

https://infohost.nmt.edu/tcc/help/pubs/python/web/sequence-types.html

as a valid sequence type but apparently there's a detail I'm still missing...


On Mon, Sep 10, 2018 at 5:22 AM, Cameron Simpson  wrote:
> On 09Sep2018 23:00, Chip Wachob  wrote:
>>
>> On Sat, Sep 8, 2018 at 9:14 PM, Cameron Simpson  wrote:
>>>
>>> Actually he's getting back bytearray instances from transfer and wants to
>>> join them up (his function does a few small transfers to work around an
>>> issue with one big transfer). His earlier code is just confused. So he
>>> wants:
>>>
>>>  bytearray().join(results)
>>>
>>> Hacked example:
>>>
>>>  >>> bytearray().join( (bytearray("foo"),bytearray("bah")) )
>>>  bytearray(b'foobah')
>>
>>
>> I understand this example and I can replicate it in the interpreter..
>>
>> But, I'm still missing something here.
>> I presume that I need to instantiate an array of slice_size-sized
>> bytearrays.
>
>
> But no!
>
>> So, when I'm looping through, I can do:
>> for i in range (0, slice_count):
>>   results[i] = spi.transfer(data_out)
>
>
> Python lists are a variable size data structure, so our example goess:
>
>  results = []
>
> which allocates an empty list. Then:
>
>  for i in range(slice_count):
>results.append(spi.transfer(data_out))
>
> suitably adjusted (data_out will be different pieces of the larger data,
> yes?) which grows the array by one item with each append. Your spi.transfer
> function allocates a new bytearray for each return value, so you end up with
> a list of distinct bytearrays.
>
>> Then I can :
>>
>> all_together = butearray().join(results)
>
>
> Yes.
>
>> But I can't seem to be able to find the proper syntax to create the
>> initial array.
>> And any attempt at filling the arrays to test some stand-alone code
>> only give me errors.
>
>
> You _can_ allocate a presized list, but there's almost no benefit and it
> isn't what people normally do.
>
>> Here's my code (all of it)
>
> [...]
>>
>> #results = bytearray( (bytearray(slice_size)*slice_count) )
>> results = bytearray(slice_size)# why isn't this 16 bytes long?
>
>
> It is 16 bytes long when I do it:
>
>>>> bs=bytearray(16)
>>>> bs
>
> bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>
>> res_list = (results)*slice_count
>
>
> This is a single 64 byte bytearray. You may have intended to make a single
> element tuple with "(results)", but that is just the same as "results"
> (rundundant brackets). To make a single element tuple you go "(results,)" -
> see the trailing comma?
>
> Example of each:
>
>>>> bs*16
>
> 

Re: [Tutor] Help with building bytearray arrays

2018-09-10 Thread Alan Gauld via Tutor
On 10/09/18 04:00, Chip Wachob wrote:

> I presume that I need to instantiate an array of slice_size-sized bytearrays.

Cameron has already addressed this and explained
that you don't need to and if you did how to do it.

I'd only add that you need to readjust your thinking
when it comes to Python data structures versus C.
In C data structures are very primitive (little more
than an allocated chunk of memory).

In Python data structures are extremely rich and indeed
much of Python's power comes from exploiting the
richness of the standard data structures. It is well
worth while just playing around with these in the >>>
prompt using dir() and help() to explore all of the
functionality embodied in strings, lists, tuples,
sets and dictionaries.


> And any attempt at filling the arrays to test some stand-alone code
> only give me errors.

There are several ways of doing this and Cameron
showed you a couple. There is another option which
is very powerful, especially for generating more
complex data sets. Its called a generator expression
and the most commonly used version is a list
comprehension:

new_list = [expression for item in collection if condition]

The expression can be any valid Python expression.
The condition can be any valid Python expression that
evaluates to a boolean result (and is also optional).

It is equivalent to:

new_list = []
for item in collection:
   if condition:
  new_list.append(expression)


Some examples to clarify:

num_list = [num for num in range(5)]

which is the same result as

numlist = list(range(5))

odds = [num for num in range(5) if num % 2] ->[1,3]

evens = [num for num in range(5) if num %2 == 0] -> [0,2,4]

squares = [num*num for num in range(5)]

odd_squares = [n*n for n in odds]

You can make them as complex as you like by
creating helper functions too:

fancy_list = [func1(n) for n in my_data if func2(n)]

The syntax can look a little confusing at first
(its somewhat like set notation) but once you
get used to it its OK.


> results = bytearray(slice_size)# why isn't this 16 bytes long?

It is for me.

> res_list = (results)*slice_count

And this is 64 bytes long

> print " results ", [results]

And this prints a list with a single, 16 byte, bytearray inside it.

> print " results size ", sys.getsizeof(results)

This prints(on my system) 65 which may be confusing you.
But remember what I said about Python data structures
being rich, the bytearray has more than just the raw data
in it. The size reflects allthe other stuff that Python
uses to create a bytearray object. Try

>>> sys.getsizeof("")

and

>>> sys.getsizeof(bytearray())
>>> sys.getsizeof(bytearray("1"))
>>> sys.getsizeof(bytearray("12"))

Do the results surprize you?

Remember, Python data structures are not just chunks of memory.

> print " res_list ", [res_list]

Note that you are putting res_list into a list here,
but it is already a bytearray... There is no adavantage
in enclosing it in a list.

> Again, I feel like I'm circling the target, but not able to divine the
> proper syntax

Its not so much the syntax but your mental model
of what's going on under the covers. It's not C
(at least not at the first level down).

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


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


Re: [Tutor] Help with building bytearray arrays

2018-09-10 Thread Cameron Simpson

On 09Sep2018 23:00, Chip Wachob  wrote:

On Sat, Sep 8, 2018 at 9:14 PM, Cameron Simpson  wrote:

Actually he's getting back bytearray instances from transfer and wants to
join them up (his function does a few small transfers to work around an
issue with one big transfer). His earlier code is just confused. So he
wants:

 bytearray().join(results)

Hacked example:

 >>> bytearray().join( (bytearray("foo"),bytearray("bah")) )
 bytearray(b'foobah')


I understand this example and I can replicate it in the interpreter..

But, I'm still missing something here.
I presume that I need to instantiate an array of slice_size-sized bytearrays.


But no!


So, when I'm looping through, I can do:
for i in range (0, slice_count):
  results[i] = spi.transfer(data_out)


Python lists are a variable size data structure, so our example goess:

 results = []

which allocates an empty list. Then:

 for i in range(slice_count):
   results.append(spi.transfer(data_out))

suitably adjusted (data_out will be different pieces of the larger data, yes?) 
which grows the array by one item with each append. Your spi.transfer function 
allocates a new bytearray for each return value, so you end up with a list of 
distinct bytearrays.



Then I can :

all_together = butearray().join(results)


Yes.


But I can't seem to be able to find the proper syntax to create the
initial array.
And any attempt at filling the arrays to test some stand-alone code
only give me errors.


You _can_ allocate a presized list, but there's almost no benefit and it isn't 
what people normally do.



Here's my code (all of it)

[...]

#results = bytearray( (bytearray(slice_size)*slice_count) )
results = bytearray(slice_size)# why isn't this 16 bytes long?


It is 16 bytes long when I do it:

   >>> bs=bytearray(16)
   >>> bs
   
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')


res_list = (results)*slice_count


This is a single 64 byte bytearray. You may have intended to make a single 
element tuple with "(results)", but that is just the same as "results" 
(rundundant brackets). To make a single element tuple you go "(results,)" - see 
the trailing comma?


Example of each:

   >>> bs*16
   
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
   >>> (bs,)*16
   (bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), 
   bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'))


But you don't need any of that.

First, the list "results" can start empty and just get things appended to it 
and second, you don't need to preallocate any bytearrays because the internal, 
primary, transfer allocates a new bytearray for each return chunk.


Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe 

Re: [Tutor] Help with building bytearray arrays

2018-09-10 Thread Chip Wachob
On Sat, Sep 8, 2018 at 9:14 PM, Cameron Simpson  wrote:
> On 08Sep2018 11:40, Alan Gauld  wrote:
>>
>> On 08/09/18 03:15, Chip Wachob wrote:
>>>
>>> Ideally, I'd like to take the slice_size chunks that have been read
>>> and concatenate them back togetjer into a long MAX_LOOP_COUNT size
>>> array to pass back to the rest of my code.  Eg:
>>
>>
>> You need to create a list of read_ary
>>
>> results = []
>>
>> then after creating each read_ary value append it
>> to results.
>>
>> results.append(read_ary)
>>
>> Then, at the very end, return the summation of all
>> the lists in results.
>>
>> return sum(results,[])
>

Cameron is correct (Gold Star for you Cameron)

>
> Actually he's getting back bytearray instances from transfer and wants to
> join them up (his function does a few small transfers to work around an
> issue with one big transfer). His earlier code is just confused. So he
> wants:
>
>  bytearray().join(results)
>
> Hacked example:
>
>  >>> bytearray().join( (bytearray("foo"),bytearray("bah")) )
>  bytearray(b'foobah')

I understand this example and I can replicate it in the interpreter..

But, I'm still missing something here.

I presume that I need to instantiate an array of slice_size-sized bytearrays.

So, when I'm looping through, I can do:

for i in range (0, slice_count):
   results[i] = spi.transfer(data_out)

Then I can :

all_together = butearray().join(results)

But I can't seem to be able to find the proper syntax to create the
initial array.

And any attempt at filling the arrays to test some stand-alone code
only give me errors.

Here's my code (all of it)

#
#
#

import sys

slice_size = 16# in bytes
MAX_LOOP_COUNT = 64# in bytes

slice_count = MAX_LOOP_COUNT / slice_size

print " slice size = ", slice_size
print " MLC = ", MAX_LOOP_COUNT
print " slice count = ", slice_count

#results = bytearray( (bytearray(slice_size)*slice_count) )
results = bytearray(slice_size)# why isn't this 16 bytes long?

res_list = (results)*slice_count

print " results ", [results]
print " results size ", sys.getsizeof(results)
print " res_list ", [res_list]
print " res_list size ", sys.getsizeof(res_list)
print " type = ", type(results)

results[0] = ([1,3,5,7,9])

all_together = bytearray().join(results)

But I'm getting:

$ python merge_1.py
 slice size =  16
 MLC =  64
 slice count =  4
 results  
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')]
 results size  65
 res_list  
[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')]
 res_list size  113
 type =  
Traceback (most recent call last):
  File "merge_1.py", line 27, in 
results[0] = ([1,3,5,7,9])
TypeError: an integer or string of size 1 is required

Again, I feel like I'm circling the target, but not able to divine the
proper syntax

I hope this makes sense.


>
> And he's working with bytearrays because the target library is Python 2,
> where there's no bytes type.
>
> Cheers,
> Cameron Simpson 
>
> ___
> 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] Help with building bytearray arrays

2018-09-09 Thread Cameron Simpson

On 09Sep2018 17:06, Chip Wachob  wrote:

Before I jump in, the 1000 foot view is I have to send an array of 512
bytes down the SPI loop, and read back 512 bytes that were latched in
from a control interface.  Unfortunately, there's a glitch in the FTDI
part and I can't just send the 512 bytes.. the part times out and and
causes the script to terminate early...  So, my solution was to
'chunk' the data into smaller groups which the part _can_ handle.
This works fine until I come to the point where I concatenate the
'chunks' into my 512 byte array..  which other functions will then
process.


Sounds good to me.


The libraries that I'm using are from the project link below.  I'm
learning from all of you how much code to post, I didn't want to post
the entire library, but the way it's set up it is hard not to.. as has
been pointed out.. methods of classes and then there's other files
that contain some of the low-level workings..

https://github.com/adafruit/Adafruit_Python_GPIO


Thanks.


Yes, I realize now that I left out important information.  I have my
own transfer function which is the supplied transfer function with a
bunch of GPIO wrapped around it, and the 'chunking'.  This way I can
call it when I need to send and receive data from the loop, which is
often.  In the end, I will have to talk with several different SPI
devices, all of which will have to have different GPIO line wiggling
going on before and after they call the spi.transfer.

[...]

   def transfer(self, data):
Ok, this is a method, a particular type of function associated with a class
instance. (All objects are class instances, and the class is their type.)

So to call this you would normally have a control object of some kind. [...]
Ah, it looks like you should have an SpiDev instance, inferring from this
code:
https://github.com/adafruit/Adafruit_Python_GPIO/blob/master/Adafruit_GPIO/SPI.py

So suppose you've got such an object and a variable referring to it, let's
say it is named "spi". You'd normally call the transfer function like this:
 spi.transfer(some_data)

[...]

When you call a Python method, the instance itself is implicitly passed as
the parameter "self" (well, the first parameter - in Python we always call
this "self" like C++ uses "this").


Ah, the one 'thorn' in my side is "this".  I have considerable
difficulty with the 'this' concept.  That probably means that my code
could be 'better', but I tend to avoid "this" like the plague.


It isn't as big a deal as you might imagine. An object method essentially gets 
the object as a piece of context. So a method call like this:


 spi.transfer(data)

just has the "spi" object available within the method for use, for example is 
probably is already set up with all the hardware access you're going to make 
use of.



So lower down in the function, when it 
goes:


 self._ft232h._write(str(bytearray(data)))

all you're doing is making use of the already initialised _ft232h object to do 
the write, and that comes along with the "spi" object you called the transfer 
method through.


So from your point of view it's just context for the transfer function.


   logger.debug('SPI transfer with command {0:2X}.'.format(command))

Write a debugging message.


I saw this, but I don't know how to turn it 'on' so I could see the
log messages.  I wouldn't mind doing this with my code as well.
Perhaps creating my own log?  Right now, I have a verbose flag that I
pass to all my functions.. called disp.  Then for each place where I
want to see a value, etc, I have a line that reads:  if(disp): print "
What data is this ", data


Ah, logging. Yes, it is probably worth learning a little about, just to hook it 
it. You can at least get away from passing your "disp" variable around - just 
call the right logging call (warning, info, debug, error etc) and tune which 
messages get out from your main programme.


The logging module is documented here:

 https://docs.python.org/2.7/library/logging.html#module-logging

So your main programme would set up the logging, including a logging level. The 
module comes with five predefined levels from DEBUG through to CRITICAL. Then 
in your code you write messages like the debug one above. When you're debugging 
you might set the systems level to DEBUG and see heaps of messages, or INFO to 
see progress reporting, or WARNING to just see when things go wrong. Then your 
code just writes messages are a suitable level and the global setting controls 
which ones get out.


All you really need to do is "import logging" and then just call 
"logging.warning" or "logging.debug" etc. There's a tutorial here:


 https://docs.python.org/2.7/howto/logging.html#logging-basic-tutorial

Get off the ground like that and return to your main programme. The whole 
logging system can be rather complicated if you get sucked into learning it 
thoroughly.


[...]

   # Send command and length.
   self._assert_cs()
I would guess that this raises a control signal. Ah, 

Re: [Tutor] Help with building bytearray arrays

2018-09-09 Thread Chip Wachob
Cameron, et al.

First off, thank you for being patient with me.  I'm not used to the
email list communication style.

Since Cameron's response was the one that raised the most questions /
comments, I'm going to reply to it.

Inline.. now that I know that this is the preferred method...

Before I jump in, the 1000 foot view is I have to send an array of 512
bytes down the SPI loop, and read back 512 bytes that were latched in
from a control interface.  Unfortunately, there's a glitch in the FTDI
part and I can't just send the 512 bytes.. the part times out and and
causes the script to terminate early...  So, my solution was to
'chunk' the data into smaller groups which the part _can_ handle.
This works fine until I come to the point where I concatenate the
'chunks' into my 512 byte array..  which other functions will then
process.

The libraries that I'm using are from the project link below.  I'm
learning from all of you how much code to post, I didn't want to post
the entire library, but the way it's set up it is hard not to.. as has
been pointed out.. methods of classes and then there's other files
that contain some of the low-level workings..

https://github.com/adafruit/Adafruit_Python_GPIO

Anyhow, on with the 'show'..


On Sat, Sep 8, 2018 at 6:49 AM, Cameron Simpson  wrote:
> On 08Sep2018 20:01, Cameron Simpson  wrote:
>>>
>>> So, if I'm understanding the transfer() function correctly, the
>>> function takes and returns a bytearray type.
>>
>>
>> It would be good to see the specification for the transfer function. They
>> we can adhere to its requirements. Can you supply a URL?
>
>
> I see you supplied the whole transfer function in your first message :-(

Yes, I realize now that I left out important information.  I have my
own transfer function which is the supplied transfer function with a
bunch of GPIO wrapped around it, and the 'chunking'.  This way I can
call it when I need to send and receive data from the loop, which is
often.  In the end, I will have to talk with several different SPI
devices, all of which will have to have different GPIO line wiggling
going on before and after they call the spi.transfer.

You're walk-through is very helpful.

>
> I'll recite it here and walk through its contents to explain:
>
>def transfer(self, data):
>
> Ok, this is a method, a particular type of function associated with a class
> instance. (All objects are class instances, and the class is their type.)
>
> So to call this you would normally have a control object of some kind. [...]
> Ah, it looks like you should have an SpiDev instance, inferring from this
> code:
>
>
> https://github.com/adafruit/Adafruit_Python_GPIO/blob/master/Adafruit_GPIO/SPI.py
>
> So suppose you've got such an object and a variable referring to it, let's
> say it is named "spi". You'd normally call the transfer function like this:
>
>  spi.transfer(some_data)
>
> instead of calling transfer() "bare", as it were.

Again, I was generalizing and also being somewhat lazy and not typing
it all... my bad.

>
> When you call a Python method, the instance itself is implicitly passed as
> the parameter "self" (well, the first parameter - in Python we always call
> this "self" like C++ uses "this").

Ah, the one 'thorn' in my side is "this".  I have considerable
difficulty with the 'this' concept.  That probably means that my code
could be 'better', but I tend to avoid "this" like the plague.

>
>"""Full-duplex SPI read and write.  The specified array of bytes will
> be
>clocked out the MOSI line, while simultaneously bytes will be read
> from
>the MISO line.  Read bytes will be returned as a bytearray object.
>"""
>
> This is a docstring. It is like a comment but it gets attached to the
> function and can be inspected. Not your problem.
>
># Build command to read and write SPI data.
>command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve << 2) |
> self.write_clock_ve
>
> This constructs a value just as you would in C.
>
>logger.debug('SPI transfer with command {0:2X}.'.format(command))
>
> Write a debugging message.

I saw this, but I don't know how to turn it 'on' so I could see the
log messages.  I wouldn't mind doing this with my code as well.
Perhaps creating my own log?  Right now, I have a verbose flag that I
pass to all my functions.. called disp.  Then for each place where I
want to see a value, etc, I have a line that reads:  if(disp): print "
What data is this ", data

>
># Compute length low and high bytes.
># NOTE: Must actually send length minus one because the MPSSE engine
># considers 0 a length of 1 and  a length of 65536
>length = len(data)
>len_low  = (length-1) & 0xFF
>len_high = ((length-1) >> 8) & 0xFF
>
> All just like C.
>
># Send command and length.
>self._assert_cs()
>
> I would guess that this raises a control signal. Ah, RS-232? So
> clear-to-send then.

This is actually a chip 

Re: [Tutor] Help with building bytearray arrays

2018-09-08 Thread Cameron Simpson

On 08Sep2018 11:40, Alan Gauld  wrote:

On 08/09/18 03:15, Chip Wachob wrote:

Ideally, I'd like to take the slice_size chunks that have been read
and concatenate them back togetjer into a long MAX_LOOP_COUNT size
array to pass back to the rest of my code.  Eg:


You need to create a list of read_ary

results = []

then after creating each read_ary value append it
to results.

results.append(read_ary)

Then, at the very end, return the summation of all
the lists in results.

return sum(results,[])


Actually he's getting back bytearray instances from transfer and wants to join 
them up (his function does a few small transfers to work around an issue with 
one big transfer). His earlier code is just confused. So he wants:


 bytearray().join(results)

Hacked example:

 >>> bytearray().join( (bytearray("foo"),bytearray("bah")) )
 bytearray(b'foobah')

And he's working with bytearrays because the target library is Python 2, where 
there's no bytes type.


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


Re: [Tutor] Help with building bytearray arrays

2018-09-08 Thread Cameron Simpson

On 08Sep2018 20:01, Cameron Simpson  wrote:

So, if I'm understanding the transfer() function correctly, the
function takes and returns a bytearray type.


It would be good to see the specification for the transfer function. 
They we can adhere to its requirements. Can you supply a URL?


I see you supplied the whole transfer function in your first message :-(

I'll recite it here and walk through its contents to explain:

   def transfer(self, data):

Ok, this is a method, a particular type of function associated with a class 
instance. (All objects are class instances, and the class is their type.)


So to call this you would normally have a control object of some kind. [...] 
Ah, it looks like you should have an SpiDev instance, inferring from this code:


 
https://github.com/adafruit/Adafruit_Python_GPIO/blob/master/Adafruit_GPIO/SPI.py

So suppose you've got such an object and a variable referring to it, let's say 
it is named "spi". You'd normally call the transfer function like this:


 spi.transfer(some_data)

instead of calling transfer() "bare", as it were.

When you call a Python method, the instance itself is implicitly passed as the 
parameter "self" (well, the first parameter - in Python we always call this 
"self" like C++ uses "this").


   """Full-duplex SPI read and write.  The specified array of bytes will be
   clocked out the MOSI line, while simultaneously bytes will be read from
   the MISO line.  Read bytes will be returned as a bytearray object.
   """

This is a docstring. It is like a comment but it gets attached to the function 
and can be inspected. Not your problem.


   # Build command to read and write SPI data.
   command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve << 2) | 
self.write_clock_ve

This constructs a value just as you would in C.

   logger.debug('SPI transfer with command {0:2X}.'.format(command))

Write a debugging message.

   # Compute length low and high bytes.
   # NOTE: Must actually send length minus one because the MPSSE engine
   # considers 0 a length of 1 and  a length of 65536
   length = len(data)
   len_low  = (length-1) & 0xFF
   len_high = ((length-1) >> 8) & 0xFF

All just like C.

   # Send command and length.
   self._assert_cs()

I would guess that this raises a control signal. Ah, RS-232? So clear-to-send 
then.


   self._ft232h._write(str(bytearray((command, len_low, len_high

Ok, it looks like this is Python 2, not Python 3. Let's unpack it.

"(command, len_low, len_high)" is a tuple of 3 values. A tuple is like a read 
only list. We're passing that to the bytearray() constructor, which will accept 
an iterable of values and make a bytes buffer. And we want to write that to 
"self._ft232h". Which expects a str, which is why I think this is Python 2. In 
Python 2 there's no "bytes" type and str is an immutable array of 8-bit 
character values. So writing bytes uses str.


So this tabkes a tuple of values, to be bytes, makes those into a bytearray and 
makes that into a str, and writes that str to the serial line.


   self._ft232h._write(str(bytearray(data)))

We write that data itself.

   self._ft232h._write('\x87')
   self._deassert_cs()

And here we lower the control signal.

   # Read response bytes.
   return bytearray(self._ft232h._poll_read(length))

This calls the _poll_read method, presumably requesting "length" bytes, the 
same length as the supplied data. I presume we get a str back: we make a new 
bytearray with those bytes in it and return it.


So you do get a new bytearray back from each call, so we can accumulate them 
into a list and then join them together later to make a single bytearray.


Why this faffing about with str and bytearray? Probably for Python 2/3 
compatibility, and because you want to deal with bytes (small ints) instead of 
characters. Ignore it: we're dealing with bytes.


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


Re: [Tutor] Help with building bytearray arrays

2018-09-08 Thread Alan Gauld via Tutor
On 08/09/18 03:15, Chip Wachob wrote:

> my function's main pieces are:

It would probably be better to post the entire function,
a partial code sample like this just gives us an inkling
of what you are trying to do but not enough to be sure
of where the errors lie.

> def transfer_byte_array():
>MAX_LOOP_COUNT = 64
>slice_size = 16
>read_ary = bytearray(MAX_LOOP_COUNT)
>scratch_ary = bytearray()
> 
>for step in range (0, MAX_LOOP_COUNT, slice_size):
>   scratch_ary = transfer(data_to_send, slice_size)

You pass in two arguments here but in your description
of transfer below it is a method of an object that
only takes one (self being the object). Something is
broken here.

I would expect, given the code below, to see something
like
scratch_ary = someObject.transfer(data_to_send)

>   for bytes in range (0, slice_size):
>  read_ary = scratch_ary[bytes]

This is replacing rad_ary each time with a single value from scratch_ary.
At the end of theloop read_ary wil;l cpontain the last valuye in
scratch_ary. You can achieve the same result without a loop:

raed_ary = scratch_ary[-1]

But I suspect that's not what you want.
I think what you really want is the first
slice_size elements of scratch_ary:

read_ary = scratch_ary[:slice_size]   # use slicing

> Ideally, I'd like to take the slice_size chunks that have been read
> and concatenate them back togetjer into a long MAX_LOOP_COUNT size
> array to pass back to the rest of my code.  Eg:

You need to create a list of read_ary

results = []

then after creating each read_ary value append it
to results.

results.append(read_ary)

Then, at the very end, return the summation of all
the lists in results.

return sum(results,[])

> def transfer(self, data):

The self parameter indicates that this is a method
definition from a class. That implies that to use
it you must create an instance of the class and
call the method on that instance.

HTH

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


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


Re: [Tutor] Help with building bytearray arrays

2018-09-08 Thread Alan Gauld via Tutor
On 08/09/18 03:15, Chip Wachob wrote:
> Admin, please remove my earlier messages.

No can do, once the emails are sent by the server
they are out there on the net, stored in people's
mailboxes and in various internet archives.

When using a mailing list always check before
sending, there's no going back...

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


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


Re: [Tutor] Help with building bytearray arrays

2018-09-08 Thread Alan Gauld via Tutor
On 08/09/18 04:57, Chip Wachob wrote:

> was my attempt at 'setting' the type of the variable.  

A variable in Python is just a name. It has no type.
Only values have types. So you can set (or change)
the type of a value but not of a variable.

> Coming from a 'C' background, I find the lack of typing in Python to
> be confusing.  

There is no shortage of typing in Python its just
applied to the values(objects) not to their labels.

> I'm used to working with bytes / words signed and
> unsigned for a reason.

The same applies in Python. You just have to separate
the concepts of variable name and variable value.
In C those two concepts get kind of squished together
but in Python the name/value duality is strong.

You can always check the type of an object by using
the type() function or if you think a type error is
likely catch it when it happens with:

try:...
except TypeError:


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


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


Re: [Tutor] Help with building bytearray arrays

2018-09-08 Thread Cameron Simpson
Please try to adopt the inline reply style; we prefer it here. It lets us reply 
point by point and makes messages read like conversations. Anyway...


On 07Sep2018 23:57, Chip Wachob  wrote:

Point taken on 'bytes'..  thanks.

the
scratch_ary = bytearray()

was my attempt at 'setting' the type of the variable.  I had hoped
that it would help resolve the error messages telling me that the
types didn't go together.
Coming from a 'C' background, I find the lack of typing in Python to
be confusing.  I'm used to working with bytes / words signed and
unsigned for a reason.


Ok. Variables aren't typed. Variables are references to objects, which _are_ 
typed. So pointing a variable at a bytearray doesn't set its type in any 
persistent sense.


Thus:

 x = 1
 x = "a string"
 x = bytearray()

All just point "x" at different objects. If you'd like a C metaphor, variables 
are _like_ (void*) pointers: they can reference any kind of object.


Aside: they're not pointers, avoid the term - people will complain. As far as 
the language spec goes they're references. Which may in a particular 
implementation be _implemented internally_ using pointers.



So, if I'm understanding the transfer() function correctly, the
function takes and returns a bytearray type.


It would be good to see the specification for the transfer function. They we 
can adhere to its requirements. Can you supply a URL?



You mentioned about
constructing a bytearray if I need one.  Can you expand on how I
approach that?


Well, you were getting several bytes or bytearray objects back from transfer 
and wanted to join them together. The efficient way is to accumulate them in a 
list and then join them all together later using the bytearry (or bytes) .join 
method:


 https://docs.python.org/3/library/stdtypes.html#bytearray.join

So:

 data_list = []
 for 
   # send some data, get some data back
   data = transfer(...)
   # add that buffer to the data_list
   data_list.append(data)
 # make a single bytes object being the concatenation of all the smaller data 
 # chunks

 all_data = bytes.join(data_list)

It looks to me like your transfer() function is handed a bytes or bytearray and 
returns one. Normally that would be a separate bytes or bytearray.


Aside: bytes and bytearray objects are generally the way Python 3 deals with 
chunks of bytes. A "bytes" is readonly and a bytearray may have its contents 
modified. From a C background, they're like an array of unsigned chars.



I'm going to try the experiment you mentioned in hopes of it giving me
a better understanding of the 'types' and what happens with the
variables.


Sounds good.

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


Re: [Tutor] Help with building bytearray arrays

2018-09-08 Thread Chip Wachob
Point taken on 'bytes'..  thanks.

the

scratch_ary = bytearray()

was my attempt at 'setting' the type of the variable.  I had hoped
that it would help resolve the error messages telling me that the
types didn't go together.

Coming from a 'C' background, I find the lack of typing in Python to
be confusing.  I'm used to working with bytes / words signed and
unsigned for a reason.

So, if I'm understanding the transfer() function correctly, the
function takes and returns a bytearray type.  You mentioned about
constructing a bytearray if I need one.  Can you expand on how I
approach that?

I'm going to try the experiment you mentioned in hopes of it giving me
a better understanding of the 'types' and what happens with the
variables.

Thank you,


On Fri, Sep 7, 2018 at 6:23 PM, Cameron Simpson  wrote:
> On 07Sep2018 15:45, Chip Wachob  wrote:
>>
>> Basically I'm trying to write a block of unsigned bytes to the device
>> and read back an equal sized block of unsigned bytes.  There's a
>> function that is provided called transfer(data_to_send, num_of_bytes)
>> that handles the heavy lifting.  Unfortunately there seems to be a bug
>> in the part and if I attempt to send the entire block of bytes (64),
>> the device will lock up.  I've been able to determine that if I send
>> 16 bytes at a time, I'm okay.
>>
>> So, I take my bytearray(64) and step through it 16 bytes at a time like
>> this:
>>
>> my function's main pieces are:
>>
>> def transfer_byte_array():
>>   MAX_LOOP_COUNT = 64
>>   slice_size = 16
>>   read_ary = bytearray(MAX_LOOP_COUNT)
>>   scratch_ary = bytearray()
>>
>>   for step in range (0, MAX_LOOP_COUNT, slice_size):
>>  scratch_ary = transfer(data_to_send, slice_size)
>>
>>  for bytes in range (0, slice_size):
>> read_ary = scratch_ary[bytes]
>>
>>   return(read_ary)
>>
>>
>> Ideally, I'd like to take the slice_size chunks that have been read
>> and concatenate them back togetjer into a long MAX_LOOP_COUNT size
>> array to pass back to the rest of my code.  Eg:
>>
>> read_ary = ary_slice[0] + ary_slice[1] + ary_slice[2] + ary_slice[3]
>
>
> Minor remark: don't use the name "bytes" for a variable, it is a builtin
> type name and you're shadowing it.
>
> It looks to me like "transfer" hands you back a buffer with the read data,
> so this:
>
>  scratch_ary = bytearray()
>
> don't do anything (it gets discarded).
>
> If you're getting back a bytes or bytearray object from transfer, just
> gather them all up in an list:
>
>  returned_buffers = []
>  for ..
>  response = transfer(data_to_send, slice_size)
>  returned_buffers.append(response)
>  ...
>  read_ary = b''.join(returned_buffers)
>
> Note that that makes a new bytes object for read_ary to refer to. You don't
> need the earlier initialisation of read_ary.
>
> Also note that the bytes object is read only; if that is a problem you'll
> need to construct a bytearray instead.
>
> [...]
>>
>> The problem that I repeatedly run into is with the line:
>>
>> read_ary = scratch_ary[bytes]  (or variants thereof)
>>
>> The traceback is this:
>>
>> Traceback (most recent call last):
>>  File "SW8T_5.py", line 101, in 
>>loop_size = RSI_size_the_loop(Print)
>>  File "/home/temp/Python_Scratch/examples/RSI.py", line 350, in
>> RSI_size_the_loop
>>read_ary.append(scratch_ary[singles])
>> TypeError: an integer or string of size 1 is required
>
>
> Yeah I thought that looked weird to me too.
>>
>> or, one of the other common ones that I've seen is
>>
>> TypeError: can't concat bytearray to list
>>
>> This one is confusing because both of the operands are bytearry
>> types.. or at least I thought they should be...
>
>
> No, one will be a list :-) putting a bunch of:
>
>  print(repr(foo))
>
> replacing "foo" with relevant variables will be illuminating to you; you can
> see immediately where this are not what you expected.
>
>> I'm obviously missing something fundamental here.  Problem is I can't
>> seem to find any examples of people asking this question before on the
>> inter-webs..
>
>
> You have the opposite of my problem. I can often find people asking the same
> question, but less often an answer. Or a decent answer, anyway.
>
> Cheers,
> Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with building bytearray arrays

2018-09-08 Thread Chip Wachob
Admin, please remove my earlier messages.

This message is a properly 'self contained' message.

Hello,

I've been struggling with this for the last day or so and I can't seem
to figure out how to make it work.

I'll start out by saying that if there's a better approach, then I'm all ears.

I'm using the Adafruit Breakout board for the FTDI FT232H part.  Along
with this comes the Python libraries and Adafruit libraries which I'm
using.  I don't think that the libraries are the real issue here, but
I thought I should mention it just for the sake of information.

Basically I'm trying to write a block of unsigned bytes to the device
and read back an equal sized block of unsigned bytes.  There's a
function that is provided called transfer(data_to_send, num_of_bytes)
that handles the heavy lifting.  Unfortunately there seems to be a bug
in the part and if I attempt to send the entire block of bytes (64),
the device will lock up.  I've been able to determine that if I send
16 bytes at a time, I'm okay.

So, I take my bytearray(64) and step through it 16 bytes at a time like this:

my function's main pieces are:

def transfer_byte_array():
   MAX_LOOP_COUNT = 64
   slice_size = 16
   read_ary = bytearray(MAX_LOOP_COUNT)
   scratch_ary = bytearray()

   for step in range (0, MAX_LOOP_COUNT, slice_size):
  scratch_ary = transfer(data_to_send, slice_size)

  for bytes in range (0, slice_size):
 read_ary = scratch_ary[bytes]

   return(read_ary)


Ideally, I'd like to take the slice_size chunks that have been read
and concatenate them back togetjer into a long MAX_LOOP_COUNT size
array to pass back to the rest of my code.  Eg:

read_ary = ary_slice[0] + ary_slice[1] + ary_slice[2] + ary_slice[3]

I know that the + version doesn't work (or didn't for me) but it is
just my attempt at illustrating the overall goal.

The problem that I repeatedly run into is with the line:

read_ary = scratch_ary[bytes]  (or variants thereof)

The traceback is this:

Traceback (most recent call last):
  File "SW8T_5.py", line 101, in 
loop_size = RSI_size_the_loop(Print)
  File "/home/temp/Python_Scratch/examples/RSI.py", line 350, in
RSI_size_the_loop
read_ary.append(scratch_ary[singles])
TypeError: an integer or string of size 1 is required

or, one of the other common ones that I've seen is

TypeError: can't concat bytearray to list

This one is confusing because both of the operands are bytearry
types.. or at least I thought they should be...

when I try to replace the same line with :

read_ary += scratch_ary[bytes]

or

read_ary.append(scratch[bytes])

or

read_ary = read_ary + scratch_ary[bytes]


I'm obviously missing something fundamental here.  Problem is I can't
seem to find any examples of people asking this question before on the
inter-webs..

the transfer function expects an input of a bytearray and returns the same:

def transfer(self, data):
"""Full-duplex SPI read and write.  The specified array of bytes will be
clocked out the MOSI line, while simultaneously bytes will be read from
the MISO line.  Read bytes will be returned as a bytearray object.
"""
# Build command to read and write SPI data.
command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve <<
2) | self.write_clock_ve
logger.debug('SPI transfer with command {0:2X}.'.format(command))
# Compute length low and high bytes.
# NOTE: Must actually send length minus one because the MPSSE engine
# considers 0 a length of 1 and  a length of 65536
length = len(data)
len_low  = (length-1) & 0xFF
len_high = ((length-1) >> 8) & 0xFF
# Send command and length.
self._assert_cs()
self._ft232h._write(str(bytearray((command, len_low, len_high
self._ft232h._write(str(bytearray(data)))
self._ft232h._write('\x87')
self._deassert_cs()
# Read response bytes.
return bytearray(self._ft232h._poll_read(length))


Thank you in advance to taking time to read.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with building bytearray arrays

2018-09-07 Thread Cameron Simpson

On 07Sep2018 15:45, Chip Wachob  wrote:

Basically I'm trying to write a block of unsigned bytes to the device
and read back an equal sized block of unsigned bytes.  There's a
function that is provided called transfer(data_to_send, num_of_bytes)
that handles the heavy lifting.  Unfortunately there seems to be a bug
in the part and if I attempt to send the entire block of bytes (64),
the device will lock up.  I've been able to determine that if I send
16 bytes at a time, I'm okay.

So, I take my bytearray(64) and step through it 16 bytes at a time like this:

my function's main pieces are:

def transfer_byte_array():
  MAX_LOOP_COUNT = 64
  slice_size = 16
  read_ary = bytearray(MAX_LOOP_COUNT)
  scratch_ary = bytearray()

  for step in range (0, MAX_LOOP_COUNT, slice_size):
 scratch_ary = transfer(data_to_send, slice_size)

 for bytes in range (0, slice_size):
read_ary = scratch_ary[bytes]

  return(read_ary)


Ideally, I'd like to take the slice_size chunks that have been read
and concatenate them back togetjer into a long MAX_LOOP_COUNT size
array to pass back to the rest of my code.  Eg:

read_ary = ary_slice[0] + ary_slice[1] + ary_slice[2] + ary_slice[3]


Minor remark: don't use the name "bytes" for a variable, it is a builtin type 
name and you're shadowing it.


It looks to me like "transfer" hands you back a buffer with the read data, so 
this:


 scratch_ary = bytearray()

don't do anything (it gets discarded).

If you're getting back a bytes or bytearray object from transfer, just gather 
them all up in an list:


 returned_buffers = []
 for ..
 response = transfer(data_to_send, slice_size)
 returned_buffers.append(response)
 ...
 read_ary = b''.join(returned_buffers)

Note that that makes a new bytes object for read_ary to refer to. You don't 
need the earlier initialisation of read_ary.


Also note that the bytes object is read only; if that is a problem you'll need 
to construct a bytearray instead.


[...]

The problem that I repeatedly run into is with the line:

read_ary = scratch_ary[bytes]  (or variants thereof)

The traceback is this:

Traceback (most recent call last):
 File "SW8T_5.py", line 101, in 
   loop_size = RSI_size_the_loop(Print)
 File "/home/temp/Python_Scratch/examples/RSI.py", line 350, in
RSI_size_the_loop
   read_ary.append(scratch_ary[singles])
TypeError: an integer or string of size 1 is required


Yeah I thought that looked weird to me too. 


or, one of the other common ones that I've seen is

TypeError: can't concat bytearray to list

This one is confusing because both of the operands are bytearry
types.. or at least I thought they should be...


No, one will be a list :-) putting a bunch of:

 print(repr(foo))

replacing "foo" with relevant variables will be illuminating to you; you can 
see immediately where this are not what you expected.



I'm obviously missing something fundamental here.  Problem is I can't
seem to find any examples of people asking this question before on the
inter-webs..


You have the opposite of my problem. I can often find people asking the same 
question, but less often an answer. Or a decent answer, anyway.


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


[Tutor] Help with building bytearray arrays

2018-09-07 Thread Chip Wachob
Hello,

I've been struggling with this for the last day or so and I can't seem
to figure out how to make it work.

I'll start out by saying that if there's a better approach, then I'm all ears.

I'm using the Adafruit Breakout board for the FTDI FT232H part.  Along
with this comes the Python libraries and Adafruit libraries which I'm
using.  I don't think that the libraries are the real issue here, but
I thought I should mention it just for the sake of information.

Basically I'm trying to write a block of unsigned bytes to the device
and read back an equal sized block of unsigned bytes.  There's a
function that is provided called transfer(data_to_send, num_of_bytes)
that handles the heavy lifting.  Unfortunately there seems to be a bug
in the part and if I attempt to send the entire block of bytes (64),
the device will lock up.  I've been able to determine that if I send
16 bytes at a time, I'm okay.

So, I take my bytearray(64) and step through it 16 bytes at a time like this:

my function's main pieces are:

def transfer_byte_array():
   MAX_LOOP_COUNT = 64
   slice_size = 16
   read_ary = bytearray(MAX_LOOP_COUNT)
   scratch_ary = bytearray()

   for step in range (0, MAX_LOOP_COUNT, slice_size):
  scratch_ary = transfer(data_to_send, slice_size)

  for bytes in range (0, slice_size):
 read_ary = scratch_ary[bytes]

   return(read_ary)


Ideally, I'd like to take the slice_size chunks that have been read
and concatenate them back togetjer into a long MAX_LOOP_COUNT size
array to pass back to the rest of my code.  Eg:

read_ary = ary_slice[0] + ary_slice[1] + ary_slice[2] + ary_slice[3]

I know that the + version doesn't work (or didn't for me) but it is
just my attempt at illustrating the overall goal.

The problem that I repeatedly run into is with the line:

read_ary = scratch_ary[bytes]  (or variants thereof)

The traceback is this:

Traceback (most recent call last):
  File "SW8T_5.py", line 101, in 
loop_size = RSI_size_the_loop(Print)
  File "/home/temp/Python_Scratch/examples/RSI.py", line 350, in
RSI_size_the_loop
read_ary.append(scratch_ary[singles])
TypeError: an integer or string of size 1 is required

or, one of the other common ones that I've seen is

TypeError: can't concat bytearray to list

This one is confusing because both of the operands are bytearry
types.. or at least I thought they should be...

when I try to replace the same line with :

read_ary += scratch_ary[bytes]

or

read_ary.append(scratch[bytes])

or

read_ary = read_ary + scratch_ary[bytes]


I'm obviously missing something fundamental here.  Problem is I can't
seem to find any examples of people asking this question before on the
inter-webs..

Thank you in advance to taking time to read.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with reading a string?

2018-07-16 Thread Steven D'Aprano
Hi Crystal, and welcome! My response is further below, after your 
question.

On Mon, Jul 16, 2018 at 05:28:37PM -0500, Crystal Frommert wrote:
> Hi, I am a beginner comp sci teacher at an all-girls high school. The girls
> are learning how to read from a txt file and search for a string.
> 
> Here is a sample of text from the txt file:
> TX,F,1910,Mary,895
> TX,F,1910,Ruby,314
> TX,F,1910,Annie,277
> TX,F,1910,Willie,260
> TX,F,1910,Ruth,252
> TX,F,1910,Gladys,240
> TX,F,1910,Maria,223
> TX,F,1910,Frances,197
> TX,F,1910,Margaret,194
> 
> How do they read the number after a certain searched name and then add up
> the numbers after each time the name occurs?

Which version of Python are you using? The answer may depend on the 
exact version, but something like this ought to be good:

# Code below is not tested, please forgive any bugs when you try it...

# Process the lines of some text file.
total = 0
with open("path to the file.txt", "r") as f:
# Read the file line-by-line.
for line in f:
# Split each record into five fields.
# Please pick more meaningful field names for a, b, c!
a, b, c, name, score = line.split(",")
# Choose only records for a specific person.
# Here I hard-code the person's name, in practice
# you ought to use a variable.
if name == "Sarah":
# Convert the score from a string to an int, 
# and add it to total.
total = total + int(score)
# Dropping back to the extreme left automatically closes
# the file.
print(total)


Remember that in Python, indentation is not optional.

Some extra features:

* You can re-write the line "total = total + int(score)" using the more
  compact notation "total += int(score)"

* Instead of the "with open(...) as f", you can do it like this:

f = open("path to the file.txt")  # the "r" parameter is optional
for line in f:
# copy for loop from above to here
# (don't forget to reduce the indentation by one level)
...
# Explicitly close the file. 
f.close()# A common error is to forget the parentheses!
# And finally print the total.
print(total)


Hope this helps, and please don't hesitate to ask if you have any 
questions. Keep your replies on the mailing list so others may 
contribute answers and learn from the responses.


Regards,



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


Re: [Tutor] help with reading a string?

2018-07-16 Thread Alan Gauld via Tutor
On 16/07/18 23:28, Crystal Frommert wrote:

> are learning how to read from a txt file and search for a string.
> 
> Here is a sample of text from the txt file:
> TX,F,1910,Mary,895
> TX,F,1910,Ruby,314
> TX,F,1910,Annie,277
> 
> How do they read the number after a certain searched name and then add up
> the numbers after each time the name occurs?
> 
> I would really like to help them with this code but I am at a loss.

Which bit are you at a loss over?

The general approach is:

open the file for reading
read each line.
search the line for your target string
extract the number at the end of the file
add the number to the running total

None of those are intrinsically difficult, so which
bit are you having problems with?

Have you got any code that you tried and it didn't work?
That would be most helpful in determining where you
need to adjust your approach.

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


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


[Tutor] help with reading a string?

2018-07-16 Thread Crystal Frommert
Hi, I am a beginner comp sci teacher at an all-girls high school. The girls
are learning how to read from a txt file and search for a string.

Here is a sample of text from the txt file:
TX,F,1910,Mary,895
TX,F,1910,Ruby,314
TX,F,1910,Annie,277
TX,F,1910,Willie,260
TX,F,1910,Ruth,252
TX,F,1910,Gladys,240
TX,F,1910,Maria,223
TX,F,1910,Frances,197
TX,F,1910,Margaret,194

How do they read the number after a certain searched name and then add up
the numbers after each time the name occurs?

I would really like to help them with this code but I am at a loss.


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


Re: [Tutor] Help

2018-07-03 Thread Alan Gauld via Tutor
On 03/07/18 06:23, Adam Jones wrote:
> Good day, I am currently checking a piece of arcpy code. Where a point is
> shifted within a set distance to protect the privacy of said point. Please
> see the code below, and please advise me or correct the code where it is
> needed

It would help us to help you if you explain what the problem is.
Do you get an error message(if so include it).
Is the data wrong (if so tell us what you expected and what you got)

Do not assume we know much about arcpy, that's not part of
standard Python, so you need to tell us what you are doing
with it.


> # Step 11 - SELECT By Attributes -> where FID == FID_1, export to new
> Feature Class
> #
> --
> # Make a layer from the feature class
> arcpy.MakeFeatureLayer_management(in_features="RDiff_AreaIntersect_Dissolve",
> out_layer="lyr_eaten",
> where_clause="",
> workspace="",
> field_info= "OBJECTID OBJECTID VISIBLE NONE", "Shape Shape VISIBLE NONE",
> "ORIG_FID ORIG_FID VISIBLE NONE", "FIRST_Join_Count FIRST_Join_Count
> VISIBLE NONE"
> FIRST_OBJECTID_1 (VISIBLE NONE;FIRST_gps_latitu FIRST_gps_latitu VISIBLE
> NONE;
> FIRST_gps_longit; FIRST_gps_longit VISIBLE NONE;FIRST_OBJECTID
> FIRST_OBJECTID VISIBLE NONE;
> FIRST_R1 FIRST_R1 VISIBLE NONE;FIRST_ORIG_FID FIRST_ORIG_FID VISIBLE
> NONE;Shape_Length Shape_Length VISIBLE NONE;
> Shape_Area Shape_Area VISIBLE NONE)

I would expect the above to give a syntax error because it doesn't look
like valid Python. It starts out as a sequence of arguments but then
semi colons start appearing in strange places amid a function call. And
the parens don't seem to match either. All very odd.


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


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


[Tutor] Help

2018-07-03 Thread Adam Jones
Good day, I am currently checking a piece of arcpy code. Where a point is
shifted within a set distance to protect the privacy of said point. Please
see the code below, and please advise me or correct the code where it is
needed

# Step 11 - SELECT By Attributes -> where FID == FID_1, export to new
Feature Class
#
--
# Make a layer from the feature class
arcpy.MakeFeatureLayer_management(in_features="RDiff_AreaIntersect_Dissolve",
out_layer="lyr_eaten",
where_clause="",
workspace="",
field_info= "OBJECTID OBJECTID VISIBLE NONE", "Shape Shape VISIBLE NONE",
"ORIG_FID ORIG_FID VISIBLE NONE", "FIRST_Join_Count FIRST_Join_Count
VISIBLE NONE"
FIRST_OBJECTID_1 (VISIBLE NONE;FIRST_gps_latitu FIRST_gps_latitu VISIBLE
NONE;
FIRST_gps_longit; FIRST_gps_longit VISIBLE NONE;FIRST_OBJECTID
FIRST_OBJECTID VISIBLE NONE;
FIRST_R1 FIRST_R1 VISIBLE NONE;FIRST_ORIG_FID FIRST_ORIG_FID VISIBLE
NONE;Shape_Length Shape_Length VISIBLE NONE;
Shape_Area Shape_Area VISIBLE NONE)

# SELECT by attribute
arcpy.SelectLayerByAttribute_management(in_layer_or_view="lyr_eaten",
selection_type="NEW_SELECTION",
where_clause="FID_RDiffBuffer = ORIG_FID")

# Write the selected features to a new featureclass
arcpy.CopyFeatures_management(in_features="lyr_eaten",out_feature_class="C:/Users/Claudinho/Desktop/2016/
GIS_702/COPC_DATA/Altered_Data_sets/702.gdb/DonutFile", config_keyword="",
spatial_grid_1="0",
spatial_grid_2="0", spatial_grid_3="0")

#
--
# Step 12 - CreateRandomPoint constrained by DonutFile
#
--
arcpy.CreateRandomPoints_management(out_path="C:/Users/Claudinho/Desktop/2016/GIS_702/COPC_DATA/
Altered_Data_sets/702.gdb", out_name="RandomFile",
constraining_feature_class="DonutFile",
constraining_extent="0 0 250 250", number_of_points_or_field="1",
minimum_allowed_distance="0 Meters",
create_multipoint_output="POINT", multipoint_size="0")

# JOIN RandomFile (CID) to DonutFile (OBJECTID)
arcpy.JoinField_management(in_data="RandomFile", in_field="CID",
join_table="DonutFile", join_field="OBJECTID",
fields="")

# DELETE unnecessary fields in RandomFile
arcpy.DeleteField_management(in_table="RandomFile",
drop_field="FIRST_OBJECTID_1;FIRST_FID_RDiffBuffer;
FIRST_gps_latitu;FIRST_gps_longit;")


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


Re: [Tutor] help with Pandas

2018-05-22 Thread Alan Gauld via Tutor
On 22/05/18 18:13, Glenn Schultz wrote:

Cavbeat: I'm no dataframe expert so I'm going on
general principles here...


>  I am trying to apply the function to the data frame as follows:
> 
> df['loanage'].apply(myfunction(x = 2, y = 10, z = 10, df['loanage]), axis = 0)

This looks wrong on several counts:

1) apply() usually takes a function object as the first argument not the
return value of a function call as here.

2) When calling a function using keyword arguments you re not allowe to
have non-keyword arguments following the keyword ones, so the df[...]
bit should be an error

3) The df['loanage] does not have a closing quote.

> I get value error: The truth in the series is ambigous.

I'm not sure if any of the above would result in a ValueError
but its possible.


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


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


[Tutor] help with Pandas

2018-05-22 Thread Glenn Schultz

All,

I have a dataframe with the column 'loanage' and a function to transform 
loanage, which will be part of a pipline, I am trying to apply the function to 
the data frame as follows:

df['loanage'].apply(myfunction(x = 2, y = 10, z = 10, df['loanage]), axis = 0)

I get value error: The truth in the series is ambigous.

However, if I write a for loop indexing into the dataframe the function works.  
I am of the understanding based on the docs and online research I should be 
able to do the above.  I cannot figure out what I am doing wrong and have tried 
every possible combination I have seen in the docs and online.  Any help is 
appreciated.

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


Re: [Tutor] Help

2018-05-16 Thread Alan Gauld via Tutor
On 16/05/18 02:43, Steven D'Aprano wrote:

> The traceback Sam posted says (in part):
> 
>   Move = input('What Will You Do? Fight or Run: ')
>   File "", line 1, in 
>   NameError: name 'Run' is not defined
> 
> so the failed line was the call to input(). In Python 3, it would return 
> a string. In Python 2, input() evaluates whatever the user types as 
> code, hence I infer Sam typed:
> 
> Run
> 
> and input() tries to evaluate it, which fails.


Shneaky!
I was trying to figure out why the traceback highlighted
that line instead of the if... I never thought about it
being a Python 2 issue.

Good catch!

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


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


Re: [Tutor] Help

2018-05-15 Thread Steven D'Aprano
On Tue, May 15, 2018 at 08:01:13PM -0500, boB Stepp wrote:
> On Tue, May 15, 2018 at 7:51 PM, Steven D'Aprano  wrote:
> 
> > You also seem to be using Python 2. In Python 2, you should never use
> > the input() function. Instead, use raw_input() instead.
> 
> What are you seeing that suggests the OP is using Python 2?  I am
> missing what you are seeing/understanding.

Excellent question :-)

The traceback Sam posted says (in part):

  Move = input('What Will You Do? Fight or Run: ')
  File "", line 1, in 
  NameError: name 'Run' is not defined

so the failed line was the call to input(). In Python 3, it would return 
a string. In Python 2, input() evaluates whatever the user types as 
code, hence I infer Sam typed:

Run

and input() tries to evaluate it, which fails.

Also, the following line says:

if Move == Fight:
pass

If input() returned a string, as in Python 3, then the next line would 
run and Sam would have got a name error for Fight. This didn't happen.



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


Re: [Tutor] Help

2018-05-15 Thread boB Stepp
On Tue, May 15, 2018 at 7:51 PM, Steven D'Aprano  wrote:

> You also seem to be using Python 2. In Python 2, you should never use
> the input() function. Instead, use raw_input() instead.

What are you seeing that suggests the OP is using Python 2?  I am
missing what you are seeing/understanding.


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


Re: [Tutor] Help

2018-05-15 Thread Steven D'Aprano
On Tue, May 15, 2018 at 02:49:54PM -0500, Sam Hoffman wrote:
> Traceback (most recent call last):
>   File "/Users/samhoffman/Documents/test.py", line 54, in 
> Battle()
>   File "/Users/samhoffman/Documents/test.py", line 41, in Battle
> Move = input('What Will You Do? Fight or Run: ')
>   File "", line 1, in 
> NameError: name 'Run' is not defined

You need to either define a value for Run:

Run = 2468

or you need to quote it, making it a string. Same applies to your Fight:

> if Move == Fight:
> pass
> elif Move == Run:

Both of these ought to be "Fight" and "Run" in quotes.

You also seem to be using Python 2. In Python 2, you should never use 
the input() function. Instead, use raw_input() instead.



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


Re: [Tutor] Help

2018-05-15 Thread boB Stepp
Greetings!

On Tue, May 15, 2018 at 2:49 PM, Sam Hoffman
 wrote:
> Traceback (most recent call last):
>   File "/Users/samhoffman/Documents/test.py", line 54, in 
> Battle()
>   File "/Users/samhoffman/Documents/test.py", line 41, in Battle
> Move = input('What Will You Do? Fight or Run: ')
>   File "", line 1, in 
> NameError: name 'Run' is not defined

The Python interpreter believes that Run is a variable to which no
value has been assigned.

>
> import time
> import random
> #Pokemon Stats
> Bulbasaur = {'N' : 'Bulby',
>  'HP' : 20,
>  'Level' : 5,
>  'Atk' : 8,
>  'Def' : 9,
>  'Spd' : 6}
>
>
> Rattata = {'N' : 'Rattata',
>'HP' : 15,
>'Level' : 3,
>'Atk' : 5,
>'Def' : 6,
>'Spd' : 4}
>
> #Move damages
> BM = {'Vinewhip' : 45,
>   'Tackle' : 40,
>   'Razorleaf' : 55}
>
>
> RM = {'Tackle' : 40,
>   'Quick Attack' : 40,
>   'Bite' : 60}
>
>
> #Damage is (2xLevel)/5)+2)xPower)xAtk/Def)+2)/50
>
>
>
> #Battle Function
> def Battle():
> print('Wild '+Rattata['N']+' Appeared!')
> time.sleep(1)
> print('Go, '+Bulbasaur['N']+'!')
> time.sleep(1)
> print(Bulbasaur['N']+ ' is out.')
> while Bulbasaur['HP'] >= 1 and Rattata['HP'] >= 1:
> Move = input('What Will You Do? Fight or Run: ')
> if Move == Fight:
> pass
> elif Move == Run:  # This appears to be the problem.  Make Run into a 
> string, "Run" or 'Run'.
> RC = random.randint(1,3)
> if RC == 1 or 3:  # This probably does not do what you think it 
> does!
> print('You Didn\'t Get Away!')
> else:
> print('You Got Away!')
> break
> else:
> print('Typo')
> break
> Battle()


HTH!

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


[Tutor] Help

2018-05-15 Thread Sam Hoffman
Traceback (most recent call last):
  File "/Users/samhoffman/Documents/test.py", line 54, in 
Battle()
  File "/Users/samhoffman/Documents/test.py", line 41, in Battle
Move = input('What Will You Do? Fight or Run: ')
  File "", line 1, in 
NameError: name 'Run' is not defined



import time
import random
#Pokemon Stats
Bulbasaur = {'N' : 'Bulby',
 'HP' : 20,
 'Level' : 5,
 'Atk' : 8,
 'Def' : 9,
 'Spd' : 6}


Rattata = {'N' : 'Rattata',
   'HP' : 15,
   'Level' : 3,
   'Atk' : 5,
   'Def' : 6,
   'Spd' : 4}

#Move damages
BM = {'Vinewhip' : 45,
  'Tackle' : 40,
  'Razorleaf' : 55}


RM = {'Tackle' : 40,
  'Quick Attack' : 40,
  'Bite' : 60}


#Damage is (2xLevel)/5)+2)xPower)xAtk/Def)+2)/50



#Battle Function
def Battle():
print('Wild '+Rattata['N']+' Appeared!')
time.sleep(1)
print('Go, '+Bulbasaur['N']+'!')
time.sleep(1)
print(Bulbasaur['N']+ ' is out.')
while Bulbasaur['HP'] >= 1 and Rattata['HP'] >= 1:
Move = input('What Will You Do? Fight or Run: ')
if Move == Fight:
pass
elif Move == Run:
RC = random.randint(1,3)
if RC == 1 or 3:
print('You Didn\'t Get Away!')
else:
print('You Got Away!')
break
else:
print('Typo')
break
Battle()




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


Re: [Tutor] Help with loops

2018-05-01 Thread Isaac Tetteh
Hi Shannon,



Yes there is a way. First in my opinion I think queue.json is not really a JSON 
data structure but just a list of list. If you are able to read it then I 
that’s great.



One way to solve this is doing something like below:



queue = [

["James Bruce", "Bananas"],

["Katherine Newton", "Bananas"],

["Deborah Garcia", "Pears"],

["Marguerite Kozlowski", "Pineapples"],

["Kenneth Fitzgerald", "Pineapples"],

["Ronald Crawford", "Bananas"],

["Donald Haar", "Apples"],

["Al Whittenberg", "Bananas"],

["Max Bergevin", "Bananas"],

["Carlos Doby", "Pears"],

["Barry Hayes", "Pineapples"],

["Donald Haar", "Bananas"]

]



stock = {"Apples": 14,

  "Bananas": 14,

  "Pineapples": 0,

  "Pears": 8}



for i in queue:

if stock[i[1]] > 0 :

print("Gave {} to {}".format(i[1],i[0]))

else:

print("Could not give {} to {}".format(i[1],i[0]))



Let us know if you have any other questions.



Isaac,





Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for Windows 10




From: Tutor <tutor-bounces+itetteh34=hotmail@python.org> on behalf of 
Shannon Evans via Tutor <tutor@python.org>
Sent: Monday, April 30, 2018 8:35:01 AM
To: tutor@python.org
Subject: [Tutor] Help with loops

Hi, is there any way that i can add a loop or iteration or something so
that i dont have to write out every person who has fruit. This information
is coming from the following json files:
*queue.json* file

[

  ["James Bruce", "Bananas"],

  ["Katherine Newton", "Bananas"],

  ["Deborah Garcia", "Pears"],

  ["Marguerite Kozlowski", "Pineapples"],

  ["Kenneth Fitzgerald", "Pineapples"],

  ["Ronald Crawford", "Bananas"],

  ["Donald Haar", "Apples"],

  ["Al Whittenberg", "Bananas"],

  ["Max Bergevin", "Bananas"],

  ["Carlos Doby", "Pears"],

  ["Barry Hayes", "Pineapples"],

  ["Donald Haar", "Bananas"]

]



*stock.json* file

{

"Apples": 14,

"Bananas": 14,

"Pineapples": 0,

"Pears": 8

}

This is what i've done so far:

import json

#Load the stock and queue files
queue=json.load(open("queue.json"))
stock=json.load(open("stock.json"))

if (stock[queue[0][1]]>0):
#in stock
print "Gave Bananas to James Bruce"
else:
print "Could not give Bananas to James Bruce"

if (stock[queue[1][1]]>0):
#in stock
print "Gave Bananas to "+ queue[1][0]
else:
print "Could not give Bananas to "+ queue[1][0]

if (stock[queue[2][1]]>0):
#in stock
print "Gave Pears to "+ queue[2][0]
else:
print "Could not give Pears to "+ queue[2][0]

if (stock[queue[3][1]]>0):
#in stock
print "Gave Pineapples to "+ queue[3][0]
else:
print "Could not give Pineapples to "+ queue[3][0]

Thanks
Shannon
___
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] Help with loops

2018-04-30 Thread Alan Gauld via Tutor
On 30/04/18 14:35, Shannon Evans via Tutor wrote:
> Hi, is there any way that i can add a loop or iteration or something so
> that i dont have to write out every person who has fruit. 

Yes that's what loops are for.
You have two options in Python: a 'for' loop or a 'while' loop

In your case I suspect a 'for' loop is most appropriate.

This information
> is coming from the following json files:
> *queue.json* file
> 
> [
> 
>   ["James Bruce", "Bananas"],
> 
...
> ]
> 
> 
> 
> *stock.json* file
> 
> {
> 
> "Apples": 14,
> 
> "Bananas": 14,
> 
> "Pineapples": 0,
> 
> "Pears": 8
> 
> }

> import json
> 
> #Load the stock and queue files
> queue=json.load(open("queue.json"))
> stock=json.load(open("stock.json"))
> 

You need to start the loop here then indent everything
below. The syntax is like

for data in queue:
name, product = data

Now change the queue access items to use name and product.

> if (stock[queue[1][1]]>0):
> #in stock
> print "Gave Bananas to "+ queue[1][0]
> else:
> print "Could not give Bananas to "+ queue[1][0]
> 
> if (stock[queue[2][1]]>0):
> #in stock
> print "Gave Pears to "+ queue[2][0]
> else:
> print "Could not give Pears to "+ queue[2][0]
> 
> if (stock[queue[3][1]]>0):
> #in stock
> print "Gave Pineapples to "+ queue[3][0]
> else:
> print "Could not give Pineapples to "+ queue[3][0]

Try it, if you get stuck come back and show us what you did.
You will find more about Looping in my tutorial(see below)

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


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


[Tutor] Help with loops

2018-04-30 Thread Shannon Evans via Tutor
Hi, is there any way that i can add a loop or iteration or something so
that i dont have to write out every person who has fruit. This information
is coming from the following json files:
*queue.json* file

[

  ["James Bruce", "Bananas"],

  ["Katherine Newton", "Bananas"],

  ["Deborah Garcia", "Pears"],

  ["Marguerite Kozlowski", "Pineapples"],

  ["Kenneth Fitzgerald", "Pineapples"],

  ["Ronald Crawford", "Bananas"],

  ["Donald Haar", "Apples"],

  ["Al Whittenberg", "Bananas"],

  ["Max Bergevin", "Bananas"],

  ["Carlos Doby", "Pears"],

  ["Barry Hayes", "Pineapples"],

  ["Donald Haar", "Bananas"]

]



*stock.json* file

{

"Apples": 14,

"Bananas": 14,

"Pineapples": 0,

"Pears": 8

}

This is what i've done so far:

import json

#Load the stock and queue files
queue=json.load(open("queue.json"))
stock=json.load(open("stock.json"))

if (stock[queue[0][1]]>0):
#in stock
print "Gave Bananas to James Bruce"
else:
print "Could not give Bananas to James Bruce"

if (stock[queue[1][1]]>0):
#in stock
print "Gave Bananas to "+ queue[1][0]
else:
print "Could not give Bananas to "+ queue[1][0]

if (stock[queue[2][1]]>0):
#in stock
print "Gave Pears to "+ queue[2][0]
else:
print "Could not give Pears to "+ queue[2][0]

if (stock[queue[3][1]]>0):
#in stock
print "Gave Pineapples to "+ queue[3][0]
else:
print "Could not give Pineapples to "+ queue[3][0]

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


Re: [Tutor] Help!

2018-04-19 Thread Neil Cerutti
On 2018-04-19, Steven D'Aprano  wrote:
> Some program ideas...
>
> Encrypt and decrypt text using a Caesar Cipher.
>
> https://en.wikipedia.org/wiki/Caesar_cipher
>
> or one of many other simple ciphers.
>
> Calculate the prime numbers up to a certain limit.
>
> https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
>
> Play "Guess the number" games.
>
> Play 20 Questions.
>
> (Advanced)
> Given the formula for a (simple) molecule like H20, print the names of 
> the elements in the molecule, their atomic weights, and the total 
> molecular weight.
>
> Convert between temperature scales (degrees Celsius, Fahrenheit, and 
> Kelvin).

Excellent suggestions.

It could also be fun to build a text-based solitaire program of
your choice.

-- 
Neil Cerutti

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


Re: [Tutor] Help!

2018-04-19 Thread Steven D'Aprano
Hello Joshua, and welcome!

My comments below.


On Thu, Apr 19, 2018 at 01:15:59AM +, Joshua Nghe wrote:
> Hi,
> This is Joshua N from Campus Middle School.

You are talking to people from all over the world, and some of us are 
not familiar with what you mean by "Middle School". What is it? About 
what age group are you in?


> In my science class, we 
> are learning topics of our choice. I chose coding as my project, and I 
> am contacting you to ask about certain projects which would be 
> appropriate for a programmer at a beginner level. I only have 15 hours 
> on Python, however I expect to get to at least double that when I 
> start to work on my project. What projects would be appropriate for 
> someone of my level.

Very simple projects! 30 hours is not a lot of time to learn a 
programming language if your aim is a complex project.

Python is a great language and I love it, but unfortunately the graphics 
capabilities are very primitive, and even when you can get them working, 
it might take many more hours to become productive with them. So unless 
you have a LOT of help from your class, I recommand you stick to a 
text-based program.

Does your project have to be oriented towards science, or can it be 
anything at all?

Some program ideas...

Encrypt and decrypt text using a Caesar Cipher.

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

or one of many other simple ciphers.

Calculate the prime numbers up to a certain limit.

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

Play "Guess the number" games.

Play 20 Questions.

(Advanced)
Given the formula for a (simple) molecule like H20, print the names of 
the elements in the molecule, their atomic weights, and the total 
molecular weight.

Convert between temperature scales (degrees Celsius, Fahrenheit, and 
Kelvin).



Try reading here:

http://www.programmingforbeginnersbook.com/blog/what_should_i_make_beginner_programming_project_ideas/

Hope this helps!



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


[Tutor] Help!

2018-04-19 Thread Joshua Nghe
Hi,
This is Joshua N from Campus Middle School. In my science class, we are 
learning topics of our choice. I chose coding as my project, and I am 
contacting you to ask about certain projects which would be appropriate for a 
programmer at a beginner level. I only have 15 hours on Python, however I 
expect to get to at least double that when I start to work on my project. What 
projects would be appropriate for someone of my level.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with a task

2018-04-12 Thread Alan Gauld via Tutor
On 12/04/18 11:54, Aditya Mukherjee wrote:
> Hello, I'm relatively new to python and have been given a task for
> university, and would greatly appreciate if anyone could help me basically
> just get started because as of now I am completely clueless and have no
> idea what to do. I don't really know who to ask, but anything would be of
> assistance.

OK, First you need to tell us what the problem is, and as this
is a text based email service non-text attachments get stripped
by the server. You need to send a new mail explaining the problem,
what you have tried, or think you should try.

If you have any code, even if it doesn't work send it. That
way we can clearly see where you are getting things wrong
or are mis-understanding how things work. From your comments
below it is obvious that you have not fully grasped the meaning
of much of the programming jargon and terminology. Getting these
details right helps discuss solutions without confusion arising.

> I feel like I understand the basics of functions such as lists,
> if/elif etc. 

These are not functions. Lists are data structures and if/else
are control structures. Functions are something entirely different
(and possibly you haven't covered them yet).

> but can't really comprehend what to do with anything involving
> more than the use of simple functions.

Can you write a description in English (or your native tongue
if not English) of what you want the computer to do to solve
the problem? You need to understand how you would do it, without
a computer, to be able to make the computer do it for you.

If you can do that include it as requested above.

> Helping me getting started and just understanding what I actually need to
> do would be vastly helpful, as I've heard from other students that they
> have over 200 lines. :)

1 good line is often better than 100 bad lines. Don't worry about
volume, worry about results.

> I've attached the premise of what the task is asking for, due in 2 days.

We can't see the attachment, just send us the description in
text (or a URL link if that's easier). And 2 days is maybe too
late for this one - remember email can take 24 hours to be
delivered, so by the time everyone receives/reads/responds
and you get the answer 2 days could be 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


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


Re: [Tutor] Help with a task

2018-04-12 Thread David Rock

> On Apr 12, 2018, at 05:54, Aditya Mukherjee  
> wrote:
> 
> Helping me getting started and just understanding what I actually need to
> do would be vastly helpful, as I've heard from other students that they
> have over 200 lines. :)
> 
> I've attached the premise of what the task is asking for, due in 2 days.

This list does not support attachments, so we can’t see what your requirements 
are.

Also, we won’t do the work for you, so you need to help us help you by telling 
us what you have tried so far.  We can give guidance, but only if we can see 
where you have tried to go.

I would also recommend talking to your classmates that are having more success 
as a first attempt to get some direction.  2 days is not much time for a 
mailing list to help you understand an unknown assignment.


— 
David Rock
da...@graniteweb.com




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


[Tutor] Help with a task

2018-04-12 Thread Aditya Mukherjee
Hello, I'm relatively new to python and have been given a task for
university, and would greatly appreciate if anyone could help me basically
just get started because as of now I am completely clueless and have no
idea what to do. I don't really know who to ask, but anything would be of
assistance.


I feel like I understand the basics of functions such as lists,
if/elif etc. but can't really comprehend what to do with anything involving
more than the use of simple functions.


Helping me getting started and just understanding what I actually need to
do would be vastly helpful, as I've heard from other students that they
have over 200 lines. :)


I've attached the premise of what the task is asking for, due in 2 days.


Thank you in advance


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


Re: [Tutor] help with code

2018-03-11 Thread Abdur-Rahmaan Janhangeer
 print 30 * "-" , "MENU" , 30 * "-"

# just tested in py3 you can do
# 'MENU'.center(67, '-')

On Sun, Mar 11, 2018 at 8:20 AM, Leslie SimondeMontfort via Tutor <
tutor@python.org> wrote:

> Hi, I wondered if there is someone that can help me with this code.  Thank
> you, Leslie
>
> ## Text menu in Python
>
> def print_menu():   ## Your menu design here
> print 30 * "-" , "MENU" , 30 * "-"
> print "1. Menu login 1"
> print "2. Menu create an account 2"
> print "3. Menu list all accounts 3"
> print "4. Quit"
> print 67 * "-"
>
> loop!=4
>
> while loop:  ## While loop which will keep going until loop = False
> print_menu()## Displays menu
> choice = input("Enter your choice [1-4]: ")
>
> if choice==1:"Menu login 1"
> count = 0
> while True:
>   def User():
> login = raw_input("Enter login name: ")
> passw = raw_input("Enter password: ")
>
> # check if user exists and login matches password
> if login in users and users[login] == passw:
> print "\nLogin successful!\n"
> else:
> print "\nUser doesn't exist or wrong password!\n"
> if choice == 3:
> print("Too many attempts.")
> exit()
>
>
> for val in "string":
> if val == "i":
> break
> print(val)
>
> print("The end")
>
>if choice==2:
>print " Menu create an account 2"
>
>
> def main():
> register()
>
> def register():
> username = input("Please input your desired username ")
> password = input("Please input your desired password ")
>  if not username or not password:
> print "Enter a valid username and password..."
> users = c.get_all_users()
> userList = users['list_users_response']['
> list_users_result']['users']
> if username in userList:
> print "username already exist"
> else:
> # I just want to create if fields are not empty and if
> username dont exist
> c.create_user(username)
> file = open("credential.txt","a")
> file.write(username)
> file.write(" ")
> file.write(password)
> file.close()
> login()
>
>  if choice==3:
>
>  def login():
> check = open("credential.txt","r")
> username = input("Please enter your username")
> password = input("Please enter your password")
>
>  def thank_you():
>   print("Thank you for signing up at our website!.")
>
> elif choice == "q":
> exit()
> Sent from Mail for Windows 10
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Abdur-Rahmaan Janhangeer
https://github.com/abdur-rahmaanj
Mauritius
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with code

2018-03-11 Thread Bob Gailer
On Mar 11, 2018 6:25 AM, "Leslie SimondeMontfort via Tutor" <
tutor@python.org> wrote:
>
> Hi, I wondered if there is someone that can help me with this code.

I have to assume that you are very new to python. Have you written a Python
program that runs the way you want it to?

It is often useful to start by writing a very simple program that contains
one aspect of the problem you're trying to solve, then getting that program
to run. Then you add another feature and get that to run.

When you run into a problem, then email us the code, and tell us what
version of python you're using, what you did to run the program, what
results you expected, and what results you got. You can often handle the
latter by copying and pasting the execution. If the result was a traceback
be sure to include the entire traceback.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with code

2018-03-11 Thread Cameron Simpson

On 10Mar2018 23:20, Leslie SimondeMontfort  wrote:

Hi, I wondered if there is someone that can help me with this code.  Thank you, 
Leslie


Generally we like to know what you think is wrong with it. For example, what 
you expected it to do, and a little transcript of what it actually did 
(cut/paste the text from your terminal/console straight in this email, complete 
with any stack traces that came with it, if there were any).


This looks like homework, and we're generally happy to help if you'll explain 
what you're trying to achieve and show the code you have so far. I'm glad to 
see you've included all your code here, it is usually necessary.


Absent an actual error transcript I can make a few general remarks about the 
code which might lead you towards making it work the way you intend it to.


Remarks inline below, in the code:


## Text menu in Python

def print_menu():   ## Your menu design here
   print 30 * "-" , "MENU" , 30 * "-"
   print "1. Menu login 1"
   print "2. Menu create an account 2"
   print "3. Menu list all accounts 3"
   print "4. Quit"
   print 67 * "-"

   loop!=4


The line above "loop!=4" is a simple expression. It is valid, but useless.  
Normally a test with be part of a statement, such as the condition in an "if" 
or "while".


Also, because it is indented it is inside the "print_menu" function,
which doesn't seem very relevant - the function shouldn't care about
the value of "loop".


while loop:  ## While loop which will keep going until loop = False


You haven't set a value to "loop" yet, so this code will raise an exception as 
soon as you try to test "loop". Probably it should be set to True before the 
loop begins.



   print_menu()## Displays menu
   choice = input("Enter your choice [1-4]: ")

if choice==1:"Menu login 1"
count = 0


Indentation is important in Python. Because this "if" statement is not 
indented, it is outside the "while" loop above. It looks like you while loop is 
meant to offer menu choices until the user chooses "Quit". So all the code 
acting on those choices needs to be inside the loop, and thus indents the same 
as the 2 lines above it which print the menu and read the choice.


You're setting "count = 0" but I don't see you use "count" elsewhere.


while True:
 def User():
   login = raw_input("Enter login name: ")
   passw = raw_input("Enter password: ")

   # check if user exists and login matches password
   if login in users and users[login] == passw:
   print "\nLogin successful!\n"
   else:
   print "\nUser doesn't exist or wrong password!\n"
   if choice == 3:
   print("Too many attempts.")
   exit()


This probably doesn't do what you imagine. A "def" statement is a statement, to 
be run. This loop runs forever, but all it does in the loop is _define_ the 
function "User". It never calls the function. So it will just run forever, 
redefining the function again and again.


Probably you need to define the function _before_ the loop, and actually call 
the function inside the loop.


Normally all your function definitions will be outside the main code, so the 
"User" function definition should be above this, for example right underneath 
your "print_menu" function definition. Likewise your other functions.



for val in "string":
   if val == "i":
   break
   print(val)


I presume this is just a little exercise loop to print some of the leading 
characters from the string "string".



print("The end")

  if choice==2:
  print " Menu create an account 2"


This "if" statement _is_ indented correctly for the main loop you set up 
earlier, but all the intervening code will be getting in the way. Once you have 
all the function definitions up the top of your code things will work better.


def main():
   register()


Note that this just defines a "main" function. Nothing seems to call it.


def register():
   username = input("Please input your desired username ")
   password = input("Please input your desired password ")
if not username or not password:


This "if" is indented differently to the other statements in this function. It 
needs to move left one space.


You seem to be using Python 2. In Python 2, input() actually evaluates the 
input string as a Python expression. This is why you got an integer earlier 
when you prompted the user for "choice". However, when reading strings such as 
usernames or passwords you need to use raw_input(), not input(). raw_input() 
just reads the string and returns it.



   print "Enter a valid username and password..."


Here's you are admonishing the user for entering an empty username or password.  
However you don't then do anything about it; instead your code falls through 
and starts setting up the user.


You probably want a loop shapes more like this (totally untested):

   while True:
   username = input("Please input your desired username ")
   if len(username) == 0:
   print("Empty 

Re: [Tutor] help with code

2018-03-11 Thread Alan Gauld via Tutor
On 11/03/18 04:20, Leslie SimondeMontfort via Tutor wrote:
> Hi, I wondered if there is someone that can help me with this code. 

I'll try but theres a lot to comment on.
See below...

> def print_menu():   ## Your menu design here
> print 30 * "-" , "MENU" , 30 * "-"
> print "1. Menu login 1"
> print "2. Menu create an account 2"
> print "3. Menu list all accounts 3"
> print "4. Quit"
> print 67 * "-"
> 
> loop!=4

That last line makes no sense. Its a boolean expression using an
undeclared variable(loop) You should get a name error when you run
it.

> while loop:  ## While loop which will keep going until loop = False

Again you reference loop but you have not assigned any
value to it. You should get an error here too.

> print_menu()## Displays menu
> choice = input("Enter your choice [1-4]: ")

This is the end of your while loop and you have not modified
the test condition (loop) so even if loop existed this would
just loop forever. One of the fundamental principles of while
loops is that you must either modify the test condition
somehow or use a break somewhere inside the loop.

Also using input to convert your data is a bad design. ijput is very
insecure and users could (deliberately or by accident) type values which
python then executes and cause damagew, in extreme cases even crashing
your computer. Its much better to explicitly convert the raw_input string:

 choice = int(raw_input("Enter your choice [1-4]: "))

To catch invalid input wrap it in a try/except block...


> if choice==1:"Menu login 1"
>   count = 0

This doesn't work either. You have an if test where the
body is the single line containing the string. It doesn't
do anything  although it is legal Python but...
The next line is indented as if it were part of the if
block but it isn't so you should get an error there too.

> while True: 
>   def User():
> login = raw_input("Enter login name: ")
> passw = raw_input("Enter password: ")
> 
> # check if user exists and login matches password
> if login in users and users[login] == passw: 
> print "\nLogin successful!\n"
> else:
> print "\nUser doesn't exist or wrong password!\n"
> if choice == 3:
> print("Too many attempts.")
> exit()

Now you have a loop that will go forever continually defining
(but not calling) a function.

Inside the function you might want to check the getpass
function from the getpass module for a more secure password
input. If you are on Unix/Linux/MacOS you could also look
at the pwd module for ways of validating the user.

Fiunally note that the if coice === 3 line is inside
the invalid user block so would only be executed if it
was an invalid user - which seems wrong?

In fact I'd suggest that if block should not even be
inside the User() function at all. Its not really checking
anything about the user, its checking what the user did.
Try to keep your functions purpose clear and distinct,
don't mix functionality in a single function.

> for val in "string":
> if val == "i":
> break

This assigns val to s,then t then r then i so it will allways break on
the 4th cycle.

You might as well just write

for val in 'str':

> print(val)

And since you just print val you might as well miss out the loop and use

print('s\nt\nr\n')

> print("The end")
>
>if choice==2: 
>print " Menu create an account 2"

This is indented but there is no enclosing block so
should give an indentation error.

> def main():
> register()
> 
> def register():
> username = input("Please input your desired username ")
> password = input("Please input your desired password ")
>  if not username or not password:
> print "Enter a valid username and password..."
> users = c.get_all_users()
> userList = users['list_users_response']['list_users_result']['users']

Note the indentation is all over the place.
Python is fussy about consistent indentation, you will get errors here.

Also you reference c but c does not appear anywhere else.
What is c?

The remaining code has more of the same so I'll stop here.
I think you need to strip this back and get the basic structure working
first before trying to add all the other functions.

print a menu, read the input and print the users choice.
Exit when option 4 is used.

Get that working then you can add the code to process
the choices one by one. Get each choice working before
adding the next.

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


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


Re: [Tutor] help with code

2018-03-11 Thread Joel Goldstick
On Sat, Mar 10, 2018 at 11:20 PM, Leslie SimondeMontfort via Tutor <
tutor@python.org> wrote:

> Hi, I wondered if there is someone that can help me with this code.  Thank
> you, Leslie
>
> ## Text menu in Python
>
> def print_menu():   ## Your menu design here
> print 30 * "-" , "MENU" , 30 * "-"
> print "1. Menu login 1"
> print "2. Menu create an account 2"
> print "3. Menu list all accounts 3"
> print "4. Quit"
> print 67 * "-"
>
> loop!=4
>
> while loop:  ## While loop which will keep going until loop = False
> print_menu()## Displays menu
> choice = input("Enter your choice [1-4]: ")
>
> if choice==1:"Menu login 1"
> count = 0
> while True:
>   def User():
> login = raw_input("Enter login name: ")
> passw = raw_input("Enter password: ")
>
> # check if user exists and login matches password
> if login in users and users[login] == passw:
> print "\nLogin successful!\n"
> else:
> print "\nUser doesn't exist or wrong password!\n"
> if choice == 3:
> print("Too many attempts.")
> exit()
>
>
> for val in "string":
> if val == "i":
> break
> print(val)
>
> print("The end")
>
>if choice==2:
>print " Menu create an account 2"
>
>
> def main():
> register()
>
> def register():
> username = input("Please input your desired username ")
> password = input("Please input your desired password ")
>  if not username or not password:
> print "Enter a valid username and password..."
> users = c.get_all_users()
> userList = users['list_users_response']['
> list_users_result']['users']
> if username in userList:
> print "username already exist"
> else:
> # I just want to create if fields are not empty and if
> username dont exist
> c.create_user(username)
> file = open("credential.txt","a")
> file.write(username)
> file.write(" ")
> file.write(password)
> file.close()
> login()
>
>  if choice==3:
>
>  def login():
> check = open("credential.txt","r")
> username = input("Please enter your username")
> password = input("Please enter your password")
>
>  def thank_you():
>   print("Thank you for signing up at our website!.")
>
> elif choice == "q":
> exit()
> Sent from Mail for Windows 10
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

A quick look shows you are using print statements and print functions.  So,
are you using python 3 or python 2?  What exactly are you asking about?

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


[Tutor] help with code

2018-03-11 Thread Leslie SimondeMontfort via Tutor
Hi, I wondered if there is someone that can help me with this code.  Thank you, 
Leslie

## Text menu in Python

def print_menu():   ## Your menu design here
print 30 * "-" , "MENU" , 30 * "-"
print "1. Menu login 1"
print "2. Menu create an account 2"
print "3. Menu list all accounts 3"
print "4. Quit"
print 67 * "-"

loop!=4

while loop:  ## While loop which will keep going until loop = False
print_menu()## Displays menu
choice = input("Enter your choice [1-4]: ")
 
if choice==1:"Menu login 1"
count = 0 
while True: 
  def User():
login = raw_input("Enter login name: ")
passw = raw_input("Enter password: ")

# check if user exists and login matches password
if login in users and users[login] == passw: 
print "\nLogin successful!\n"
else:
print "\nUser doesn't exist or wrong password!\n"
if choice == 3:
print("Too many attempts.")
exit()


for val in "string":
if val == "i":
break
print(val)

print("The end")
   
   if choice==2: 
   print " Menu create an account 2"


def main():
register()

def register():
username = input("Please input your desired username ")
password = input("Please input your desired password ")
 if not username or not password:
print "Enter a valid username and password..."
users = c.get_all_users()
userList = users['list_users_response']['list_users_result']['users']
if username in userList:
print "username already exist"
else:
# I just want to create if fields are not empty and if username 
dont exist
c.create_user(username)
file = open("credential.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.close()
login()

 if choice==3: 
  
 def login():
check = open("credential.txt","r")
username = input("Please enter your username")
password = input("Please enter your password")

 def thank_you():
  print("Thank you for signing up at our website!.")
  
elif choice == "q":
exit()
Sent from Mail for Windows 10

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


Re: [Tutor] [Help] urllib.error.HTTPError: HTTP Error 400: Bad Request

2018-02-13 Thread Peter Otten
cm wrote:

> Dear tutors,
> 
> I have written below function to open the profanity check url and then
> to check for profanity in some text. When I go to the url
> http://www.wdylike.appspot.com/?q= and type in the same text, it works
> fine.
> 
> I am using Microsoft OS X and Python 3.5.2 Interpreter with Pycharm
> Community Edition.
> 
> ---
> import urllib.request
> 
> def check_profanity(some_text):
> # check text for a curse word
> connection =
> urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+some_text)
> output = connection.read()
> print(output)
> connection.close()
> 
> check_profanity(some_text="I gave it a good shot")
> ---
> 
> Error message:
> Traceback (most recent call last):
>   File
>   "C:/Users/Administrator/PycharmProjects/Udacity/profanity_check.py",
> line 29, in 
> check_profanity(some_text="I gave it a good shot")
>   File
>   "C:/Users/Administrator/PycharmProjects/Udacity/profanity_check.py",
> line 15, in check_profanity
> connection =
> urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+some_text)
>   File "C:\Program Files\Anaconda3\lib\urllib\request.py", line 163, in
>   urlopen
> return opener.open(url, data, timeout)
>   File "C:\Program Files\Anaconda3\lib\urllib\request.py", line 472, in
>   open
> response = meth(req, response)
>   File "C:\Program Files\Anaconda3\lib\urllib\request.py", line 582,
> in http_response
> 'http', request, response, code, msg, hdrs)
>   File "C:\Program Files\Anaconda3\lib\urllib\request.py", line 510, in
>   error
> return self._call_chain(*args)
>   File "C:\Program Files\Anaconda3\lib\urllib\request.py", line 444,
> in _call_chain
> result = func(*args)
>   File "C:\Program Files\Anaconda3\lib\urllib\request.py", line 590,
> in http_error_default
> raise HTTPError(req.full_url, code, msg, hdrs, fp)
> urllib.error.HTTPError: HTTP Error 400: Bad Request
> 
> Process finished with exit code 1
> 
> ---
> However when I run the code it just says Bad Request. I tried to read
> into the traceback message but it refers not only to my file but the
> urllib function itself too and I can't understand.

Spaces aren't allowed in the url:

>>> c = rq.urlopen("http://www.wdylike.appspot.com/?q=nice try")
[...]
urllib.error.HTTPError: HTTP Error 400: Bad Request

Once you escape the ' ':

>>> c = rq.urlopen("http://www.wdylike.appspot.com/?q=nice+try;)
>>> c.read()
b'false'

Have a look at the first example at

https://docs.python.org/dev/library/urllib.request.html#urllib-examples

for a more general solution.

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


  1   2   3   4   5   6   7   8   9   10   >