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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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 for Windows 10




From: Tutor  on behalf of 
Shannon Evans via Tutor 
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


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


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


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


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


Re: [Tutor] help

2018-02-08 Thread Frank Dominguez
Thanks for the tip!

On Feb 7, 2018 18:49, "Rex"  wrote:

> I think you need to convert the input value to an integer with
> int(variable_name)
>
>
>
> Sent from my iPhone
>
> > On Feb 7, 2018, at 4:34 PM, Frank Dominguez 
> wrote:
> >
> > greetings,
> > this is my first time using python and i just cannot figure out what I am
> > doing wrong im sure the answer is very simple but sadly i do not know
> what
> > it is
> > thanks for the help!
> > 
> > ___
> > 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

2018-02-07 Thread Rex via Tutor
I think you need to convert the input value to an integer with 
int(variable_name)



Sent from my iPhone

> On Feb 7, 2018, at 4:34 PM, Frank Dominguez  wrote:
> 
> greetings,
> this is my first time using python and i just cannot figure out what I am
> doing wrong im sure the answer is very simple but sadly i do not know what
> it is
> thanks for the help!
> 
> ___
> 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

2018-02-07 Thread Alan Gauld via Tutor
On 07/02/18 21:34, Frank Dominguez wrote:

> this is my first time using python and i just cannot figure out what I am
> doing wrong im sure the answer is very simple but sadly i do not know what

Please always include full error messages in your mail
 - don't assume we will willingly run buggy code!

Also post the code in the email, using plain text rather
than attaching it. It makes replies easier and ensures
it doesn't get lost in the archives.

Here is yours with my comments:

> length = eval(input("Enter the length of the yard")
> width = eval(input("Enter the width of the yard")
> sod = eval(input("Enter the cost of sod"

You are missing a closing paren there.
But you are also missing a closing paren on all
the other lines. You close the input() but not
the eval()

> fence = eval(input("What is the cost of the fence")

Never, ever, combine eval() with input() it is a
recipe for disaster since a malicious user (or
a mis-typing one) can wreak havoc by typing in
malicious code that could, potentially trash
your computer. It's a very bad habit, avoid at
all costs.

Read the input and convert it explicitly using
int() or float() or whatever. Like so:

fence = float(input("What is the cost of the fence"))

It's much safer (and not much extra typing).

> area = length*width
> perimeter = length*2+width*2
> total_sod = area*sod
> total_fence = fence*perimeter
> landscaping = total_sod+total_fence
> print ("the total cost of landscaping is",landscaping)

This bit seems fine.

-- 
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 some code for my 8 year old! Thank you.

2018-02-03 Thread Alan Gauld via Tutor
On 03/02/18 02:12, JSelby wrote:
>My 8 year old is reading  Python for kids and is trying a few programs
>from the book We are working on a Mac  OS X ELCapitain.  We are looking at
>WHACK THE BOUNCING BALL.
>He has copied the code  below and we get the red error message below. 

This is a text only mailing list so attachments get stripped
by the server. Please resend but cut 'n paste the actual text
into the mail message, don't use an attachment.

If that doesn't work you could post the attachments on a
web server and send a link that we can view.

For the error messages be sure to send the entire message
not just a few lines or summary.

>Object: [1]application/x-apple-msg-attachment
>Object: [2]application/x-apple-msg-attachment

-- 
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 some code for my 8 year old! Thank you.

2018-02-03 Thread Whom Isac
Sorry can't see any error messages through the visible links.

On 3 Feb. 2018, 7:08 pm, at 7:08 pm, JSelby  wrote:
> My 8 year old is reading  Python for kids and is trying a few programs
>from the book We are working on a Mac  OS X ELCapitain.  We are looking
>at
>   WHACK THE BOUNCING BALL.
>He has copied the code  below and we get the red error message below.
>We
>followed the code exactly so are not sure what is wrong. Please can you
>   help.
>   Object: [1]application/x-apple-msg-attachment
>   Object: [2]application/x-apple-msg-attachment
>   Julie Selby
>   [3]ju...@beaglestrategy.com
>   Tel: 604 762 1968
>   [4]http://ca.linkedin.com/in/julieselby/
>   [5]www.beaglestrategy.com
>
>References
>
>   Visible links
> 1. file:///tmp/cid:BC5630A8-FD4A-488B-9979-8A8936D74EC7@hitronhub.home
> 2. file:///tmp/cid:80B89FF3-BA17-444D-8E95-8C63CCF4851F@hitronhub.home
>   3. mailto:ju...@beaglestrategy.com
>   4. http://ca.linkedin.com/in/julieselby/
>   5. http://www.beaglestrategy.com/
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help regarding creating tags

2017-11-01 Thread Alan Gauld via Tutor
On 01/11/17 06:02, Hemant Sain wrote:
> i want to tag categories to its menuname.

Your description below does not explain how you will
tag them together, you simply identify which menu
items have a category, but no way to determine
which category goes with which menu item?

> i have a csv containing menu item name and in other 
> csv i have a column containing some strings,

> i want to pick that strings from categories and look into  menu items if
> any menu item containing that string i want to create a new column next to
> menu item name flagged as 1 otherwise 0
> and the only condition is once a menu item flagged
> as 1 i don't need to consider that menu item again
> to tag further in case of redundant strings

That sounds like what you think the solution
should be rather than your actual requirement.
I'd suggest it might be easier to create two
lists and move the found results into the
second list. this has the advantage of reducing
the number of items to be searched without having
to do any extra tests

But at the end you will simply have identified
which items have a category and which have not,
you will not have identified which category
each item belongs to. Maybe you need to store
the category alongside the items once you find
a match? Or better still use a dictionary keyed
by category?

In pseudo code it might look like:

results = {}
for category in categories:
results[category] = [ item for item in menuitems
  if category in item ]

But maybe a dictionary is not what you need
for your output format? And what to do with
menuitems that don't match any category?
That take us back to a dual list 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


Re: [Tutor] Help with python 2.7

2017-10-30 Thread Mike Miller
This is a mailing list, so the best way to get help is to send a request
with code examples and most importantly what you have already tried. That
being said, there are some smart people on here, much more experienced than
I am on Python so I would say you can get help with any problem you may
have.

I have taken the MIT course you are talking about and it is quite
challenging (perhaps a little more than it should be) and my oldest son at
one point took the Microsoft MVA course on the subject of python and he
said it was very good (surprisingly enough)..he is a Java programmer
primarily and said that for someone with even average skill and ability,
the MS course is actually great and easy to follow on. Good luck, and
welcome.

Mike

On Mon, Oct 30, 2017, 7:24 PM Alchemy  wrote:

> Hello,
>
> I am in the midst of a career change from renovations to computers.
> I’m used to working conceptually and understand coding is that.
> I am taking an online opencourseare classfrom MIT “Introduction to
> computer science and programming”.
> The class uses python 2.7, has video lectures and homework assignments
> that are coding exercises.
> Python seems like the root to everything in the computers possabilities
> and I want to internalize it.
> I’m stuck on the homework ,butmore importantly stuck on the concepts
> behind the homework.
>
> Can your orginazation help?
>
> gratefully,
>
> Ian
>
> ___
> 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 python 2.7

2017-10-30 Thread Alan Gauld via Tutor
On 30/10/17 21:02, Alchemy wrote:

> I’m stuck on the homework ,butmore importantly stuck on the concepts behind 
> the homework.
> 
> Can your orginazation help?

Yes, we are happy to help with homework although we won't
usually give you the full answer. We will make suggestions
and are happy to review or comment on code.

To make life easier:

Always post any code in plain text (email messes up the
formatting of html/rtf) And put it inline not as an attachment.

Always post the full text of any error messages.

Mention the OS and Python versions.

-- 
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 putting numbers from highest to lowest.

2017-09-27 Thread Mark Lawrence via Tutor

On 27/09/2017 20:36, Derry, James R wrote:




[Top posting fixed]



From: Tutor [tutor-bounces+jderry=mail.utexas@python.org] on behalf of 
edmundo pierre via Tutor [tutor@python.org]
Sent: Wednesday, September 27, 2017 8:10 AM
To: Tutor Python
Subject: [Tutor] Help with putting numbers from highest to lowest.

Hello,
When I used sort() to do that, but my problem is that sort() just arrange 
numbers from small to big, not from big to small. That is the issue I am having 
now. For instance:
# The user is entering those numbers:a = 2.7b = 4.7c= 5.8d = 7.9# I will like 
the answer to be like this: 7.9  5.8  4.7 2.7
#but if I use sort(), I will have that answer, but I do not want that:2.7 4.7 
5.8 7.9
Thank you!


> In [2]: ?sorted

Noting that this is iPython specific...

> Signature: sorted(iterable, /, *, key=None, reverse=False)
> Docstring:
> Return a new list containing all items from the iterable in ascending 
order.

>
> A custom key function can be supplied to customize the sort order, 
and the

> reverse flag can be set to request the result in descending order.
> Type:  builtin_function_or_method
>
> In [3]: sorted([3,1,5], reverse=True)
> Out[3]: [5, 3, 1]

...as are all the In[x] and Out[y] bits and pieces.

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

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


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


Re: [Tutor] Help with putting numbers from highest to lowest.

2017-09-27 Thread Mark Lawrence via Tutor

On 27/09/2017 14:10, edmundo pierre via Tutor wrote:

Hello,
When I used sort() to do that, but my problem is that sort() just arrange 
numbers from small to big, not from big to small. That is the issue I am having 
now. For instance:
# The user is entering those numbers:a = 2.7b = 4.7c= 5.8d = 7.9# I will like 
the answer to be like this: 7.9  5.8  4.7 2.7
#but if I use sort(), I will have that answer, but I do not want that:2.7 4.7 
5.8 7.9
Thank you!


You need reverse=True on the call to sort.

You can find this out by:-

1. Using the interactive interpreter help, e.g.

>>> l = [2.7, 4.7, 5.8, 7.9]
>>> help(l.sort)
Help on built-in function sort:

sort(*, key=None, reverse=False) method of builtins.list instance
Stable sort *IN PLACE*.

None

2. clicking `index` to the top right of https://docs.python.org/3/, then 
`s` then `(list method)` under `sort`.


3. using your favourite search engine.

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

Mark Lawrence

---
This email has been checked for viruses by AVG.
http://www.avg.com


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


Re: [Tutor] Help with putting numbers from highest to lowest.

2017-09-27 Thread Derry, James R
In [2]: ?sorted
Signature: sorted(iterable, /, *, key=None, reverse=False)
Docstring:
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
Type:  builtin_function_or_method

In [3]: sorted([3,1,5], reverse=True)
Out[3]: [5, 3, 1]


From: Tutor [tutor-bounces+jderry=mail.utexas@python.org] on behalf of 
edmundo pierre via Tutor [tutor@python.org]
Sent: Wednesday, September 27, 2017 8:10 AM
To: Tutor Python
Subject: [Tutor] Help with putting numbers from highest to lowest.

Hello,
When I used sort() to do that, but my problem is that sort() just arrange 
numbers from small to big, not from big to small. That is the issue I am having 
now. For instance:
# The user is entering those numbers:a = 2.7b = 4.7c= 5.8d = 7.9# I will like 
the answer to be like this: 7.9  5.8  4.7 2.7
#but if I use sort(), I will have that answer, but I do not want that:2.7 4.7 
5.8 7.9
Thank you!
___
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 putting numbers from highest to lowest.

2017-09-27 Thread Roel Schroeven

edmundo pierre via Tutor schreef op 27/09/2017 15:10:

Hello,
When I used sort() to do that, but my problem is that sort() just arrange 
numbers from small to big, not from big to small. That is the issue I am having 
now. For instance:
# The user is entering those numbers:a = 2.7b = 4.7c= 5.8d = 7.9# I will like 
the answer to be like this: 7.9  5.8  4.7 2.7
#but if I use sort(), I will have that answer, but I do not want that:2.7 4.7 
5.8 7.9


You can reverse the sort order with reverse=True, like so:

numbers = [7.9, 4.7, 2.7, 5.8]
numbers.sort(reverse=True)
print(numbers)

--> [7.9, 5.8, 4.7, 2.7]

See https://docs.python.org/3/library/stdtypes.html?highlight=sort#list.sort

--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven

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


Re: [Tutor] Help

2017-09-15 Thread Abdur-Rahmaan Janhangeer
besides already written notes,
i suggest

use .split(".")

floatNum = input("> ")

parts = floatNum.split(".")
whole = parts[0]
deci = parts[1]



Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

On 7 Sep 2017 21:51, "edmundo pierre via Tutor"  wrote:

>
> I am trying to write a code that asks an User to Enter a decimal number,
> the my program should separate the number in two parts like this:
> 1 cae:Enter a number: 12.9Decimal part: 12whole part : 9
> 2 case:Enter: 10Decimal par:Whole part: 10
> That is my code:
> A = input("Enter a number")
> C = [ ] for  i  in  str(A) :
>   C.append(i)  if i ==".# period ": break  aa=
> "".join(c)   print(aa, end =" ")
>if i == int(A): print(" It is the whole part")
> I can not display the whole part when I enter float number. Plus when I
> enter an integer, it takes that enteger as a decimal number. Any help?
> ___
> 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

2017-09-07 Thread boB Stepp
Greetings Edmundo!

On Thu, Sep 7, 2017 at 1:35 PM, Peter Otten <__pete...@web.de> wrote:
> edmundo pierre via Tutor wrote:
>
>>
>> I am trying to write a code that asks an User to Enter a decimal number,
>> the my program should separate the number in two parts like this: 1
>> cae:Enter a number: 12.9Decimal part: 12whole part : 9 2 case:Enter:
>> 10Decimal par:Whole part: 10 That is my code:
>> A = input("Enter a number")
>> C = [ ] for  i  in  str(A) :
>> C.append(i)  if i ==".# period ": break  aa= "".join(c)
>> print(aa, end =" ") if i == int(A): print(" It is the whole part")
>> I can not display the whole part when I enter float number. Plus when I
>> enter an integer, it takes that enteger as a decimal number. Any help?
>
> Hello Edmundo!
>
> We are all volunteers. Please help us help you. If you have a look at
>
> https://mail.python.org/pipermail/tutor/2017-September/111984.html
>
> you can see what we see of your code. It's completely garbled, and second-
> guessing what it might originally have looked like is no fun.
>
> You have to find out how to get your email program to send unmodified plain
> text before we can engage in a meaningful conversation.

I'd like to augment Peter's request:  Please use a more informative
subject line than "Help".  I notice you have posted two "Help" emails
recently on two substantially different topics.

As to the most current topic, your code is garbled to me as well, but
it looks like you realize that input() returns a string, not a float,
and that you are trying to use string methods to get what you want.
Another approach you might want to look into is using float(input())
to convert the string resembling a float into a floating point number
and then use the operator "//" (to perform integer division) and then
use that result to extract the decimal portion.  You will still have
to work on dealing with the decimal point removal and just getting the
decimal fraction as just integer-like numbers, but that is not too
hard ...

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


Re: [Tutor] Help

2017-09-07 Thread Mats Wichmann
On 09/07/2017 10:20 AM, edmundo pierre via Tutor wrote:
> 
> I am trying to write a code that asks an User to Enter a decimal number, the 
> my program should separate the number in two parts like this:
> 1 cae:Enter a number: 12.9Decimal part: 12whole part : 9
> 2 case:Enter: 10Decimal par:Whole part: 10
> That is my code: 
> A = input("Enter a number")
> C = [ ]     for  i  in  str(A) :
>       C.append(i)      if i ==".# period ":         break      aa= "".join(c) 
>   print(aa, end =" ")
>    if i == int(A):         print(" It is the whole part")
> I can not display the whole part when I enter float number. Plus when I enter 
> an integer, it takes that enteger as a decimal number. Any help?

Depending on what you have already learned, these hints may be helpful.

1. type() will let you experiment with what Python thinks you got. So as
to the second question,

A = input("Enter a number")
print(type(A))

if it is not what you expected, how can you get it to something you can
work with. Hint: you're already doing that once in your code.

2. strings are easy to split into pieces.  See the split() method.  This
simple tutorial might give you an idea:

http://www.pythonforbeginners.com/dictionary/python-split

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


Re: [Tutor] Help

2017-09-07 Thread Peter Otten
edmundo pierre via Tutor wrote:

> 
> I am trying to write a code that asks an User to Enter a decimal number,
> the my program should separate the number in two parts like this: 1
> cae:Enter a number: 12.9Decimal part: 12whole part : 9 2 case:Enter:
> 10Decimal par:Whole part: 10 That is my code:
> A = input("Enter a number")
> C = [ ] for  i  in  str(A) :
> C.append(i)  if i ==".# period ": break  aa= "".join(c)  
> print(aa, end =" ") if i == int(A): print(" It is the whole part")
> I can not display the whole part when I enter float number. Plus when I
> enter an integer, it takes that enteger as a decimal number. Any help?

Hello Edmundo!

We are all volunteers. Please help us help you. If you have a look at

https://mail.python.org/pipermail/tutor/2017-September/111984.html

you can see what we see of your code. It's completely garbled, and second-
guessing what it might originally have looked like is no fun.

You have to find out how to get your email program to send unmodified plain 
text before we can engage in a meaningful conversation.

Thank you.

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


Re: [Tutor] Help

2017-09-06 Thread Chris Warrick
On 6 September 2017 at 08:39, edmundo pierre via Tutor  wrote:
> Hi Python,
> I am trying to make a french to English dictionary. First of all, I made a 
> dictionary with keys and values. Then I asked the user to enter a letter. If 
> the letter correspond to the Keys, my print function should display the Key 
> and value. But my code below, could not . Thank you!
>
> List ={"le":"…"}
(it”s called dict, or dictionary, and “List”/“dict” are not good variable names)

> keys = List.keys()print(keys)
> a = str(input(""))
> if 'a' in keys:print(a + ":"+ List['a'])else:print("impossible")

You’re trying to find the letter 'a' and print it, you aren’t using
the variable a. Don’t put it in quotes. So, do it like this:

data = {"le": "…"}
print(data.keys())
search_key = str(input("> "))
if search_key in data:
print(search_key, ":", data[search_key])
else:
print("Not in dictionary.")

(I also cleaned it up a little)

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


Re: [Tutor] Help With Python Tasks

2017-09-05 Thread Alan Gauld via Tutor
On 05/09/17 19:25, Ruth Hardy wrote:

> I was wondering if you can help me please with these computer science tasks

We can help, but we won;t do them for you.

> First Task
> 
> Write code do the following things involving strings.  Wherever possible, 
> you should try to incorporate functions/procedures, 
> 
> Print a list of 20 random numbers one after the other vertically on the 
> screen.

There are (at least) two ways to do this. One very easy but laborious,
the other much shorter and quicker.
Do you know what they are? Can you print 20 numbers (forget random for
now) on the screen?

> Half way through, use a user input request to pause printing until 
> input is received.

Do you know how to read user input?

> Ask a user to enter two numbers, one after the other.  

This is slightly ambiguous, but I'd assume they mean
you should ask for input twice.
Do you know how to store user input into a variable?
Do you know how to convert user input to a number?

> Your code should validate that you receive numbers and 
> prompt the user appropriately.  

Do you know how to validate/check that the received
input is a number? (there are several ways to do this,
I'm not sure how they expect you to tackle it, it depends
on what you've been taught so far)


For the:
> first number, use try-except to ensure you have a floating point number; 

OK, That answers my question. You can use try/except
to check the number is valid...

> place a comment in you code about how this works
> second number, use .isnumeric() to check you have an integer; 

OK, They tell you what to do here.
Personally I don;t like the isnumeric() technique but its
what they want you to do so do it...

> Use a forced type conversion to turn both numbers into floats, >divided one 
> by the other and print the answer to 2 d.p.

Do you know how to print a number so it shows two dp?

> You code should keep on asking for numbers until two have been received.

OK, Lets just get it working for a single pair of numbers first.
Done that? Good, so now wrap it in a loop. What kind of loop will
work here?

> Ask the user to input a true/false value and convert th> input to a Boolean 
> (hint: I don’t think you can do a forced
> type conversion for this…)

The hint is correct.
How would you do it without a type conversion?

> Second Task 

Let's leave this task to another email.

See if you can answer the questions above.
If you can you should be able to join the bits together to get
the task completed. If not come back to us with specific
issues sand we'll explain a bit more.

Show us your code plus any error messages you get.

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

2017-08-19 Thread Cameron Simpson

On 19Aug2017 06:13, kay Cee  wrote:

   update_log = open('update_log.txt', 'r+')


Normally one would use 'a' (append) for a log open. I don't see what 'r+' 
accomplishes for you. In particular I expect it would always write at the start 
of the log file, overwriting whatever was there. Which might be your problem.


Others have made other remarks.

I'm not sure any of your problems have to do with the subprocess module itself.

Cheers,
Cameron Simpson  (formerly c...@zip.com.au)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with subprocess module

2017-08-19 Thread Alan Gauld via Tutor
On 19/08/17 11:13, kay Cee wrote:

> import subprocess
> import time
> import datetime
> 
> class UpdateError(Exception):
> pass

In defining your own type of Exception you implicitly
say that you will be raising it somewhere. But you
never raise this exception in your code...

> def update():
> while True:
> try:
> update_log = open('update_log.txt', 'r+')
> time.sleep(1)

Do you really want to run apt-get update every second?
That seems way too frequent, every hour would be a lot,
every day more reasonable.

> subprocess.call(['apt-get', 'update', '-y'])
> date = datetime.datetime.now()
> update_log.write("System was updated sucessfully on {}\n".format
> (str(date)))
> subprocess.call(['reboot'])

And do you want your computer rebooting after every
successful apt-get update? You really should not have
to do that. Especially every second, you are likely
to make your system unusable.

> except UpdateError:
> print("Update Error!!!")

Since nothing raises an UpdateError you will never receive one.
You are more likely to get an OSError or an IOError or a
FileNotFound or similar.

> update_log.close()

Since you open the file inside the loop you should close
it inside the loop. Ideally inside a finally clause.
Or better still use a with... construct to open the
file then you don;t need to close it yourself.

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

2017-08-19 Thread Mats Wichmann
On 08/19/2017 04:13 AM, kay Cee wrote:
> I made a python script that will update a Ubuntu Server every second and
> writes asuccess message  and date to a log file, but for some reason the
> file is not being written to.
> 
> Here is the Script:
> 
> #!/usr/bin/python3
> 
> import subprocess
> import time
> import datetime
> 
> class UpdateError(Exception):
> pass
> 
> def update():
> while True:
> try:
> update_log = open('update_log.txt', 'r+')
> time.sleep(1)
> subprocess.call(['apt-get', 'update', '-y'])
> date = datetime.datetime.now()
> update_log.write("System was updated sucessfully on {}\n".format
> (str(date)))
> subprocess.call(['reboot'])
> except UpdateError:
> print("Update Error!!!")
> update_log.close()
> 
> if __name__ == '__main__':
> update()

Hate to not just "answer the question", but what are you trying to
accomplish with this script?

You certainly don't want to call "apt-get update -y" in loop this fast.
Why are you then rebooting? (update doesn't change the system, only the
apt cache info)

Ubuntu has a way to do this stuff as a background task anyway.

For logging, you may want to actually use Python logging facilities.


All those said, the way you want to debug something like this is to run
a much more benign task through subprocess, before moving on to big (and
slow) tasks.

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