Re: [Tutor] Object creation query

2019-08-09 Thread bob gailer

On 8/9/2019 7:39 AM, Alan Gauld via Tutor wrote:

On 09/08/2019 09:54, mhysnm1...@gmail.com wrote:


updates and insertions. I have multiple tables with the same structure with
differe

I agree 100% with Peter and Alan's responses.

--
Bob Gailer

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


Re: [Tutor] instantiate and name a class from / with a string

2019-08-09 Thread bob gailer

On 8/9/2019 1:55 PM, ingo wrote:

With the available classes Root, Channel and SSE I build the following
(in CherryPy):

root = Root()
root.channel = Channel()

root.channel.weather = SSE('weather')
root.channel.energy = SSE('energy')
root.channel.mail = SSE('mail')
root.channel.rss = SSE('rss')
...

http://example.com/channel/weather/ will then become the emitter of the
weather event stream.

I'd like create the instances of SSE programmatically by pulling the
string 'weather', 'energy' etc. from a database.


Are you asking for help in obtaining a value from a database?

Or how to dynamically create instances assigned to root.channel attributes?

Assuming the latter:

name = # get from data base
setattr(root.channel, name, SSE(name))

--
Bob Gailer

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


Re: [Tutor] Difference between decorator and inheritance

2019-08-02 Thread bob gailer

And now for something completely different...

Decorators are not required to return a function!

I use them to create a dictionary that maps function names to the 
corresponding function object.


This is very useful when associating actions with user-entered commands. 
Example:


def collect(func=None, d={}):
    if not func: return d
    d[func.__name__] = func

@collect
def add(a,b):
    return a+b

# adds item to dictionary d (key = 'add', value = func)
# repeat for other user-command functions
# finally:
cmd_dict = collect() # returns the dictionary
cmd = input('enter a command>')
func = cmd_dict.get(cmd)

--
Bob Gailer

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


Re: [Tutor] Stylometry Help

2019-07-20 Thread Bob Gailer
On Jul 20, 2019 7:56 AM,  wrote:
>
> Hello together,
>
> I try to write a Python tool but after hours of trying , reading and
looking for help nothing an no one would help me. So this is my most
desperate call for help. I attached the project and my required files.

Unfortunately the tutor list does not forward attachments. If the files are
not too big just include them in the body of the email. Otherwise you'll
have to store them in the cloud and give us a link.

Be sure to reply all so we all get to see your problem.

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


Re: [Tutor] pointers or references to variables or sub-sets of variables query.

2019-07-08 Thread bob gailer

Data = [

   ['2019-01-19','Fred Flintstone',23],
['2019-02-01','Scooby doo', 99]
]

Warning 3: age is not a fundamental attribute; it is a computed value!

--
Bob Gailer

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


Re: [Tutor] [Python-Help] Writing hello world

2019-06-29 Thread Bob Gailer
On Jun 28, 2019 9:26 AM, "Erastus muriithi" 
wrote:
>
> Iam a student..iam interested in learning python,,I don't know how to
study this python.kindly help me how to go about it..Thankyou

First make sure you have python installed on your computer. If you need
help with that let us know what kind of computer and operating system you
are using.

At the python. Org website you will find links to tutorials. Try some of
these out.

Direct future emails to tutor@python.org.
Always reply all so a copy goes back to the list.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.7 Grids

2019-06-29 Thread Bob Gailer
On Jun 29, 2019 3:01 AM, "David Merrick"  wrote:
>
> Hi Looking for a way to use the determine the position of a card in a grid
> using the mouse click event in Python. Code is attached.

Unfortunately this list does not forward attachments. Either give us a link
to the code or even better if it's not terribly complicated paste it into
the reply. be sure to reply all so everyone on the tutor list will see your
reply.

> There are no viruses.

That's kind of like a Salesman saying "trust me".

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


Re: [Tutor] python

2019-06-25 Thread Bob Gailer
On Jun 25, 2019 8:52 AM, "Shaon Debnath"  wrote:
>
> I just wanted to know all about map() function in python.

See https://www.geeksforgeeks.org/python-map-function/.

If after reading that you still have questions please come back and ask
them.

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


Re: [Tutor] How to store scores of a race's players

2019-03-26 Thread Bob Gailer
Please do not use a mangled return email address. It causes us a lot of
pain when we fail to read your address to fix it and get the message
bounced back. The only reason I'm even bothering to resend it is because I
put a lot of work into it.:
> On
> Mar 26, 2019 6:55 AM, "^Bart"  wrote:
> >
> > Hello!
> >
> > I need to store scores of three players for more than a race, after
every race the user will read "Is the competition finished?", if the
competition if finished the user will see the winner who got higest score:
> >
> Thank you for reaching out to us for help as You Learn Python. A good
mailing list to use instead of the main python list is tutor@python.org.
I'm including that list in the reply addresses; please use that address in
the future and always reply all so a copy goes to that list.
>
> This looks like a homework assignment. Be advised we won't write code for
you but we will help you when you get stuck and provide some guidance. I'm
personally curious as to who wrote that specification, since it is not well
written. One of the questions that fails to address is what if two or more
players have the same high score?
>
> It's also a little hard to guide you since we don't know what you've
already learned. One of the fundamental concepts in computer programming is
that of a loop. Since the requirements indicate there will be more than one
race that requires a loop. The simplest python construction for a loop is a
while. Within that Loop you write the code once rather than rewriting it as
you have done. I hope that is enough to get you started. Please apply that
advice as best you can and come back with a revised program.
>
> > p1 = int (input ("Insert score of the first player: "))
> > p2 = int (input ("Insert score of the second player: "))
> > p3 = int (input ("Insert score of the third player: "))
> >
> > race = str (input ("Is the competition finished?"))
> >
> > totalp1 = 0
> > totalp2 = 0
> > totalp3 = 0
> >
> > winner = 0
> >
> > if p1 > p2 and p1 > p3:
> > winner = c1
> > elif p2 > p1 and p2 > p3:
> > winner = p2
> > else:
> > winner = p3
> >
> > if "yes" in race:
> > print("The winner is:",winner)
> > else:
> > p1 = int (input ("Insert score of the first player: "))
> > p2 = int (input ("Insert score of the second player: "))
> > p3 = int (input ("Insert score of the third player: "))
> >
> > race = str (input ("Is the competition finished?"))
> >
> > You read above just my toughts, is there someone who could help me to
understand how to solve it?
> >
> > Regards.
> > ^Bart
> > --
> > https://mail.python.org/mailman/listinfo/python-list
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to store scores of a race's players

2019-03-26 Thread Bob Gailer
On Mar 26, 2019 6:55 AM, "^Bart"  wrote:
>
> Hello!
>
> I need to store scores of three players for more than a race, after every
race the user will read "Is the competition finished?", if the competition
if finished the user will see the winner who got higest score:
>
Thank you for reaching out to us for help as You Learn Python. A good
mailing list to use instead of the main python list is tutor@python.org.
I'm including that list in the reply addresses; please use that address in
the future and always reply all so a copy goes to that list.

This looks like a homework assignment. Be advised we won't write code for
you but we will help you when you get stuck and provide some guidance. I'm
personally curious as to who wrote that specification, since it is not well
written. One of the questions that fails to address is what if two or more
players have the same high score?

It's also a little hard to guide you since we don't know what you've
already learned. One of the fundamental concepts in computer programming is
that of a loop. Since the requirements indicate there will be more than one
race that requires a loop. The simplest python construction for a loop is a
while. Within that Loop you write the code once rather than rewriting it as
you have done. I hope that is enough to get you started. Please apply that
advice as best you can and come back with a revised program.

> p1 = int (input ("Insert score of the first player: "))
> p2 = int (input ("Insert score of the second player: "))
> p3 = int (input ("Insert score of the third player: "))
>
> race = str (input ("Is the competition finished?"))
>
> totalp1 = 0
> totalp2 = 0
> totalp3 = 0
>
> winner = 0
>
> if p1 > p2 and p1 > p3:
> winner = c1
> elif p2 > p1 and p2 > p3:
> winner = p2
> else:
> winner = p3
>
> if "yes" in race:
> print("The winner is:",winner)
> else:
> p1 = int (input ("Insert score of the first player: "))
> p2 = int (input ("Insert score of the second player: "))
> p3 = int (input ("Insert score of the third player: "))
>
> race = str (input ("Is the competition finished?"))
>
> You read above just my toughts, is there someone who could help me to
understand how to solve it?
>
> Regards.
> ^Bart
> --
> https://mail.python.org/mailman/listinfo/python-list
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create a structure from a Log file

2019-03-11 Thread Bob Gailer
On Mar 11, 2019 2:53 AM, "Asad"  wrote:
>
> Hi All ,
>
>I think this format would be easy in a row and table format
>
> Date
> Time
> Message
> 1/21/2019
> 10:13:14.237 CET
> Method Entry. workDir=/tmp frameworkHome=/u01/app/oracle/product/
12.2.0.1/dbhome_1

For me the easiest would be to create an HTML page and display it in the
browser. You could start out with the table tag and then write each segment
of the log file into the proper column and end with a closing table tag.

I hope that's sufficient cuz I'm dictating this into my cell phone and
don't particularly want to try to actually dictate HTML or type it on a
cell phone keyboard.

Excel is also a good idea and there are several python modules dedicated to
creating Excel files. A Google search would reveal those.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create a structure from a Log file

2019-03-10 Thread Bob Gailer
Thank you for showing us a sample of the log file. That is half the battle.
Would you now reformat a couple of the lines so that we can see how you'd
like to see them.

It also may be the case that the advice given by others will be sufficient
to guide you
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create a structure from a Log file

2019-03-09 Thread Bob Gailer
Would you give us more information? What is an example of a log file? How
would you like to see it presented? The more information you give us the
easier it is for us to help.

On Mar 9, 2019 11:20 AM, "Asad"  wrote:

Hi All ,

   I would like to know , how can I approach this problem to create
a easy structure from the logfile using python so I can review the logfiles
quite efficiently . Please share suggestion tip or already written codes.



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


Re: [Tutor] Python

2018-12-20 Thread Bob Gailer
On Dec 20, 2018 12:17 PM, "Mary Sauerland"  wrote:
>
> Hi,
>
> I want to get rid of words that are less than three characters but I keep
getting errors. I tried multiple ways but keep getting errors.

Hi Mary welcome to the tutor list. We love to help. We are a few
volunteers. It is very difficult for us to be mind readers. So please give
us more information. Especially what the error is you are getting. I
presume it is what we call a trace back. It is important that you copy the
entire traceback and paste it into the email. It will also be very helpful
if you gave us a sample of the two text files and the output You're
Expecting.

>
> Here is my code:
>
> f1_name = "/Users/marysauerland/Documents/file1.txt"
> #the opinions
> f2_name = "/Users/marysauerland/Documents/file2.txt"
> #the constitution
>
>
> def read_words(words_file):
> return [word.upper() for line in open(words_file, 'r') for word in
line.split()]
>
>
> read_words(f1_name)
> #performs the function on the file
> set1 = set(read_words(f1_name))
> #makes each word into a set and removes duplicate words
> read_words(f2_name)
> set2 = set(read_words(f2_name))
>
> count_same_words = 0
>
> for word in set1:
> if word in set2:
> count_same_words += 1
> #comparing the set1 (set of unique words in the opinions) with set2 (set
of unique words in the constitution) and adding 1 for each matching word
found which is just counting the words
> print(count_same_words)
>
>
> Best,
>
> Mary
> ___
> 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] Extract URL

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 2:01 PM, "Sammy Lee"  wrote:
>
> I need help on the problem stated below.
>
>
> Given a URL, open the webpage and return the first anchor link url (a
href).
>
>
> def extract_url_link(url):

Same comments as my other two emails.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python function

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 1:55 PM, "Sammy Lee"  wrote:
>
> How do I create a python function that opens a CSV file and determines
how many columns
> of data are in the file? The CSV files have been randomly generated from
https://www.mockaroo.com/
>
> def csv_column_count(openfile):

Same comments as I made in response to your other question. What part of
this do you need help with? do need to know how to read a file? do you need
to understand what a CSV file is? do you need to know how to parse a
character string?

The more specific you are the easier it is for us to help you.

Have you ever written a Python program? What has your course taught you so
far? Do you know how to write pseudocode?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Long Lines techniques

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 1:51 PM, "Avi Gross"  wrote:
>
> Simple question:

Avi: when I see an email from you I tend to ignore it because it always
seems to lead to something that is long, time consuming and complex. Would
you consider finding ways to make your questions or comments a lot briefer?

I will be more inclined to read them if they are briefer.

You have correctly determined the conditions that will lead to continuation
lines without backslash. I think we tend to use whatever is convenient.

In your example of a list comprehension over multiple lines there is no
indentation. There is just a lot of white space. You might look at it this
way: the compiler sees a left bracket with no corresponding right bracket
on that line. So it assumes that there's more to the statement on the next
line, it ignores the newline and just continues. Indentation is only
significant if it starts at the beginning of a statement.

Hope this helps

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


Re: [Tutor] Open webpage and save CSV

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 1:51 PM, "Sammy Lee"  wrote:
>
> I need help on the problem below,

Could you be more specific? What kind of help do you need? Have you made
any attempt to write a program?

We are happy to help but we're not going to do all the work for you. So
tell us what you do know about the various aspects of this problem.

My personal guess is that this is a homework assignment. If that's the case
the class should have given you some of the information (ideally all the
information) you need to solve the problem.

Also please tell us what operating system you're using and what version of
python.

You will need the services of the urllib. request module to get the
contents of a web page.

So start with that.

> Given a URL, open the webpage and save the CSV to a given file path.
>
>
> def save_url_to_csv_file(url, savefile):

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


Re: [Tutor] I need help with my project

2018-11-28 Thread Bob Gailer
On Nov 28, 2018 3:43 AM, "Treyton Hendrix" <2hendri...@stu.bps-ok.org>
wrote:
>
> If the user selected a sandwich, french fries, and a beverage, reduce the
> total cost of the order by $1.00.
>
> This is what I have to do and I don't know where to start.

You start by learning how to ask effective questions. Example:

I am taking python 101 at Fubar University. I have been given the following
assignment:

Here you tell us the entire assignment not just one sentence from it.

Then you show us whatever attempt you have made to solve the problem. Have
you written any Python program? Show us the program. Tell us where you are
stuck.

We really like to help but we do not have any crystal balls to look into.
Help us understand your situation fully.

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


Re: [Tutor] seeking beginners tutorial for async

2018-11-19 Thread Bob Gailer
> Can you be more specific what you're looking for?

For starters a minimal executable  program that uses the async keyword.

On the JavaScript side this is trivial and easily understood.

I did find in the python documentation a hello world program that uses
async IO. It helped me understand how to build an event Loop , start soon,
start later stop Loop, run forever and run until complete. That was very
helpful. But it did not introduce async.

I'd like to see  the trivial program built up step-by-step adding one new
feature at a time so that I can understand exactly what that feature does.

I am talking about python 3.6 and 3.7.

Thank you for asking for the clarification, I hope this helps.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] seeking beginners tutorial for async

2018-11-18 Thread bob gailer

I have yet to find a tutorial that helps me understand and apply async!

The ones I have found are either incomplete, or they wrap some other 
service, or they are immediately so complex that I have no hope of 
understanding them.


I did find a useful javascript tutorial at 
https://javascript.info/promise-basics, but trying to map it to python 
is very frustrating.


The python docs also do not help.

Can you point me to any resources that are actually useful to a beginner?

Bob Gailer

guru of many languages including Python ( up till now!)

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


Re: [Tutor] how to print lines which contain matching words or strings

2018-11-18 Thread Bob Gailer
On Nov 18, 2018 1:19 PM, "Bob Gailer"  wrote:
>
> On Nov 18, 2018 12:14 PM, "Asad"  wrote:
> >
> > Hi All ,
> >
> >I have a set of words and strings :
> >
> > like :
> >
> > p = [A ,"B is good" ,123456 , "C "]
> >
> > I have a file in which I need to print only the lines which matches the
> > pattern in p
> >
> > thanks,

Terminology is very important. You say set then you show us a list.

You say words and strings, but your list contains a python identifier and a
number in addition to Strings.

You say pattern but don't Define what you mean by pattern. I could not
begin to guess what your definition of pattern is.

We also do not know what the term word means to you. You may say that is
obvious but it is not. So tell us your meaning of word.

To make the question meaningful I would suggest you show us sample of the
file indicating lines that meet the pattern and lines that don't.

Please realize that we are not here to write code for you, rather we like
to help you when we see you put in some effort. So I suggest you write a
Python program that attempts to do what you want, then tell us where the
program isn't doing what you want or where you are stuck will try to help.

Please respond in some way so that we know you have heard us.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to print lines which contain matching words or strings

2018-11-18 Thread Bob Gailer
On Nov 18, 2018 12:14 PM, "Asad"  wrote:
>
> Hi All ,
>
>I have a set of words and strings :
>
> like :
>
> p = [A ,"B is good" ,123456 , "C "]
>
> I have a file in which I need to print only the lines which matches the
> pattern in p
>
> thanks,

you are welcome, but I'm not sure what you're thanking us for. I don't see
any kind of request in your email.

There are various resources on how to ask effective questions. You might
try Googling that topic.

I have more that I will say later.

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


Re: [Tutor] Require Python assistance

2018-11-09 Thread Bob Gailer
On Nov 9, 2018 12:34 PM, "TCY via Tutor"  wrote:
>
>
>
>
> Dear
> May I know how to solve the cryptography with Python programming
language as below -
> (1) Implement Elgamal Method(2) Implement Elliptic Curve Cryptography
method(3) Implement Rabin Method(4) Implement RSA Method
> Find (a) Prime test (b) Inverse function

This list does not send attachments. If the file is not large just send it
as part of the email body.

As you can see the text above came thru as 1 long line. I presume  when you
sent it it looked like 4 lines. If that is the case you need to send the
email as plain text rather than some fancy formatted way.

> Please help me by provide your advice

Learn how to ask questions that are more precise and specific. "Solve the
cryptography" doesn't tell me anything. The more clearly you state your
objectives the easier it becomes for us to help you.

Google is your friend here. For example try searching Google for "Elliptic
Curve Cryptography python"
and suggestion so that I can improve my computing skills (please see the
attached file)

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


Re: [Tutor] Request for help with code

2018-11-06 Thread Bob Gailer
On Nov 6, 2018 4:51 PM, "Joseph Gulizia"  wrote:
>
> I'm using the bookazine  "The Python Book" First Edition on pages 13-14 it
> gives the code (listed further below).
>
> It asks for user to state a given number of integers (for example
4)...then
> user enters integers.  It doesn't stop seeking input after the number
> requested thereby creating an infinite loop.
>
> -
> CODE
> -
>
> # Python Book Page_13.py
> # Joe G.
>
> # several comment lines explain the code below it.
> # Re-typing is good practice
>
> # We're going to write a program that will ask the user to input an
> arbitrary
> # number of intergers, store them in a collection, and then demonstrate
how
> the
> # collection would be used in various control structures.
>
> # Used for the sys.exit function
> import sys
> # Requests number of intergers
> target_int=raw_input("How many intergers?")
> # By now, the variable target_int contains a string representtion of
> # whatever the user typed.  We need to try and convert that to an interger
> but
> # be ready to # deal with the error if it's not.  Otherwise the program
will
> # crash
> # Begin the error check
> try:
> target_int=int(target_int)
> except ValueError:
> sys.exit("You must enter an interger")
> # creates a collection (list) called ints
> ints=list()
> # keeps track of number of intergers
> count=0
> # Keep asking for an interger until we have the required number
> while count new_int=raw_input("Please enter interger{0}:".format(count+1))
> isint=False
> try:
> new_int=int(new_int)
> except:
> print("You must enter an interger")
> # Only carry on if we have an interger.  If not, we'll loop again
> # Notice below I use == which is different from =.  The single equals sign
> is an
> # assignment operator whereas the double equals sign is a comparison
> operator. I would
> # call it a married eguals signbut whenever single is mentioned I have
> to mention marriage.
>
> if isint==True:
> # Add the interger to the collection
> ints.append(new_int)
> # Increment the count by 1
> count+=1
> # print statement ("using a for loop")
> print("Using a for loop")
> for value in ints:
> print(str(value))
> # Or with a while loop:
> print("Using a while loop")
> # We already have the total above, but knowing the len function is very
> # useful.
> total = len(ints)
> count = 0
> while count < total:
>print(str(ints[count]))
>count +=1
>
> count = 0
> while count < total:
> print(str(ints[count]))
> count += 1
>
> ---
> END OF CODE
> ---
> Sample output:
>
> How many integers?3
> Please enter integer1:1
> Please enter integer1:2
> Please enter integer1:3
> Please enter integer1:a
> You must enter an integer
> Please enter integer1:4
> Please enter integer1:5
> Please enter integer1:6
> Please enter integer1:b
> You must enter an integer
> Please enter integer1:
> (Keeps Looping)
>
> Thanks in advance

Your code came through with all of the indentation removed. Please be sure
to send plain text. We could guess at the indentation but we might get it
wrong.

With the indentation corrected the code you supplied does not agree with
the execution. Note the difference between integer and interger.

You also did not make any request. Please in the future tell us what you
want from us.

The fact that the program keeps asking for integer 1 suggest that count is
not being incremented. This would also explain why the loop never ends.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2018-10-27 Thread Bob Gailer
On Oct 27, 2018 7:48 AM, "Jesse Stockman"  wrote:
>
> Hi there
>
> I need to draw a patten with turtle in python 3.7 but I cant get it to
work here are the specs of the pattern and my code so far can you please
help

Thank you for asking for help. It would help us if you were more specific.
"Can't get it to work" doesn't tell us much.

Does the program run or do you get an error?

If you get an error, also known as a traceback, copy the entire traceback
and paste it into your reply.

Otherwise show us your input and output. Tell us where it differs from what
you expected. Again use copy and paste to show your results.
>
> • Specifications of the pattern o The radius of the three heads is 10.
> o The length of legs is 30. o The length of the sizes of the two
triangles (the body of runner-up and third-place) is 40. They are all
equal-size triangles. The winner’s body is a 40x40 square. o The width of
the three blocks of the podium is 60. The heights are 90, 60, and 40
respectively.
>
> And my code so far
>
> from turtle import *
>
> x = 0
> y = 0
> radius = 0
> x1 = 0
> x2 = 0
> y1 = 0
> y2 = 0
> color = 0
> width = 0
> hight =0
>
>
>
> def main():
> speed(0)
> pensize(3)
> pencolor("black")
>
> winner_color = "red"
> second_color = "orange"
> third_color = "purple"
> draw_podium(winner_color, second_color, third_color)
> darw_third(third_color)
> draw_winner(winner_color)
> draw_second(second_color)
>
> def move_to(x, y):
> x = int(input("input X coordinate: "))
> y = int(input("input y coordinate: "))
> penup()
> goto(x, y)
> pendown()
>
> def draw_head(x, y, radius):
> radius = int(input("input radius: "))
> move_to(x, y)
> circle(radius)
>
> def draw_line(x1, y1, x2, y2):
> x1 = int(input("line start X: "))
> y1 = int(input("line start Y: "))
> x2 = int(input("line end X: "))
> y2 = int(input("line end Y: "))
> penup()
> goto(x1,y1)
> pendown()
> goto(x2,y2)
>
> def draw_block(x, y, hight, width, color):
> move_to(x, y)
> hight = int(input("input hight: "))
> width = int(input("input width: "))
> color(winner_color)
> begin_fill()
> forward(width)
> left(90)
> forward(hight)
> left(90)
> forward(width)
> left(90)
> forward(hight)
> end_fill()
>
>
> main()
> draw_block(x, y, hight, width, color)
>
>
> exitonclick()
>
>
> please help me
> thank you
> kind regards
> Tarantulam
>
>
> 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] Python Help

2018-10-26 Thread Bob Gailer
On Oct 26, 2018 1:20 PM, "Adam Eyring"  wrote:
>
> Try this cleaned up version with colons in the right places, dollar signs
removed, and other corrections:

Does it do what you want?

> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))
> party = beefmeals + shitmeals
> print("Total meals", party)
> a = 0
> b = 0
> c = 0

There is no need for three variables here. You only need one to represent
room cost. If you make that change then you will also not need to
initialize the room cost variable. Makes the code simpler to maintain and
read and understand.

> if party <= 50:
>
> a=75
> print("Room cost $75")

If you use one variable for room cost then you can use just one print just
above the room tax line.

> elif party <= 150:
>
> b=150
> print("Room cost $150")
> else:
> c=250
> print("Room cost $250")
> roomtax = party * 0.065
> print("Room tx", roomtax)
> print("Beef Meals", beefmeals)
> beef = (beefmeals * 15.95)
> print("Beef cost", beef)
> print("Vegan Meals", shitmeals)
> shit = (shitmeals * 10.95)
> print("Vegan cost", shit)
> cost=(beef + shit)
> grat= cost * 0.18
> print("Gratuity", grat)
> GT = print("Grand total", grat + beef + shit + a + b + c)

The print function always returns None. Therefore the effect of this
statement is to assign None to GT. Also note that you don't use GT later on.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help

2018-10-26 Thread Bob Gailer
On Oct 26, 2018 6:11 AM, "Ben Placella"  wrote:
>
> I need to write code that runs a  cost calculating program with many
> different variables and I honestly don't understand it

Could you be more specific? What exactly don't you understand, or even
better what do you understand?

my code is:

How could you have written so much code without understanding it?

> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))
> party=beefmeals+shitmeals
> print(party)
> if party<=50

Something is missing from that last statement. Can you tell what it is? Do
you know how to find out? Hint use help.

Hint 2 it is also missing from the elif and else statements.

> a=75
> print("Room cost $75")
> elif party <=150
> b=150
> print("Room cost $150")
> else
> c=250
> print("Room cost $250")
> roomtax=party*0.065
> print(roomtax)
> print("Beef Meals", beefmeals)
> $beef=(beefmeals*15.95)
> print($beef)
> print("Beef cost", $$beef)
> print("Vegan Meals", shitmeals)
> $shit=(shitmeals*10.95)
> print($shit)
> cost=($beef+$shit)
> grat=cost*0.18)
> print(grat)
> GT=(grat+$beef+$shit+(a,b,c))

There is a convention in Python that and all uppercase name is a constant.
This is not a requirement.

> print(GT)
>
> This is what the output is supposed to be:

I don't see any output here. Alan''s responses may help you figure that out.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

More comments on code:
 guess = raw_input("[pod #]> ")
    if int(guess) != good_pod:
If user enters something that will not convert to integer an exception 
will be raised. For example

>>> int('a')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'a'

Either use try - except
- or
    good_pod = str(randint(1,5))
    guess = raw_input("[pod #]> ")
    if guess != good_pod:
- or if you import choice from random
    good_pod = choice('12345')

Migrating to a database (separating data from logic). Why?
- it keeps the code simple.
- makes adding / editing scenes easier.

Given a database (game.db) with 2 tables:
            table            columns
    scene_entry        scene, text, prompt
    scene_action       scene, action, text, next_scene

Example:
 CentralCorridor, The Gothons of Planet Percal #25 have invaded 
..., Do you shoot!, dodge!, or tell a joke?
 CentralCorridor, shoot!, Quick on the draw you yank out your 
, Death
 CentralCorridor, dodge!, Like a world class boxer you dodge 
, Death
 CentralCorridor, tell a joke!, Lucky for you they made 
you,, Laser_weapon_armory


The generic structure of a game program:
    next_scene = 'CentralCorridor'
    while next_scene != 'Finished':
        get text, prompt from scene_entry
        print entry text
        prompt user for action
        get text, next_scene from scene_action
        print text

A simple python game program utilizing the game database follows. You 
would first create c:/games/game.db
using a tool like SQLite Studio, or request a copy from me. It is up to 
you to fill in the rest of the various table rows.
What's missing? Code to handle the code and good_pod guesses. That will 
come later.


-- program --
import sqlite3 as sq

def sel(cols, rest, vals=(,)):
    # construct, execute a sql select statement from the arguments
    # get and return one row (there should be at most one)
    sql = "select " + cols + " from " + rest + ";"
    curs = conn.execute(sql, vals)
    x = curs.fetchone()
    if x: return x
    raise ValueError(sql, vals)

def game(next_scene):
    while next_scene != 'finished':
    text, prompt = sel("text, prompt", "scene_entry where scene = 
?", (next_scene,))

    print(text)
    action = input(prompt + '>') # tell a joke!
    text, next_scene = sel("text, next_scene", "scene_action where 
scene = ? and action= ?", (next_scene, action))

    print(text)

conn = sq.connect("c:/games/game.db")
game('CentralCorridor')
-- end program --


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


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

On 10/14/2018 1:42 PM, Mats Wichmann wrote:

Hint here: don't use 'map' as your own variable name, since it's a
built-in function.
Absolutely, I am always warning others about this gotcha. In this case 
map is local to add_to_map so it does not affect then global namespace.


The reason I used it here was because the OP was using map (actually 
Map). Duh!


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


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

More comments:

 User Friendly? 
I hope this game is not intended for actual use. No one will be able to 
guess the correct actions in a reasonable time. or 3 digit random code 
given 10 tries for any one code. I for one would give up pretty quickly.


The original colossal cave game is an excellent example of a 
user-friendly text adventure game. If you are using a Windows computer 
you can get a version from the Microsoft Store


It
- gives explicit directions
- keeps responses to a few words most chosen from a limited list or 
names of visible objects.


 Python coding "trick"1  
when I build a map I omit the () after the class e.g. 'death' = Death, 
... and apply them to the item retrieved from the map.


use a decorator to build the map dictionary:

# the decorator function:
def add_to_map(cls, map={}): # map is initialized to a {} when function 
is "compiled"

    if cls:
        map[cls.__name__] = cls # add entry to dictionary
        return cls
    else: return map

# apply decorator to class definitions
# this will add 'Death': 
@add_to_map
class Death(Scene):
    class_definition

 # ditto for all other classes based on Scene - then

class Map:
    scenes  = add_to_map() # note when map is called with no arguments 
it returns the dictionary


 Python coding "trick" 2 
instead of:     print(Death.quips[randint(0, len(self.quips)-1)])
try:                 print(random.choice(Death.quips)

 Python coding "trick" 3 
action = raw_input('>').title() # to make user input agree with class names

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


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

On 10/13/2018 4:25 AM, Mariam Haji wrote:
...
Your problem intrigued me enough to spend some time "fixing" your 
program so it will compile with no errors and run at least the initial 
case where I entered "shoot!"


Here are the problems I found: (line numbers refer to your original code)
- spelling error  return 'laser_weapon_armoury' - fixed
- line 122 there is no if preceding the elif - I added one
- line 160 returns 'finished'. There is no corresponding entry in Map.scenes
   - I added one and a corresponding class Finished.
- the logic for allowing 10 guesses of the code is flawed. It only 
allows 2 guesses.

  I will leave it up to you to figure out why.

In addition I
- used """ for all multi  line prints; a personal preference - it makes 
entry and reading easier.

- updated code so it will run under python 3. This involves:
  - changing print statements to print function calls
  - assigning input to raw_input for version 3
- added raise to Map.next_scene to handle undefined scenes

Try it out.

> how do I create a keyword to exit the game mid way?

You don't create keywords. To support mid-game exiting I added an abort 
method to Finished. Use:

Finished.abort('reason')

-- program --
from sys import exit, version
from random import randint
if versison[0] == '3':
    raw_input = input

class Scene(object):
    def enter(self):
    print("This scene is not yet configured. Subclass it and 
implement enter().")

    exit(1)

class Engine(object):

    def __init__(self, scene_map):
    self.scene_map = scene_map

    def play(self):
    current_scene = self.scene_map.opening_scene()
    while True:
    print("\n")
    next_scene_name = current_scene.enter()
    current_scene = self.scene_map.next_scene(next_scene_name)

class Death(Scene):

    quips = [
"You died. You Kinda suck at this.",
"Your mum would be proud if she were smarter.",
"Such a looser.",
"I have a small puppy that's better at this."
]

    def enter(self):
    print(Death.quips[randint(0, len(self.quips)-1)])
    exit(1)

class CentralCorridor(Scene):

    def enter(self):
    print("""The Gothons of Planet Percal #25 have invaded your 
ship and destroyed

Your entire crew, you are the only surviving memeber and your last
Mission is to get the neutron destruct a bomb from the weapons Armory
Put it in the bridge and blow the ship up after getting into an
escape pod

You're running down the central corridor to the Weapons Armory when
a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clow costume
flowing around his hate filled body. He's blocking the door to the
Armoury and about to pull a weapon to blast you.
Do you shoot!, dodge!, or tell a joke? enter below.""")
    action = raw_input("> ")
    if action == "shoot!":
    print("""Quick on the draw you yank out your blaster and 
fire it at the Gothon.

His clown costume is flowing and moving around his body, which throws
off your aim. Your laser hits his costume but misses him entirely. This
completely ruins his brand new costume his mother bought him, which
makes him fly into a rage and blast ou repeatedly in the face until
you are dead. Then he eats you""")
    return 'death'
    elif action == "dodge!":
    print("""Like a world class boxer you dodge, weave, slip 
and slide right

as the Gothon's blaster cranks a laser past your head
In the middle of your artful dodge your foot slips and you
bang your head on the metal wall and you pass out
You wake up shortly after, only to die as the Gothon stomps on
your head and eats you""")
    return 'death'
    elif action == "tell a joke":
    print("""Lucky for you they made you learn Gothon insults 
in the academy

you tell the one Gothon joke you know
Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq 
gur ubhfr.

The Gothon stops, tries not to laugh, he busts out laughing and can't move.
While he is laughing you run up and shoot him square in the head
putting him down, then jump through the Weapon Armory door.""")
    return 'laser_weapon_armory'
    else:
    print("DOES NOT COMPUTE!")
    return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
    print("""You do a drive roll into the weapon Armory, crouch and 
scan the room

for more Gothons that might be hiding. It's dead quiet, too quiet
You stand up and run to the far side of the room and find the
neutron bomb in it's container. There's a keypad lock on the box
Wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits""")
    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    guess = raw_input("[keypad]> ")
    guesses = 0
    while guess != code and guesses < 10:
    print("BZZZEE!")
    guesses += 1
    guess = raw_input("[keypad]> ")
    if guess == 

Re: [Tutor] python game error

2018-10-13 Thread Bob Gailer
suggestions:
1-Use triple-quoted strings:
  print """take the
short-cut!""'

2 - make the program much simpler to start with. The usual approach to
developing programs like this is to start simple get the simple things
working right then add more complicated scene descriptions.

Even better: separate data from logic. Create a sqlite database in which
you store the information about the various scenes. Then write a program
that does nothing but access the various database elements. This will
result in much much easier to read and maintain code, and much much easier
to read and maintain the description of the scenes. I realize this may
sound like a big chunk but it is well worth the effort to learn how to do
it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python programming help!

2018-09-23 Thread Bob Gailer
On Sep 23, 2018 3:33 AM, "V E G E T A L" 
wrote:
>
> Hello folks! So, I'm pretty much a noob still experimenting with basic
> commands. I wanted to make a code that checks if the value of one variable
> is less, equal or greater than the other. Pretty simple right? But then,

> this problem emerged.

What problem? I don't see any problem here. If you provided an attachment
this email list does not forward attachments.

The proper way is to copy and paste directly into the body of the email.

If you did not attempt to show us the problem, why? You certainly can't
expect us to read your mind.

I would really love some help, since I'm stuck and
> can't figure out what I've done wrong.
>
> PS: I'm using Anaconda and JupyterNotebook.
> ___
> 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 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] I have a problem with def

2018-02-23 Thread Bob Gailer
On Feb 23, 2018 3:58 AM, "David Bauer"  wrote:
>
> it doesn't work, you are suppsed to declare a function as def func() and
it
> comes back as:
>
> File "", line 1
> def func()
>  ^
> SyntaxError: invalid syntax
>
> that is not expected I would also expect def to turn red because it is a
> keyword in Python, but that doesn't happen

That is an effect of syntax coloring. That in turn depends on what you're
using to enter your program. Please tell us what you are using to enter
your program and we can help with that.

anyone else having this
> problem Anyone know what I should do or look for
> ___
> 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] Data Structures printing and Python Package creation

2018-02-03 Thread Bob Gailer
On Feb 3, 2018 2:09 PM, "Daniel Bosah"  wrote:
>
> I'm in a research group for school, and my first task is to learn how to
> make a Python package and to learn how to print out all types of data
> structures. Are there resources I can be pointed to to help me out.

https://python-packaging.readthedocs.io/en/latest/

I got that using Google search. Hint hint?

All types is a bit vague. I suggest you take one type at a time.

Very often it is sufficient to print the object using, as you might guess,
the print function.

Also Google python prettyprint and python formatting.

Let us know how it goes and please ask more questions.
___
> 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] Writing to a file

2018-01-19 Thread Bob Gailer
=

On Jan 18, 2018 5:45 PM, "Devansh Rastogi"  wrote:
>
> Hello,
>
> I'm new to python and programming as
>
> from collections import Counter
> import json
>
I don't see any value for having a class. All you need are functions and
global variables

> class Files:
> def __init__(self, filename):

I don't see any need for a function or"with". Just write file_input_string
= open(filename, 'r', encoding='utf-16').read().replace('\n', ' ')


> with open(filename, 'r', encoding='utf-16') as file_input:
> self.file_input_string = file_input.read().replace('\n', ' ')
>
You are assuming that all words are separated by blanks which is rarely the
case in natural language.

> def num_of_words(self):
> """ Return number of words in the file"""
> return str(len(self.file_input_string.split()))
>
Several comments on Counting:


Your program is creating lists of ones. Rather than counting them all you
need to do is take the length of each list.. e;g;: lowercase_letters =
len(1 for c in self.file_input_string if c.islower())

However there is a much better way to do the counting: translate the text
using the string translate method into various characters that identify the
class of each letter in the file. Then count the occurrences of each of
those characters. Example: counting Upper Lower, Nunber, and punctuation
Single, Double stroke):

txt=  "THIS is 123 ,./ :*(" # input file text

transtable =
str.maketrans("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
,./:*(",
  "L"*26 + "U"*26 + "N"*10 + "S"*4 + "D"*3) # maps input characters to
corresponding class characters

xlation = txt.translate(transtable) # 'SLLSNNNSDDD' # creates
string of class characters

counts =dict(Counter(xlation) # {'S': 7, 'U': 4, 'N': 3, 'L': 2, 'D': 3}

> def num_of_keystrokes(self):
> """ Total number of keystrokes
> # abcde.. = 1 stroke
> # ABCDE.. = 2 strokes
> # '.,-/;[]=\ = 1 stroke
> # !@#$%^&*()_+|}{":?>< = 2 strokes """
>
> lowercase_letters = sum(1 for c in self.file_input_string if
> c.islower())
> uppercase_letters = sum(2 for c in self.file_input_string if
> c.isupper())
> one_keystroke_punc = ".,-=[]\;'/ "  # space included
> puncuation_one = sum(1 for c in self.file_input_string if c in
> one_keystroke_punc)
> two_keystroke_punc = '!@#$%^&*()_+|}{":?><'
> puncuation_two = sum(2 for c in self.file_input_string if c in
> two_keystroke_punc)
>
> return str(lowercase_letters + uppercase_letters +
> puncuation_one + puncuation_two)
>
> def num_of_char(self):
> """ Return number of characters in the string without spaces"""
> return str(len(self.file_input_string) -
> self.file_input_string.count(" "))
>
> def frequency_of_char(self):
> """ Frequency of characters in the file """
> count = Counter(self.file_input_string)

There is no need to apply dict to count. Counters have an items method.

> dict_count = dict(count)
> print("{:<12} {:<10}".format('Character', 'Frequency'))
> for k, v in dict_count.items():
> print("{:<12} {:<10}".format(k, v))
>
> def frequency_of_words(self):
> """ Frequency of words in the file"""
> # word_count = Counter()
> # for word in self.file_input_string.replace(' ', '\n'): ###
> macht wider char. sollte fuer line funktioniern
> # word_count.update(word)
> # print("{:<15} {:15}".format("Word", "Frequency"))
> # for k, v in word_count.items():
> # print("{:<15} {:<15}".format(k, v))
>
> word_list = self.file_input_string.split()
> word_frequecy = [word_list.count(w) for w in word_list]  ##
> funktioniert mit string.count!!
> word_frequecy_dict = dict(zip(word_list, word_frequecy))
> print("{:<15} {:15}".format("Word", "Frequency"))
> for k, v in word_frequecy_dict.items():
> print("{:<15} {:<15}".format(k, v))
>
> def average_len_of_words(self):
> """ calculate the averge length of the words"""
> word_list = self.file_input_string.split()
> average = sum(len(word) for word in word_list) / len(word_list)
> return str(average)
>
> def write_to_file(self, data):
> """ collect all data for Morgen_Kinder.txt in a file"""
> with open('data.json', 'w') as f:
> json.dump(data, f, sort_keys=True, indent=4)
>
> #test
> x = Files('Morgen_Kinder.txt')
> a = Files.num_of_char(x)
> Files.write_to_file(x,a)
> print(a)
> b = Files.num_of_words(x)
> Files.write_to_file(x,b)
> print(b)
> c = Files.frequency_of_char(x)
> Files.write_to_file(x,c)
> d = Files.frequency_of_words(x)
> Files.write_to_file(x,d)
> e = Files.average_len_of_words(x)
> Files.write_to_file(x,e)
> print(e)
> g = Files.num_of_keystrokes(x)
> Files.write_to_file(x,g)
> print(g)
> 

Re: [Tutor] application development

2017-12-09 Thread bob gailer

On 12/9/2017 2:09 PM, Ayanlade Timilehin via Tutor wrote:

Goodday, I'm a Windows user and I am interested in developing android 
applications but I can't find any tutorial resource online. Please how can you 
help.
Google "android development tutorial". If you can't find what you are 
looking for there, then please refine your question and ask again.


Since this is a Python list, perhaps you want to use Python in the 
development process; in that case Google "android development python". 
Note references to "Kivy". If you can't find what you are looking for 
there, then please refine your question and ask again.


The more explicit your question the more likely you are to get explicit 
answers. Saying "I can't find any tutorial resource online" suggests you 
don't know how to Google!


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


Re: [Tutor] Counting iterations of a function

2017-11-30 Thread Bob Gailer
On Nov 30, 2017 12:56 PM, "Michael Dowell" 
wrote:
>
> Hello, I'm trying to code a magic 8-ball program and it needs to include a
> counter for the number of questions asked. I'm having a hard time
> implementing a count, and need a little help. I had tried to implement it
> in the main() function, but that (naturally) led it to only counting '1'
> for each question, for each question asked. Is there a way to count how
> many times a give line of code is executed? For instance, every time the
> oracle() function is run, a counter goes up. Thanks for any help.
>
> Program:
>
>
> #Michael Dowell
> #11-26-27
> #Capstone: Magic 8-ball
>
> #import modules
> import random
> import turtle
>
>
> #Give welcome message
> def print1():
>
> print("Hello!")
> print("Thank you for using this Magic 8-Ball Simulator.")
> print("We understand that you have a choice in magic 8-ball
> experiences,\n and that you have no choice in viewing mine.")
> print("Thank you")
>
> #Define main function
>
> def main():
> #Set local variables
> count=0  #Tried to intergrate count into main() function
> query=''
>
> #Get question
> query=str(input("Please type in your question(press 'Enter' to
exit):"))
>
> while query!='':
> oracle()
> main()
Your problem is here. Instead of calling main recursively you should move
the while to the top of the main function preceded by assigning something
to query. Also get rid of the break statement
> break

>
> #Determine fate (the error "Variable 'fate' is not defined" was quite
> existential)
> def oracle():
>
> fateList=["It is certain","It is decidedly so","Without a doubt","Yes
–
> definitely","You may rely on it","As I see it, yes","Most likely","Outlook
> is good","Yes","Signs point to yes","Reply hazy, try again","Ask again
> later","Better not tell you now","Cannot predict now","Concentrate and ask
> again","Don’t count on it","My reply is no","My sources say no","Outlook
> not so good","Very doubtful"]
> fate=fateList[random.randint(0,len(fateList))-1]
>
> #Draw 8 ball/Refresh fate
> turtle.pensize(10)
> turtle.speed(7)
> turtle.hideturtle()
> turtle.goto(0,-200)
> turtle.fillcolor('black')
> turtle.begin_fill()
> turtle.circle(250)
> turtle.end_fill()
> turtle.goto(0,-50)
> turtle.fillcolor('blue')
> turtle.begin_fill()
> turtle.circle(150)
> turtle.end_fill()
> turtle.fillcolor('white')
> turtle.begin_fill()
> turtle.pendown()
> turtle.goto(130,150)
> turtle.goto(-130,150)
> turtle.goto(0,-50)
> turtle.end_fill()
> turtle.penup()
> turtle.goto(-75,125)
> x=turtle.pos()
>
> #Helvetica is the one true font
> turtle.write(fate,font=("Helvetica",12,"normal"))
>
> #call functions
> print1()
> main()
>
> #exit message
>
> for count in range(20):
> print("Thanks for playing!")
> ___
> 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] beginning to code

2017-09-10 Thread Bob Gailer
On Sep 10, 2017 8:40 AM, "Senthil Kumaran"  wrote:
>
> > unindent does not match any outer indention level
>
> Means that your Intendentaion is not proper. You should align your print
> statement and rest to the same level as if statement.
>
> Use a proper editor that supports Python Syntax.
>
Also the last line will print access granted if the password does not
match. Probably not what you wanted. Either indent it and put it before
break or unindent it so it lines up with while.

For what it's worth if the user never gets the password he is stuck forever
in the loop.

In the future please include the entire traceback in your email. That makes
it a lot easier for us to relate it to your code.

> On Sun, Sep 10, 2017 at 4:32 AM, Elmar Klein  wrote:
>
> > Hi there,
> >
> > im starting to learn how to code (bougt me the "automate the boring
stuff
> > with phyton" book).
> >
> > And im not going anywhere with a code sample using the "continue"
> > statement.
> >
> > The code i should try is as following:
> >
> > while True:
> >   print ('who are you')
> >   name = input ()
> >   if name != 'bert':
> >   continue
> > print ('hi, joe. pwd?')
> > pwd = input ()
> > if pwd == 'sword':
> > break
> > print ('access granted')
> >
> > But everytime this produces an error (unindent does not match any outer
> > indention level) in the "print ('hi, joe. Pwd?')" sentence.
> >
> > What am i doing wrong?
> >
> > Greetings
> >
> > kerbi
> >
> >
> >
> > ___
> > 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] unknown syntax error

2016-12-15 Thread bob gailer

On 12/11/2016 11:30 AM, oliver patterson wrote:

hey i dont know if this is the right place but i was just coding in idle and 
kept getting this syntax error and i can not see m to fix it here is my bit of 
code:

my_age=14
age=input("How old are you?:")
print("type start()")
def start():
 print("hey")
 if age == my_age:
 print("i'm",age,"too")
 else:
 if age < 14:
 print(" i'm older that you i'm",my_age,":)")
 else:
 print("your older than me i'm",my_age,":(")



please help thank you.
IDLE's way of reporting some errors is different than the standard 
traceback, so you may not be able to follow Bob Stepp's advice.


When I select Run on your module I see the first "else" highlighted in 
red, and the invalid syntax message.


If you undent the else blocks giving:

my_age=14
age=input("How old are you?:")
print("type start()")
def start():
print("hey")
if age == my_age:
print("i'm",age,"too")
else:
if age < 14:
print(" i'm older that you i'm",my_age,":)")
else:
print("your older than me i'm",my_age,":(")

the program will pass the syntax checks. When you run it it will fail:

How old are you?:as
type start()
>>> start()
hey
Traceback (most recent call last):
  File "", line 1, in 
start()
  File "C:/Python35/oliver.py", line 9, in start
if age < 14:
TypeError: unorderable types: str() < int()
>>>

Can you figure out why? Can you propose a fix?

If you want to impress potential employers I recommend cleaning up your 
English.

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


Re: [Tutor] (no subject)

2016-12-10 Thread Bob Gailer
On Dec 10, 2016 12:15 PM, "Tetteh, Isaac - SDSU Student" <
isaac.tet...@jacks.sdstate.edu> wrote:
>
> Hello,
>
> I am trying to find the number of times a word occurs on a webpage so I
used bs4 code below
>
> Let assume html contains the "html code"
> soup = BeautifulSoup(html, "html.parser")
> print(len(soup.find_all(string=["Engineering","engineering"])))
> But the result is different from when i use control + f on my keyboard to
find
>
> Please help me understand why it's different results. Thanks
> I am using Python 3.5
>
What is the URL of the web page?
To what are you applying control-f?
What are the two different counts you're getting?
Is it possible that the page is being dynamically altered after it's loaded?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 1 to 49 numbered grid

2016-12-08 Thread Bob Gailer
On Dec 8, 2016 8:52 AM, "M Ali"  wrote:
>
> Hi Team
>
> I was wondering if you can help me, as I am struggling to create a
numbered grid in Python. I am trying to be able to create a snakes and
ladders game in Python and it must have a numbered grid and involve 2
players. I would appreciate it if you can help me or guide me to create
this game.
Assuming you are taking a class, what tools have you been given?
What Graphics packages?
The more information you give us the more helpful we can be. Be assured we
are here to help.
>
> Regards
>
> Mr Ali
> ___
> 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] String within a string solution (newbie question)

2016-10-27 Thread Bob Gailer
BubOn Oct 27, 2016 8:38 AM, "Wish Dokta"  wrote:
>
> Hello Alan,
>
> Thank you for the reply.
>
> I have actually fixed that bug. If you are bored or for some other reason
> would like to assist a newbro my code is here:
>
> main: http://pastebin.com/LgbeywiB
> functions: http://pastebin.com/vU7zzJKe

Code following first while needs to be indented.
Too many unnecessary blank lines.
Since a drive is a letter ask user to enter a letter rather than going
through the exercise of translating letters to numbers and back.
Minimize the number of statements following try.
To print a message surrounded by blank lines consider:
print("\nMessage\n") or
print("""
Message
""")
>
> I'd be very grateful for any feedback on improvements to the code or how I
> am coding in general. I'd be particularly interested in a better data
> structure to use to store the directories and their sizes.
>
> Many thanks,
> Glen
>
> On 26 October 2016 at 19:34, Alan Gauld via Tutor 
wrote:
>
> > On 26/10/16 19:06, Wish Dokta wrote:
> >
> > > folders with a drive/directory. To do this I am storing each directory
> > in a
> > > dict as the key, with the value being the sum of the size of all
files in
> > > that directories (but not directories).
> > >
> > > For example:
> > >
> > > for "C:\\docs\\code" in key:
> > >
> > > Which works fine and will return "C:\\docs\\code" : 20,
> > > "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35)
> > >
> > > However it fails when I try to calculate the size of a directory such
as
> > > "C:\\docs", as it also returns "C:\\docs123".
> > >
> > > I'd be very grateful if anyone could offer any advice on how to
correct
> > > this.
> >
> > We can't guess what your code looks like, you need to show us.
> > Post the code and we can maybe help.
> >
> > --
> > Alan G
> > Author of the Learn to Program web site
> > http://www.alan-g.me.uk/
> > http://www.amazon.com/author/alan_gauld
> > Follow my photo-blog on Flickr at:
> > http://www.flickr.com/photos/alangauldphotos
> >
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> ___
> 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] String within a string solution (newbie question)

2016-10-26 Thread Bob Gailer
On Oct 26, 2016 2:07 PM, "Wish Dokta"  wrote:
>
> Hello,
>
> I am currently writing a basic program to calculate and display the size
of
> folders with a drive/directory. To do this I am storing each directory in
a
> dict as the key, with the value being the sum of the size of all files in
> that directories (but not directories).
>
> For example:
>
> { "C:\\docs" : 10, "C:\\docs123" : 200, "C:\\docs\\code\\snippets" : 5,
> "C:\\docs\\code" : 20, "C:\\docs\\pics" : 200, "C:\\docs\\code\\python" :
> 10  }
>
> Then to return the total size of a directory I am searching for a string
in
> the key:
>
> For example:
>
> for "C:\\docs\\code" in key:

Put "\\" at the end of the search string.
>
> Which works fine and will return "C:\\docs\\code" : 20,
> "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35)
>
> However it fails when I try to calculate the size of a directory such as
> "C:\\docs", as it also returns "C:\\docs123".
>
> I'd be very grateful if anyone could offer any advice on how to correct
> this.
> ___
> 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] Adding numbers within a string

2016-10-12 Thread Bob Gailer
On Oct 12, 2016 4:09 AM, "LQ Soh"  wrote:
>
> To whom it may concern,
> Can someone enlighten me as to how you can create a function such
> that sum_numbers('10 5 8'), when run, will give an answer of 23, without
> using str.split() and using a for loop

def sum_numbers(x):
for x in [1]:
print(23)

Your instructor will probably be displeased with that answer, but it meets
the requirements.

It would be nice if our teachers could models writing good requirements.

What do you think a good requirement statement would be?
___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Word Problems(Student) MORE ISSUES

2016-10-06 Thread bob gailer

On 10/6/2016 10:15 AM, Zeel Solanki wrote:

def filter_long_words(words, n):
   for x in words.split():
 return filter(lambda x: len(x) > n, words)

print filter_long_words(raw_input("Enter a list of words with spaces in
between."), raw_input("Enter a number."))
raw_input() always returns a string. When you enter a number (say, 5) it 
will be a string ("5").


use int() to convert that string to numeric.

But there are more issues. The function logic is misleading: you can 
remove the line beginning with "for". the loop will get the first word, 
appply filter (ignoring the word), then the function will stop.


"However , if i replace the raw_inputs with any given list and a number 
in the editor" Exactly what do you enter for a list?


Remember that anything you enter in the editor for words and n must be a 
string. Your function will give incorrect results.


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


Re: [Tutor] Python Word Problems(Student)

2016-10-06 Thread bob gailer

On 10/6/2016 10:15 AM, Zeel Solanki wrote:

def filter_long_words(words, n):
   for x in words.split():
 return filter(lambda x: len(x) > n, words)

print filter_long_words(raw_input("Enter a list of words with spaces in
between."), raw_input("Enter a number."))
raw_input() always returns a string. When you enter a number (say, 5) it 
will be a string ("5").


use int() to convert that string to numeric.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Max Number and Min number script

2016-09-17 Thread Bob Gailer
On Sep 17, 2016 4:55 PM, "Sharon Wallace"  wrote:
>
> Would you please help me with the last piece of this assignment?
>
>
>
> This is my code:
>
>
>
> largest = None
>
> smallest = None
>
>
>
> while True:
>
> num = raw_input("Enter a number:  ")
>
> if num == "done" : break
>
> print num
>
>
>
> try :
>
> num = int(num)
>
> except :
>
> print "Invalid input"
>
> continue
>
>
>
> if num > largest :

> comparing integers To None is not a good idea. Your earlier program had
it right when you tested for None and greater than /  less then.

Another way to tackle this is to initialize largest to some extremely large
negative value and I smallest to some extremely large positive value.

When replying to these emails please always include the tutor group.

Congratulations on persisting and making it this far.

> largest = num
>
>
>
> if num < smallest :
>
> smallest = num
>
>
>
> print 'Maximum is', largest
>
> print 'Minimum is', smallest
.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Max Number and Min number script

2016-09-16 Thread Bob Gailer
On Sep 16, 2016 8:12 PM, "Sharon Wallace"  wrote:
>
In addition to showing us your code ,
Please show us whatever Trace back you got when you ran the code. I would
guess you are either getting an indentation error or syntax error in the
vicinity of line that begins if num =.

> inp = raw_input
>
> largest = None
>
> smallest = None
>
>
>
> while True:
>
> num = raw_input('Enter a number:  ')
>
> if num = 'done' : break
>
> print num
>
>
>
> try :
>
> num = float(inp)
>
> except :
>
> print 'Invalid input'
>
> continue
>
>
>
> if largest is None or num > largest :
>
> largest = num
>
>
>
> if smallest is None or num < smallest :
>
> smallest = num
>
>
>
> print 'Maximum is:', largest
>
> print 'Minimum is:', smallest
>
>
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Assignment

2016-08-02 Thread Bob Gailer
On Aug 2, 2016 4:42 AM, "Justin Korn via Tutor"  wrote:
>
> To whom it may concern,
>
> I need help on this assignment:
>
>
> Create a new class, SMS_store. The class will instantiate SMS_store
objects, similar to an inbox or outbox on a cellphone:
> my_inbox = SMS_store()
> This store can hold multiple SMS messages (i.e. its internal state will
just be a list of messages). Each message will be represented as a tuple:
> (has_been_viewed, from_number, time_arrived, text_of_SMS)
> The inbox object should provide these methods:
> my_inbox.add_new_arrival(from_number, time_arrived, text_of_SMS)
>   # Makes new SMS tuple, inserts it after other messages
>   # in the store. When creating this message, its
>   # has_been_viewed status is set False.
>
> my_inbox.message_count()
>   # Returns the number of sms messages in my_inbox
>
> my_inbox.get_unread_indexes()
>   # Returns list of indexes of all not-yet-viewed SMS messages
>
> my_inbox.get_message(i)
>   # Return (from_number, time_arrived, text_of_sms) for message[i]
>   # Also change its state to "has been viewed".
>   # If there is no message at position i, return None
>
> my_inbox.delete(i) # Delete the message at index i
> my_inbox.clear()   # Delete all messages from inbox
> Write the class, create a message store object, write tests for these
methods, and implement the methods.
>
> The following attachment is what I have so far:

This mailing list is not forward attachments. Instead copy your code and
paste it into the email.
>
>
> and I get the error
>
> Traceback (most recent call last):
>   File "/Applications/Python Assignments/C15E6_JustinKorn.py", line 58,
in 
> my_inbox.get_message(i)
> NameError: name 'i' is not defined
>
> Please help me.
>
> Thanks,
> Justin
>
> ___
> 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 me out please

2016-07-19 Thread Bob Gailer
On Jul 19, 2016 9:24 AM, "Marc Sànchez Quibus" 
wrote:
>
> Hi,
> First of all I'm gonan introduce myself. My name is Marc and I'm a student
> and also a python's programmer begginer. I've been studying/learning
python
> and now I need some help to finish my project.
> I have two scripts, one of them in python (the main script) and the other
> one written in html. Well, is just a brief javascript (an app) that I took
> by Github. I need to change a variable inside this html script. I was
> wondering wether I could change this variable from my python script or
not.
> Is there some way to do it?

There might be. Tell us more about your situation.

> Thanks in advance and sorry for the inconvenience.

Since we are here to help, the only inconvenience his when we don't get
enough information. That seems to be typical for first time questioners.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rock paper scissor lizard spock help

2016-06-14 Thread Bob Gailer
On Jun 14, 2016 4:05 PM, "Katelyn O'Malley"  wrote:
>
> Hi I am just getting into python and I am trying to create a rock paper
> scissor lizard spock game for 3 people and I cannot figure out the scoring
> of the players I attached the code below, any help/ideas is much
> appreciated.
Welcome to python and the tutor list.

I don't know what you mean by "figure out the scoring". Please explain.

Did you test the program? Please do that now, fix the problems that you
will discover.

I don't want to sound discouraging, but there are many problems here. I
will list some.

Unused items e.g. random.
Undefined names e.g. difference.
Unnecessary function calls e.g. str, int
Repeated code.

I assume this is your first attempt at programming.

Have you gone through any tutorials?

It would be good to start with something simpler.

I suggest you sit with pencil and paper and walk through the program line
by line.

What happens If a player enters something other than a valid choice?

We want you to succeed. But you must study proper coding techniques. Take a
course, read a book, get a simpler program running.

>
> import random
>
> number_of_games = 3
>
> print("Player 1 please choose rock , paper , scissors , lizard, or spock
> (in lower case please)")
> choice1 = input("What do you choose?  ")
> player1_choice = str(choice1)
> print("Player 2 please choose rock , paper , scissors , lizard, or spock
> (in lower case please)")
> choice2 = input("What do you choose?  ")
> player2_choice = str(choice2)
> print("Player 3 please choose rock , paper , scissors , lizard, or spock
> (in lower case please)")
> choice3 = input("What do you choose?  ")
> player3_choice = str(choice3)
> def name_to_number(name):
> if name == "rock":
> name = 0
> return name
> elif name == "spock":
> name = 1
> return name
> elif name == "paper":
> name = 2
> return name
> elif name == "lizard":
> name = 3
> return name
> elif name == "scissors":
> name = 4
> return name
>
> def number_to_name(number):
> if number == 0:
> number = "rock"
> return number
> elif number == 1:
> number = "spock"
> return number
> elif number == 2:
> number = "paper"
> return number
> elif number == 3:
> number = "lizard"
> return number
> elif number == 4:
> number = "scissors"
> return number
>
> player1_number = name_to_number(choice1)
> player2_number = name_to_number(choice2)
> player3_number = name_to_number(choice3)
>
> while number_of_games > 0:
> number_of_games -= 1
> print("Player 1 choice is: " + player1_choice)
> print("Player 2 choice is: " + player2_choice)
> print("Player 3 choice is: " + player3_choice)
> if (int(player1_number) - player2_number) % 5 >=3:
> print("Player 1 wins!")
> elif difference >=2:
> print("Player 2 wins!")
> elif difference <=1:
> print ("Player 3 wins!")
> elif difference == 0:
> print("It's a tie! You have %d tries left..." % number_of_games)
> number_of_games = ''
> else:
> print("You lost to the Computer. You have %d games left..." %
> number_of_games)
> number_of_games = ''
> break
>
> while number_of_games >0:
> number_of_games -=1
> choice1 = input("What do you choose?  ")
> player1_choice = str(choice1)
> print("Player 1 choice is: " + player1_choice)
> choice2 = input("What do you choose?  ")
> player2_choice = str(choice2)
> print("Player 2 choice is: " + player2_choice)
> choice3 = input("What do you choose?  ")
> player3_choice = str(choice3)
> print("Player 3 choice is: " + player3_choice)
> if difference >=3:
> print("Player 1 wins!")
> elif difference >=2:
> print("Player 2 wins!")
> elif difference <=1:
> print ("Player 3 wins!")
> elif difference == 0:
> print("It's a tie! You have %d tries left..." % number_of_games)
> number_of_games = ''
> else:
> print("You lost to the Computer. You have %d games left..." %
> number_of_games)
> number_of_games = ''
> break
>
> while number_of_games >0:
> number_of_games -=1
> choice1 = input("What do you choose?  ")
> player1_choice = str(choice1)
> print("Player 1 choice is: " + player1_choice)
> choice2 = input("What do you choose?  ")
> player2_choice = str(choice2)
> print("Player 2 choice is: " + player2_choice)
> choice3 = input("What do you choose?  ")
> player3_choice = str(choice3)
> print("Player 3 choice is: " + player3_choice)
> if difference >=3:
> print("Player 1 wins!")
> elif difference >=2:
> print("Player 2 wins!")
> elif difference <=1:
> print ("Player 3 wins!")
> elif difference == 0:
> print("It's a tie! You have %d tries left..." % 

Re: [Tutor] How to make object disappear?

2016-05-09 Thread Bob Gailer
On May 9, 2016 8:01 AM, "Lisa Hasler Waters"  wrote:
>
> Dear Tutor,
>
> My students and I are creating a maze game in tkinter. We are trying to
> make the ball disappear when it hits the wall (black lines). We are not
> having much luck. The following code has run the best, but still, the ball
> does not disappear. Any advice would be appreciated!
>
> from tkinter import *
> import random
> import time
>
>
> tk = Tk()
> tk.title("Game")
> tk.resizable(0, 0)
> tk.wm_attributes("-topmost", 1)
> canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0)
> canvas.pack()
> tk.update()
>
>
> class dot:

It is a Python convention to capitalize class names. In the future write
class Dot.

> def __init__(self, canvas, color):
> self.canvas = canvas
> self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue',
> tags='dot1')
>
> this = dot(canvas, 'blue')
>
> def ball(n, x, y):
> canvas.move(n, x, y)
>
> def mt(event):
> if event.keysym == 'Left':
> ball(1, -30, 0)
> restart()
> elif event.keysym == 'Up':
> ball(1, 0, -30)
> restart()
> elif event.keysym == 'Down':
> ball(1, 0, 30)
> restart()
> elif event.keysym == 'Right':
> ball(1, 30, 0)
> restart()
> else:
> ball(1, 30, 0)
> restart()

This is my own opinion. It is important to separate data from logic. In
this case you are trying to map a key symbol to some numeric values:
key_to_val = {'Left' : (0, 30, 0), 'Right' etc}

(I realize you are probably introducing students to programming. So you
might first show the  then else logic, then introduce the dictionary
alternative.)

val = key_to_val.get(event.keysym, (30, 0))
ball(val)
restart()

15 lines of code replaced by 4. Easier to write,  easier to understand,
easier to maintain. Worth learning about dictionaries.
>
> canvas.bind_all('', mt)
> canvas.bind_all('', mt)
> canvas.bind_all('', mt)
> canvas.bind_all('', mt)
>
> dot_bbox = canvas.coords('dot1')
>
>
>
>
> x = dot_bbox[0]
> y = dot_bbox[1]
> x2 = dot_bbox[2]
> y2 = dot_bbox[3]
>
> canvas.create_line(0, 0, 0, 300, width=20)
> canvas.create_line(0, 300, 300, 300, width=10)
> canvas.create_line(80, 240, 80, 0, width=10)
> canvas.create_line(160, 300, 160, 60, width=10)
> canvas.create_line(240, 240, 240, 0, width=10)
> canvas.create_line(300, 300, 300, 150, width=10)
> canvas.create_line(300, 150, 600, 150, width=10)
> canvas.create_line(80, 0, 2000, 0, width=30)
> canvas.create_line(300, 75, 600, 75, width=10)
> canvas.create_line(760, 0, 760, 300, width=10)
> canvas.create_line(600, 75, 680, 75, width=10)
>
> def restart():
> if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or
> (canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or
> (canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or
> (canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or
> (canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True:
> canvas.delete('dot1')

I got a syntax error from that if statement.

It seems to me (obviously?) that canvas.delete is never called. This is a
great opportunity for reaching debugging. I'd add a print function call to
show the value of the canvas.find_overlapping call.

Also a good opportunity to read the manual. canvas.find_overlapping returns
a tuple of all matching items.

It would make code reading and maintenance easier if you assign
canvas.find_overlapping(x, y, x2, y2) to a name, then refer to that name in
the logic.
Revisiting the separation of data from logic:
if canvas.find_overlapping(x, y, x2, y2) in ((1,1),(1,2) etc.)

Also avoid things like if x ==True:
It is sufficient to write if x:

In English we say "if it is raining..." rather than " if it is raining is
True ".

Take what you want -l eave the rest.
>
>
>
>
>
>
> Shell:
>
> Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44)
> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> Type "copyright", "credits" or "license()" for more information.
> >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.
> Visit http://www.python.org/download/mac/tcltk/ for current information.
>
> >>>
>  RESTART: /Users/BScherer/Desktop/MazeTest.py
> 
> >>>
> === RESTART: Shell
> ===
> >>>
>  RESTART: /Users/BScherer/Desktop/MazeTest.py
> 
> >>>
> === RESTART: Shell
> ===
> >>> from tkinter import *
> >>> import random
> >>> import time
> >>> tk = Tk()
> >>>
> >>> tk.title("Game")
> ''
> >>> tk.resizable(0, 0)
> ''
> >>> tk.wm_attributes("-topmost", 1)
> ''
> >>> canvas = Canvas(tk, width=1400, height=835, bd=0,
highlightthickness=0)
> >>> canvas.pack()
> >>> tk.update()
> >>> class dot:
> def __init__(self, canvas, color):
> 

Re: [Tutor] Python Homework CORRECTION rules -> tools (programs)

2016-05-04 Thread Bob Gailer
On May 3, 2016 2:38 PM, "Katie Tuite"  wrote:
>
> So I know what a color gradient is, I don't know how to compute it
though. As far as programs, they told us we should use matplotlib, NumPy,
and SciPy to display graphs.

Thanks. Always reply to the list as well as me.

Computing gradient. Each color has a numeric value, normally in the range
of 0 to 16,581,375. Each of your data points has a value in the range of -1
to 1. You need to get the values of  red and yellow, then the color value
of each data point is proportionately between red and yellow as the data
point is between -1 and 1.
Since I don't know your academic background I'm guessing that this
explanation might work. Let us know.
I'm not familiar enough with the plotting packages you cited. Perhaps
someone else on this list can help here.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Homework CORRECTION rules -> tools (programs)

2016-05-03 Thread bob gailer


On May 3, 2016 3:04 AM, "Katie Tuite" > wrote:

>
> So the question is:
>
> "a contour plot is a graphic representation of the relationships 
among three numeric variables in two dimensions. Two variables are for X 
and Y axes, and a third variable Z is for contour levels. The contour 
levels are plotted as curves; the area between curves can be color coded 
to indicate interpolated values.

>
> A color gradient specifies a range of position-dependent colors, 
usually used to fill a region.

>
> The class file holds data for a 1000x1000 matrix, each element is a 
floating point number and has a value between -1 and 1. Plot each point 
of the matrix using Python to a grid and assign a red to yellow color 
gradient to the plot where -1 is red and 1 is yellow."


There are two problems to be solved here. One is Computing the gradient, 
the other is displaying the graph.
Do you understand the concept of a color gradient? Do you know how to 
compute it? Have you been given any tools (programs) for displaying graphs?

Once we have that information we can take the next steps.

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


Re: [Tutor] Dictionary Question

2016-05-02 Thread Bob Gailer
On May 2, 2016 5:27 PM, "Jason N. via Tutor"  wrote:
>
> Hello,
> Wanted to ask if its possible to have a dictionary that can be looked up
by either values?
> For example,
> mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple"
to come. But if the user enter "Apple" I want "A" to respond.
I think this would depend on how big the data set is and how often you want
to look things up.
Two other Solutions:
Create a class which internally manages two dictionaries.
If things are really big create a database using for example sqlite.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Homework

2016-05-01 Thread Bob Gailer
On May 1, 2016 4:33 AM, "Katie Tuite"  wrote:
>
> I'm trying to do a python homework question and cannot figure out how to
> start at all.
>
> This is the question
>
> [image: pasted1]
As you can see attachments don't work. Include the code in your post.
> ___
> 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] Issues converting a script to a functioin (or something)

2016-05-01 Thread Bob Gailer
On May 1, 2016 8:04 AM, "Olaoluwa Thomas"  wrote:
>
> The novice Python programmer is back.
Welcome back. We are here to help you when you are stuck. Telling us
something is broken is not adequate. Tell us-what you are expecting the
program to do and what results you're getting.
>
> I'm trying to incorporate a function and its call in the GrossPay.py
script
> that Alan solved for me.
> It computes total pay based on two inputs, no. of hours and hourly rate.
>
> There's a computation for overtime payments in the if statement.
>
> Something seems to be broken.
>
> Here's the code:
> def computepay(hours, rate):
> hours = float(raw_input ('How many hours do you work?\n'))
> rate = float(raw_input ('What is your hourly rate?\n'))
> if hours > 40:
> gross = ((hours - 40) * (rate * 1.5)) + (40 * rate)
> elif hours >= 0 and hours <= 40:
> gross = hours * rate
> print "Your Gross pay is "+str(round(gross, 4))
>
> computepay()
>
> What am I doing wrong?
>
> *Warm regards,*
>
> *Olaoluwa O. Thomas,*
> *+2347068392705*
> ___
> 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] "List" object is not callable

2016-04-30 Thread bob gailer

On 4/30/2016 3:27 PM, Alex Kleider wrote:



On 2016-04-30 11:51, Jason N. via Tutor wrote:

Hello,
I found this simple script online but when I execute it I get the
following error: "TypeError: 'list' object is not callable"
Here is the code sample:import subprocess

ls_output= subprocess.check_output(['dir'])

It works on my system: Ubuntu 14.04LTS

Works on my Windows 10 also.

Always post the traceback. The problem must lie in check_output as there 
is nothing in your code that could raise that exception.


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


Re: [Tutor] Best tool for programming interactive games in Python

2016-03-29 Thread Bob Gailer
On Mar 29, 2016 2:03 PM, "Lisa Hasler Waters"  wrote:
>
> I continually get this error:
>
>
> Traceback (most recent call last):
>   File "/Users/lwaters/Desktop/pygameTest.py", line 1, in 
> import pygame, sys
>   File
>
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py",
> line 95, in 
> from pygame.base import *
> ImportError:
>
dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so,
> 2): no suitable image found.  Did find:
>
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so:
> no matching architecture in universal wrapper
I assume you are running python 2.7 . true?
What operating system?
How did you install pygame?
First guess uninstall and reinstall a game.
Any other information you can give us may help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Advice on multi-dimensional data storage

2016-03-19 Thread Bob Gailer
On Mar 16, 2016 5:59 AM, "Matt Williams" 
wrote:
>
> Dear Tutors,
>
> I am looking for some advice. I have some data that has three dimensions
to
> it. I would like to store it such that one could manipulate (query/
update/
> etc.) by dimension - so it would be feasible to ask for all of the data
> that shares a value in d1, or iterate over all of the values via d2.

I don't understand. Please give a couple of examples.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can This Script Be Modified to Read Many Files?..

2016-01-25 Thread Bob Gailer
On Jan 25, 2016 6:26 PM, "Sam Starfas via Tutor"  wrote:
>
> Hi,I am very new to Python, but having fun learning.
> I need to have a script read all of the XML files contents that are in a
directory, pull out the contents of an element, in my case , and
list them in an output file. I have this script that does exactly what I
need. But in my beginning Python class we didn't go over reading all files,
only one file at a time.
> Can the below script be modified to scan/read all of the XML files in a
directory instead of just the file typed into the script? If so, how do I
do this?
> Thanks for all the help.Sam
>
> import xml.etree.ElementTree as ETtree = ET.parse('TEST.xml')   <-- Want
to read all the files in directory, not type in the filename.root =
tree.getroot()
>
> for uicontrol in root.iter('uicontrol'):print(uicontrol.text)
As you probably noticed your code got mangled this is probably due to the
email program you're using what you should do is have it send plain text so
the formatting will be preserved.
I hope it's obvious that you will need a loop to process multiple files so
I'm going to assume that what you want is how to get a list of files
meeting some criteria in a directory. I'm dictating into my cell phone
right now so I can't look some things up but my presumption is you will
need to use the glob function in the glob module to get the list of
filenames, then iterate over that list. Hope that helps.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] new line to list of strings send by email

2016-01-08 Thread Bob Gailer
On Jan 8, 2016 11:03 AM, "Emil Natan"  wrote:
>
> Hello list,
>
> I have a function which receives a string and sends it as a body of an
> email.
>
> It is a part of a program which does certain checks on network
> infrastructure. When a check fails I append error message to a
> error_collector list:
>
>
> if self.check_axfr_refused(ip):
>  error_collector.append('%s:%s AXFR test for %s FAILED' %
>(ns, ip, self.domainname))
>
> At the  end I send the alert like this:
>
> if len(error_collector) != 0:
> email_body = str(error_collector)
> email_alert(email_body)
Instead of str( str(error_collector) ) try '\n'.join(error_collector)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] noob python question

2015-10-26 Thread Bob Gailer
Welcome to the tutor list. In order for us to help you please post the
following:
Python version
Operating system
The code you are running
To trace back you are getting
The trace back will be several lines of references to various programs and
line numbers

Once we have that information then it becomes easy to help good luck
On Oct 26, 2015 12:08 AM, "bob5487"  wrote:

> Howdy!
>
> Reading *Learn Python the Hard Way* Zed Shaw
>
> All good so far but got to Ex 42 dealing with classes...
>
> I get a TypeError: getattr(): attribute name must be a string when I run
> the
> program...
>
> I looked online, python reference manual 3rd edition, etc...
>
> I was wondering if anyone has experience with this book because I hit a
> road
> block
>
>
>
>
>
> --
> View this message in context:
> http://python.6.x6.nabble.com/noob-python-question-tp5174789.html
> Sent from the Python - tutor mailing list archive at Nabble.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] I don't understand why this program is said to be "not defined" when I test it.

2015-10-17 Thread Bob Gailer
Also:
Briefly describe problem 22
Show us what you did to test the program
It would be better to test for integer before doing a numeric comparison
There is no need ever to compare a boolean expression to true or false. All
you need is either if condition or if not condition.
A good short cut for a range test is
if 0<= x <= 6:
It is not necessary to surround a condition with parentheses.
Your code will be simpler if you initially set Bueller to true, then change
it to false as needed. Please excuse my spelling as I am dictating this.
Who would have thought so many comments could come from such a simple piece
of code.
On Oct 16, 2015 7:17 PM, "Alan Gauld"  wrote:

> On 16/10/15 23:31, zak nelson wrote:
>
>> I don't understand why this program is said to be "not defined" when I
>> test
>> it.
>>
>
> In future please be more precise in describing the problem,
> and that means including the full error message in the post.
> It contains a lot of useful information.
>
> I'm guessing it doesn't say that the program is not defined
> but it says the name buler is not defined? Is that correct?
>
> Notice the spelling?
> Now look at your code
>
> def problem22(aList):
>>  length=len(aList)
>>  if (length>6):
>>  bueler=False
>>  else:
>>  bueler=True
>>  for i in aList:
>>  if(i < 0 and i > 6)==False:
>>  bueler=False
>>  else:
>>  buler=True
>>  if type(i)!=("integer"):
>>  bueler=False
>>  else:
>>  bueler=True
>>  return bueler
>>
>
> But there are a couple of other issues in there too.
> Specifically this line:
>
>   if(i < 0 and i > 6)==False:
>
> The bit in parentheses can never be true because i can
> never be both <0 and >6 at the same time. So the if
> statement is always true and the next line is always
> executed.
>
> Also the line
>
>if type(i)!=("integer"):
>
> Will never be true because the string 'integer' is not a type.
> You should use the type name:
>
>if type(i) != int
>
> or compare to the type of a known value:
>
>if type(i) != type(5):
>
> In the case of an int the first one would be better.
> A final refinement is that for these kinds of comparisons
> it probably reads better to use is/is not rather
> than the ==/!= symbols, so:
>
>if type(i) is not int:
>
> HTH
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python algorithms (Lang line simplification algorithm)

2014-04-14 Thread bob gailer

On 4/14/2014 11:30 AM, Laura Kauria wrote:

Thanks a lot for all the help! I got the courage to start at least..


Some requests regarding posts.

1) put your comments following the relevant text rather than at the top.
2) delete old (irrelevant) text.
4) be more clear with your questions.

I started by converting the pseudocode I had to python.


3) post your code
Still I have problems with perpendicular distance and creating a line 
with python.

I need to create a line between two points

what does that mean (apart from the obvious) in terms of your code
and then check what is the distance between a line and intermediate 
points which were between lines start and end point. If someone could 
help me with this?
I'm a geographer student so all possible library suggestions 
concerning spatial data is also appreciated.



4) be more clear with your questions.

I can make guesses about what you want, but that wastes time.

 distance between a line and intermediate points which were between 
lines start and end point as I read this the answer seems to be zero. ( 
a point that is between lines start and end point is on the line). I 
don't think you mean that.


We are here to help. The more you tell us the easier it is for us to help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why should modules or packages should define their own domain-specific base exception class?

2014-04-14 Thread bob gailer

On 4/14/2014 10:09 PM, brian arb wrote:
I don't quite understand why the google python style guide recommends 
that packages and modules we write should avoid using the catch-all 
except. Instead the guide encourages you to write domain specific 
exception classes.


class Error(Exception):
  ...

class ThisSpecificError(Error):
...

class ThatSpecificError(Error):
...


try:
  ...
except mylib.Error:
  ...
|
|
|REF. 
|http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Exceptions#Exceptions


Thoughts?
Let's say I write a program to process some user input that should 
follow some syntatic / semantic rules. When my program finds a violation 
I want to raise an exception that is specific to these rules, rather 
than a built-in exception.


Raising such exceptions is a useful way to exit from some possibly 
deeply nested series of calls, ifs, whiles, fors, etc. I write except 
statements for my error classes, then let the python-specific ones be 
caught by a different except.


The python-specific exceptions mean something is wrong with my progam, 
which I handle differently than those related to user input.

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


Re: [Tutor] Range within a range

2014-04-11 Thread bob gailer

On 4/11/2014 1:13 PM, Andoni Gorostiza wrote:
Hi tutor. I need your help with something I don't understand. In the 
tutorial, it mentions an example of a range within a range. I'll keep 
it simplified. How exactly does this work? I'll provide a few examples.


 for x in range(0,5):
...for n in range(0,5):
...  print(x)

 for x in range(0,5):
...for n in range(0,5)
...  print(n)

This one comes from the tutorial:

for  n  in  range(2,  10):
... for  x  in  range(2,  n):
... if  n  %  x  ==  0:
... print(n,  'equals',  x,  '*',  n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n,  'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
Can you explain what is going on?
We could but that will not help you learn. Instead I recommend with 
pencil and paper you play computer - execute (write) the code one step 
at a time and write down what happens. Very simple example:

execute:   change:
for x in range(0,2):  x == 0
  for n in range(0,2):   n == 0
print(x) output == 0
  next for n   n == 1
print(x) output == 0
next for x x == 1
  for n in range(0,2):   n == 0
print(x) output == 1
keep going - at each step write what executes and what changes or happens

When you run into an operation you don't understand stop and either
- look it up
- ask this list

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


Re: [Tutor] Refining Code

2014-04-11 Thread bob gailer

On 4/10/2014 6:26 PM, Saba Usmani wrote:


 My task is :

Welcome to the tutor list. In what school are you learning Python?

What version of Python? What operating system? What do you use to write 
and run your code?


What Python elements have you studied so far? Your code can be greatly 
simplified by the application of tuples, lists, dictionaries, functions 
and/or classes.


Requests: post in plain text rather than html (no formatting). This 
guarantees that all of us will be able to read your posts with ease.


Also reply in such a way that a copy goes to tutor@python.org, to keep 
all of us in the loop.


The rest of my comments follow the relevant part of your post. Please 
also reply in similar fashion. Avoid as much as possible top posting.


A food vending machine accepts 10p, 20p, 50p and £1 coins. One or more 
coins are inserted and the current credit is calculated and displayed. 
A product is selected from those available. The system checks to see 
if there is enough credit to purchase the product chosen. If there is 
not enough credit the system displays an error message. If there is 
enough credit it dispenses the product, updates the credit available 
and displays the remaining credit. Further selections can be made if 
there is enough credit. The vending machine simulation should have 
five products and prices. Design, code, test and evaluate a program 
for this simulation.
I am glad to see this problem appear again. Recently it was sent to me 
privately by someone who claimed it was not homework!


Critique of the specification: it is a bit vague (imprecise). I assume 
the instructor has a broad tolerance for what is delivered. In a 
business environment I'd want it a lot more precise. Often I have to 
help the user accomplish this, as many users don't know how to do this.


it is a good idea to first develop a sample dialog from the 
specification, review that with the user, then code to reproduce that 
sample. Do this. Either review it with the instructor or forget that step.


I have designed the following code, but would like to know how to make 
it more efficient without making it too complex as I am a beginner or 
is this fine?
Efficient? Do you mean execution time? With today's processor speeds 
that is rarely an issue to be concerned about when first writing code.


Complexity does not necessarily create efficiency.
Also, how do I add a loop to this so that once one product has been 
dispensed the program asks the user if they would like to continue and 
purchase another product?

Alan has given a suggestion already.

Based on your code you already know how to use a while loop. What is 
mysterious about using it here?



Code:

print Welcome to Snack Attack

snack1 = 0.40
snack2 = 0.75
snack3 = 1.20
snack4 = 0.99
snack5 = 0.50
insert = 0

You never use this variable!


change = 0

This machine does not dispense change!

currentCredit = 0.00
A = 0.10
B = 0.20
C = 0.50
D = 1.00
a = 0.10
b = 0.20
c = 0.50
d = 1.00
Never Never use floating values for money, as floating point cannot in 
general represent fractional values exactly.


print Menu
print Snack 1: Snickers - £0.40
print Snack 2: Doritos - £0.75 
print Snack 3: J20 - £1.20
print Snack 4: Oreos - £0.99
print Snack 5: MM's - £0.50
print Exit?- how do I make this a Boolean 
expression, so the user can respond with either yes or no?


You don't. Better (as Alan suggested) use raw_input and treat users 
entries as character. There is no advantage to using input and integers 
and a lot of room for errors.



choice = input(Select your snack: )
This does not agree with the specification - enter coin(s) first. The 
ensuing dialog also does not agree with the specification. You deposit 
one or more coins first, see the available credit. then choose a


if choice==1:
  print  
  print You have selected Snickers, which cost £0.40
  print Please insert £0.40
  while currentCredit  snack1:
  print Please select which of these coins to insert; 
A:10p,B:20p,C:50p and D:£1

  insert_coins = input(Insert coins: )
  currentCredit = insert_coins + currentCredit
Major problem here. As A user I'd enter (say) 20p. How does that get 
translated to a numeric value for adding?

What should happen if I enter 30p, or 20x, or foo?

  print Your current credit is £,currentCredit
This assumes that credit less than £1 will be reported as a fraction of 
a £. How will you handle this fraction?

  else:
  change_given=currentCredit-snack1
  print  
  print Your change is £,change_given
  print Your Snickers have been dispensed...Enjoy!

elif choice==2:
 print You have selected Doritos, which cost £0.75
 print Please insert £0.75
 while currentCreditsnack2:
  print Please select which of these coins to insert; 
A:10p,B:20p,C:50p and D:£1

  insert_coins = input(Enter coins: )
  currentCredit = insert_coins + currentCredit
  print Your current credit is £,currentCredit
 else:

Re: [Tutor] difference between expressions and statements

2014-04-10 Thread bob gailer
Caveat: I began this before there were any other responses. So this may 
be overkill - but I ike to be thorough.


On 4/9/2014 12:49 PM, Jared Nielsen wrote:

Hi Pythons,
Could someone explain the difference between expressions and statements?

I know that expressions are statements that produce a value.
No. Expressions are not statements. These are mutually exclusive. 
Expressions do produce values.

An attempt at a thorough answer:

In the language reference glossary under expression you will find:

A piece of syntax which can be evaluated to some value. In other words, 
an expression is an accumulation of expression elements like literals, 
names, attribute access, operators or function calls which all return a 
value There are also statements which cannot be used as expressions, 
such as if. Assignments are also statements, not expressions.


Tthe above is a quote; I don't like some of the grammar.

In your examples print is a function. So all calls to print are expressions.

In the language reference you will also find:

7. Simple statements
7.1. Expression statements
7.2. Assignment statements
7.3. The assert statement
7.4. The pass statement
7.5. The del statement
7.6. The return statement
7.7. The yield statement
7.8. The raise statement
7.9. The break statement
7.10. The continue statement
7.11. The import statement
7.12. The global statement
7.13. The nonlocal statement
8. Compound statements
8.1. The if statement
8.2. The while statement
8.3. The for statement
8.4. The try statement
8.5. The with statement
8.6. Function definitions
8.7. Class definitions

With the exception of
- 7.1. Expression statements
- all of the above are either start with a keyword except 7.2 assignment 
which is indicated by an equal sign (=) .
- all of the above cause something to happen (except pass), and do not 
return a value.


7.1. Expression statement is either one expression or several separated 
by commas.

Used interactively to display value(s).
Used anywhere to make a function call.

I'm unclear on functions and especially strings.
Are any of the following expressions?

print(42)
print(spam)
spam = 42
print(spam)

Is the first example producing a value or simply displaying an integer?
All function calls return a value. In the case of print the return value 
is always None.

spam = 42 is a statement. (indicated by the = sign. 42 is a value.

Does a string count as a value?
Yes - however I suspect you are limiting string to something within quotes. Those are 
string literals.
Is a variable assignment considered a value?

No

If I print a variable is that considered production of a value?

See above comment on print.

Long but comprehensive answer. Feel free to ask questions.

Note there are various subtleties here -some  keywords may be used to 
start a statement or in an expression - e.g. if, else, for yield.


This also raises the fact that else (inter ala) is neither an expression 
or a statement; rather it is part of a compound statement. Nothing is 
simple.


Oh there is more but I may never hit send

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


Re: [Tutor] difference between expressions and statements

2014-04-10 Thread bob gailer

On 4/10/2014 5:48 PM, Jared Nielsen wrote:


Thanks for the thorough answer, Bob. I now understand the difference.


Thanks for the ACK. It helps me remember I have something to contribute.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Vending machine problem.

2014-04-02 Thread bob gailer

On 4/1/2014 5:09 PM, Sebastien Gomez wrote:
I have started my code but there are some errors including indentation 
and syntax, please fix it if you can:


Did you miss my request that you send a copy to the tutor list 
(tutor@python.org)?


Were there any more specifications in the assignment?

Please take care of these; then I will respond. Also keep in mind that 
our goal is to help you think for yourself, so we may not fix it but 
rather help you understand and  fix the problems.


What tool did you use to discover multiple errors? If you try to run the 
program directly the Python interpreter will report the first error it 
finds and then stop.


In general it is a good idea to tell us (so please do so now)
- your operating system
- Python version
- what you use to edit and run the program

I am sorry to be so wordy and rigorous but we really need to know if we 
are to help.

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


Re: [Tutor] Vending machine problem.

2014-04-02 Thread bob gailer

On 4/2/2014 5:06 PM, Sebastien Gomez wrote:

i am using python 3.2
windows vista

This is my last email to you. Communicating with you is way too time 
consuming; you consistently do not provide all the information I 
request, nor do you include the tutor list in your responses.


If you want any more help you will have to ask it from the tutor list.

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


[Tutor] Vending machine problem.

2014-04-01 Thread bob gailer

I'm posting this to include you in this conversation.

Recently I got the following Request: can you write me a code in python 
please or if you have one already


my response:
 print('hello world')
what more can I do for you?

 (next two lines are best guesses as I can't find the relevant emails.
Request:  can you write me a code for a vending machine  in python 
please or if you have one already

Response: I need a lot more detail.

Request:
The vending machine must have 5 prices with items
it should accept 10p, 20p 50p and £1 coins
it should allow the user to purchase a item and give him a choice of 
purchasing something else. it should display the remaining credit once 
the item is purchased. i will let you know of anything else


Tutors: sounds familiar, eh?

Response: This sounds like a homework assignment. We don't provide 
answers for homework. We will help you once you show some effort and 
tell us where you need a hand.


The requirements are kinda vague. I would have a hard time guessing 
exactly what the instructor is looking for.


Did you get any other information?

Did you get some sample of the expected input and output?

If no to the latter,  good starting place is to write down a sample 
dialog, then apply the Python functions you should have learned by now 
to make that dialog happen.


How would you store the collection of items and their prices? What 
Python data types have you learned that you could use here?


How would you look up an item to get its price?

Show us your answers to any of the above, tell us exactly where you are 
stuck, and we will see what we can do to help.

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


[Tutor] Vending machine problem.

2014-04-01 Thread bob gailer

On 4/1/2014 3:26 AM, Sebastien Gomez wrote:

The vending machine must have 5 prices with items
it should accept 10p, 20p 50p and £1 coins
it should allow the user to purchase a item and give him a choice of 
purchasing something else. it should display the remaining credit once 
the item is purchased. i will let you know of anything else


Thank you. I am copying this to tutor@python.org where a bunch of us 
hang out and collectively help others. PLEASE in future always reply-all 
so a copy goes to the list.


I am changing the subject line to something meaningful.

This sounds like a homework assignment. We don't provide answers for 
homework. We will help you once you show some effort and tell us where 
you need a hand.


The requirements are kinda vague. I would have a hard time guessing 
exactly what the instructor is looking for.


Did you get any other information?

Did you get some sample of the expected input and output?

If no th the latter,  good starting place is to write down a sample 
dialog, then apply the Python functions you should have learned by now 
to make that dialog happen.


How do you plan to store the collection of items and their prices? What 
Python data types have you learned that you could use here?


How do you plan to look up an item to get its price?

Show us your answers to any of the above, tell us exactly where you are 
stuck, and we will see what we can do to help.

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


Re: [Tutor] How to create a sqlite table schema dynamically

2014-03-20 Thread bob gailer

On 3/19/2014 8:19 AM, Toni Fuente wrote:

Hello everyone,

I am stack with a problem that I can't find a solution:

I need to create a sqlite schema dynamically, I've got a dictionary with
text keys: RedHat, CentOS, SLES9,..., etc, etc

My intention was at the time of creating the table schema run a loop
through the dictionary keys and incorporate them to the schema:

for os in osDict.items():
cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT 
NULL, number INTEGER NOT NULL)''')
IMHO you are mixing data with column names. Usually the column name in 
this case would be just os.


What is your use case for this?

But I don't know how to pass the os key to the sqlite command.

Thank you in advance for any help,
Kind regards,




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


Re: [Tutor] improvements on a renaming script

2014-03-09 Thread bob gailer

On 3/9/2014 3:22 PM, street.swee...@mailworks.org wrote:

Hello all,

A bit of background, I had some slides scanned and a 3-character
slice of the file name indicates what roll of film it was.
This is recorded in a tab-separated file called fileNames.tab.
Its content looks something like:

p01 200511_autumn_leaves
p02 200603_apple_plum_cherry_blossoms

The original file names looked like:

1p01_abc_0001.jpg
1p02_abc_0005.jpg

The renamed files are:

200511_autumn_leaves_-_001.jpeg
200603_apple_plum_cherry_blossoms_-_005.jpeg

The script below works and has done what I wanted, but I have a
few questions:

- In the get_long_names() function, the for/if thing is reading
the whole fileNames.tab file every time, isn't it?  In reality,
the file was only a few dozen lines long, so I suppose it doesn't
matter, but is there a better way to do this?
The usual way is to create a dictionary with row[0] contents as keys 
and row[1] contents as values. Do this once per run. Then lookup each 
glnAbbrev in the dictionary and return the corresponding value.

- Really, I wanted to create a new sequence number at the end of
each file name, but I thought this would be difficult.  In order
for it to count from 01 to whatever the last file is per set p01,
p02, etc, it would have to be aware of the set name and how many
files are in it.  So I settled for getting the last 3 digits of
the original file name using splitext().  The strings were unique,
so it worked out.  However, I can see this being useful in other
places, so I was wondering if there is a good way to do this.
Is there a term or phrase I can search on?
I'm  sorry but I don't fully understand that paragraph. And why would 
you need to know the number of files?

- I'd be interested to read any other comments on the code.
I'm new to python and I have only a bit of computer science study,
quite some time ago.
Beware using tabs as indents. As rendered by Thunderbird they appear as 
8 spaces which is IMHO overkill.
It is much better to use spaces. Most Python IDEs have an option to 
convert tabs to spaces.


The Python recommendation is 4; I use 2.

#!/usr/bin/env python3

import os
import csv

# get longnames from fileNames.tab
def get_long_name(glnAbbrev):
with open(
  os.path.join(os.path.expanduser('~'),'temp2','fileNames.tab')
  ) as filenames:
filenamesdata = csv.reader(filenames, delimiter='\t')
for row in filenamesdata:
if row[0] == glnAbbrev:
return row[1]

# find shortname from slice in picture filename
def get_slice(fn):
threeColSlice = fn[1:4]
return threeColSlice

Writing a function to get a slice seems overkill also. Just slice in place.

# get 3-digit sequence number from basename
def get_bn_seq(fn):
seq = os.path.splitext(fn)[0][-3:]
return seq

# directory locations
indir = os.path.join(os.path.expanduser('~'),'temp4')
outdir = os.path.join(os.path.expanduser('~'),'temp5')

# rename
for f in os.listdir(indir):
if f.endswith(.jpg):
os.rename(
os.path.join(indir,f),os.path.join(
outdir,

get_long_name(get_slice(f))+_-_+get_bn_seq(f)+.jpeg)
)

exit()

HTH - remember to reply-all so a copy goes to the list, place your 
comments in-line as I did, and delete irrelevant text.

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


Re: [Tutor] i dont understand this code

2014-02-22 Thread bob gailer

On 2/22/2014 7:26 AM, piyush joshi wrote:


Can anyone help me out in understanding this code


Your question is kinda vague. Exactly what do you not understand?


#

import os

rotationMatrix1 = [7, 1, 5, 3, 0, 6, 2, 5, 2, 3, 0, 6, 1, 7, 6, 1, 5, 
2, 7, 1, 0, 3, 7, 6, 1, 0, 5, 2, 1, 5, 7, 3, 2, 0, 6]


rotationMatrix2 = [1, 6, 2, 5, 7, 3, 0, 7, 1, 6, 2, 5, 0, 3, 0, 6, 5, 
1, 1, 7, 2, 5, 2, 3, 7, 6, 2, 1, 3, 7, 6, 5, 0, 1, 7]


keyboardDict = {  2: '1',  3: '2',  4: '3',  5: '4',  6: '5',  7: 
'6',  8: '7',  9: '8', 10: '9', 11: '0',


 16: 'q', 17: 'w', 18: 'e', 19: 'r', 20: 't', 21: 'y', 
22: 'u', 23: 'i', 24: 'o', 25: 'p',


 30: 'a', 31: 's', 32: 'd', 33: 'f', 34: 'g', 35: 'h', 
36: 'j', 37: 'k', 38: 'l',


 44: 'z', 45: 'x', 46: 'c', 47: 'v', 48: 'b', 49: 'n', 
50: 'm' }


def keyboardEncToAscii(inKey):

out = 

for c in inKey:

if c == 0: return out

if c in keyboardDict: out += 
keyboardDict[c]


else: return 

return out

def decryptHash(hash, key, rotationMatrix):

outhash = []

for i in range(0, len(hash)):

outhash.append(((hash[i]  (rotationMatrix[7*key+i]))  0xFF) | 
(hash[i]  (8-rotationMatrix[7*key+i])))


return outhash

print()

print(hexa decimal code)

print(hexadecimal code from which the password can be calculated,)

print(07088120410C)

print()

print(Please enter the code: )

code = raw_input()

hash = []

for i in range(1, len(code) // 2):

hash.append(int(code[2*i]+code[2*i+1],16))

key = int(code[0:2], 16) % 5

password = keyboardEncToAscii(decryptHash(hash, key, rotationMatrix1))

if password == :

password = keyboardEncToAscii(decryptHash(hash, key, 
rotationMatrix2))


if password == :

print(The password could not be calculated. Bummer.)

else:

print(The password is:  + password)

if (os.name == 'nt'):

print(Press a key to exit...)

raw_input()




http://www.avast.com/   

This email is free from viruses and malware because avast! Antivirus 
http://www.avast.com/ protection is active.





___
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] Code runs in interpreter but won't output to stdout

2014-01-31 Thread bob gailer

On 1/29/2014 8:59 PM, scurvy scott wrote:

Please always reply to the tutor list so we can all play with your question.



On 1/28/2014 9:12 PM, scurvy scott wrote:

Hi guys, I'm trying to figure out why my code won't output to
terminal, but will run just fine in interpreter.
I'm using python 2.7.3 on Debian Linux/Crunchbang.

Here is my code.

import requests
from bs4 import BeautifulSoup as beautiful
import sys

def dogeScrape(username, password):
payload = {'username': username, 'password': password}
r = requests.post(http://dogehouse.org/index.php?page=login;,
data=payload)
soup = beautiful(r.text)
confirmed = str(soup.findAll('span',{'class':'confirmed'}))
print Confirmed account balance:  + confirmed[86:98]

dogeScrape(, )

It will output the confirmed. part, just not the confirmed
variable. It will output the entire thing in the interpreter.


I am stuck at import requests. Where did you get that module?

My guess is that you are getting a different response from the server. I 
suggest you write the entire response text to a file, then edit it 
looking for 'class=confirmed'.


I signed up at Dogehouse. What the heck is it? There is no explanation 
as to what it does or what I'd do with it!


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


Re: [Tutor] Code runs in interpreter but won't output to stdout

2014-01-29 Thread bob gailer

On 1/28/2014 9:12 PM, scurvy scott wrote:
Hi guys, I'm trying to figure out why my code won't output to 
terminal, but will run just fine in interpreter.

I'm using python 2.7.3 on Debian Linux/Crunchbang.

Here is my code.

import requests
from bs4 import BeautifulSoup as beautiful
import sys

def dogeScrape(username, password):
payload = {'username': username, 'password': password}
r = requests.post(http://dogehouse.org/index.php?page=login;, 
data=payload)

soup = beautiful(r.text)
confirmed = str(soup.findAll('span',{'class':'confirmed'}))
print Confirmed account balance:  + confirmed[86:98]

dogeScrape(, )

It will output the confirmed. part, just not the confirmed 
variable. It will output the entire thing in the interpreter.


Good reminder for everyone: be explicit about behavior. We wasted an 
iteration just to get this clarified.


The expression to be printed is the concatenation of Confirmed account 
balance:  with a slice of confirmed. Therefore confirmed is less that 
86 characters (or the slice is blank), therefore no output appears. 
Print the entire value of confirmed; that will tell us a lot.

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


Re: [Tutor] code works in windows command but not ubuntu terminal

2014-01-25 Thread bob gailer

On 1/24/2014 10:28 PM, bob gailer wrote:

Sorry for misspelling parens.

My reason for requesting the various names is that it makes 
communication clear, explicit and terse.


When someone says just brackets what does he actually mean?

For more grins see 
http://www.codinghorror.com/blog/2008/06/ascii-pronunciation-rules-for-programmers.html

and http://www.theasciicode.com.ar/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code works in windows command but not ubuntu terminal

2014-01-24 Thread bob gailer

On 1/24/2014 4:47 AM, Steven D'Aprano wrote:

Hi Tobias, and welcome.

On Thu, Jan 23, 2014 at 07:34:18PM -0700, Tobias Quezada wrote:

hello community,i am a newbie to python and program in general.
the script below works in python 2.7.3 on windows but not in the python 2.7.3 
ubuntu terminal.


fp=open(prez.dat,r)
x=fp.read
(print(x)

***i used fp for file pointer.I am using windows 7 and it works

Are you sure this is the *exact* same code you use on Windows 7? Because
it won't read the file, it will fail with a SyntaxError due to the
missing close bracket after the print.
This is Python 2.7.3, not 3.x. The error is due to a ( in front of the 
print statement.


And please call () parends and [] brackets, and{} braces. Saves a lot of 
confusion.


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


Re: [Tutor] Suggestion required on python as scripting language

2013-12-08 Thread bob gailer

On 12/8/2013 1:59 AM, Shankar Donepudi wrote:

Hi All,

I am working as test engineer in Networking in storage domain. We have 
decided to automate our testing and have chosen python for the same. 
We have basic knowledge on python so can anyone suggest good tutorials 
for writing automation scripts using python.
It might help if you were more specific. What are you testing? What in 
your domain does an automation script do?


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


Re: [Tutor] Automation

2013-11-03 Thread bob gailer

Always reply in such a way that a copy goes to the tutor list.

On 11/3/2013 5:56 PM, Renato Barbosa Pim Pereira wrote:

Solved:

for row in column:
   print row[0]

Sorry for my ignorance, by now, how can I locate the min/max value for 
the printed row?, thanks for patience.


Collect the elements in a list.
Apply min() and max() to the list.
Use list.index() to get the position of the value in the list.

Or write your own program to examine each value, tracking when it gets 
smaller (bigger) and also tracking the index where that change occurs,


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/30/2013 10:00 PM, Carmen Salcedo wrote:

 Hi Everyone,

hi

some guidelines for this list.
  post in plain text not html.
  tell us what version of Python you are using, what OS, what you use 
to edit and run the program.

  when replying:
reply-all so a copy goes to the list
put your responses following the relevant text
delete irrelevant text
if you get an exception (error) post the entire traceback. example:

File N:\foo.py, line 2, in module
2/0
ZeroDivisionError: division by zero

 I hope you're having a great week.  I'm working on this program that 
converts strings to integers. Can someone please help me out? :)


What kind of help do you want?
It is a lot easier for us and more profitable for you when you
  are specific
  tell us what kind of help you need
  did you run the program?
  what did you get and what did you expect?

Below is the program:

 def main():
 selection = input(Enter you choice. Enter 1  +
for Phone Translator or 2 for Backward String.)
 while selection != 1 and selection !=2:
 print Invalid choice
 selection = input(Please enter you selection. Enter 1  +
for Phone Translator or 2 for Backward String.)
 if selection == 1:
 phoneTranslator()
 elif selection == 2:
 backwardString()
 def phoneTranslator():
 print Phone Translator 
 phoneNumber = raw_input (Please enter the phone number: )
 phoneNumber = phoneNumber.upper()
 for n in phoneNumber:
 if str.isalpha(n):
 if n == A or n == B or n == C:
 n = 2
 elif n == D or n == E or n == F:
 n = 3
 elif n == G or n == H or n == I:
 n = 4
 elif n == J or n == K or n == L:
 n = 5
 elif n == M or n == N or n == O:
 n = 6
 elif n == P or n == Q or n == R or n == S:
 n = 7
 elif n == T or n == U or n == V:
 n = 8
 else:
 n = 9
 print str.isalpha()
 main()
 Thanks!! :)
 Carmen

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Dictionary from a text file

2013-10-31 Thread bob gailer

On 10/31/2013 2:16 AM, Nitish Kunder wrote:

I have a dictionary which is in this format
for ex:

{
'5x' : {
'50' : {
'update' : {
'update-from-esxi5.0-5.0_update01' : {
'call' : Update,
'name' : 'Update50u1',
'release' : '15/03/12'
},
'update-from-esxi5.0-5.0_update02' : {
'call' : Update,
'name' : 'Update50u2',
'release' : '21/12/12'
},
},
'patch' : {
'ESXi500-201109001' : {
'call' : Patch,
'name' :'Patch_501',
'release' : '13/09/11'
},
'ESXi500-20001' : {
'call' : Patch,
'name' :'ExpressPatch501',
'release' : '13/09/11'
},
},
},

[snip]
Does it have to be in a dictionary format? I'd rather use sqlite to 
store the data.


Also please give us a use case. There is probably a much simper and more 
elegant solution.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 6:49 AM, Carmen Salcedo wrote:

Hi,

I'm using python 2.7. I'm editing the program with idle. I use windows 8.

I finally got the string to convert to integers, however I can't 
figure out how to print them in this phone number format555-5678 
tel:555-5678.


The numbers are printing out this way.
5
5
5
5
6



Please post the new program.

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 7:52 AM, Carmen Salcedo wrote:
I'm not able to post it right now. All I did to the previous program i 
emailed was changed isalpha() to str.isalpha.

That does agree with what you posted or got.

The part of your original program that should print a character already is
print (str.isalpha()
which raises this exception:

  File N:\Script2.py, line 37, in phoneTranslator
print(str.isalpha())
TypeError: descriptor 'isalpha' of 'str' object needs an argument

it should be

print n

Exactly what did you type in response to
phoneNumber = raw_input (Please enter the phone number: )

Note you are not consistent in converting letters:
elif n == G or n == H or n == I:
n = 4
elif n == J or n == K or n == L:
n = 5
all the numbers should be characters e.g.
n = 5
etc.

There are many ways to get the desired output.
One is:
  collect the characters in one list, say numberList
  Then use slicing to insert the - e.g. numberList[3:3] = -
  Then print .join(numberList)

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 10:11 AM, Carmen Salcedo wrote:

Thanks Bob! :) A list is great idea. I'm just trying to figure out how to print 
the number across like a phone number 555- instead of downward. I'm stuck 
on that.


I repeat what I said before:


There are many ways to get the desired output.
One is:
   collect the characters in one list, say numberList
   Then use slicing to insert the - e.g. numberList[3:3] = -
   Then print .join(numberList)



--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 10:11 AM, Carmen Salcedo wrote:

I'm just trying to figure out how to print the number across like a phone 
number 555- instead of downward. I'm stuck on that.
  On further thought:


print %s%s%s-%s%s%s%s % tuple(numberList)

The % operator does formatting. Each %s is replaced by the next string 
in the tuple.


Just be sure you have exactly 7 characters in the list or this will fail.

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 2:51 PM, Carmen Salcedo wrote:

Thanks Bob! :) I'm very new at programming in Python. I appreciate your 
feedback.

Here are some improvements to consider:

import string
def main():
d = {1 : phoneTranslator, 2 : backwardString}  # map user 
selection to corresponding function

while True:
selection = raw_input(Enter you choice. Enter 1  +
   for Phone Translator or 2 for Backward String.)
operation = d.get(selection, None) # retrieve corresponding 
function or None

if operation: # did we get something?
operation() # call it
break # out of the while loop
print Invalid choice

def phoneTranslator():
trans = string.maketrans(ABCDEFGHIJKLMNOPQRSTUVWXYZ, 
222333444555666888)

print Phone Translator 
phoneNumber = raw_input (Please enter the phone number: ).upper()
phoneNumber = phoneNumber.translate(trans)
print phoneNumber[:3] + - + phoneNumber[3:]

def backwardString():
print not implemented

main()

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Geometric sequence

2013-10-30 Thread bob gailer

On 10/30/2013 1:08 PM, Peter O'Doherty wrote:

Hi List,

I know a geometric sequence can be produced by:

series = [2**x for x in range(7)]

But I would like to curtail the sequence before the last element 
excedes a certain value.

import itertools
series = [2**x for x in itertools.takewhile(lambda x: 2**x60, range(7))]

if the limit is really large you could calculate it once:

import itertools
import math
limit =  int(math.log(60)) + 1
series = [2**x for x in itertools.takewhile(lambda x:xlimit, range(7))]

which in turn leads to:

import math
series = [2**x for x in range(int(math.log(60)) + 2)]

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Python String Help

2013-10-29 Thread bob gailer

On 10/28/2013 4:55 PM, Alex Tenno wrote:

Hey everyone,

Hey back.


I'm encountering a problem with a python function that I am supposed 
to create.

What is the problem? You have not told us that!

What class is this for? I guess either the class is not the right one 
for you (over your head) or the class is just a dud, or you got behind. 
It will help us if you explain your circumstances.


Also we like to see any effort you have put into solving the problem.

What version pf Python? What Operating System? What do you use to write 
your programs? How do you run them?


I want my function to look at a string, and then replace each letter 
in the string with its relative position in the alphabet. for example, 
'abcde' would return '12345', 'zabd' would return '4123', and 'xpft' 
would return '4213'. I have been given hints that tell me You may 
want to iterate over the letters ch in s as in the for loop above, and 
inside that for loop, count the number of letters that are in s and 
come before the loop variable ch. You will also need an accumulator to 
build the permutation the function will return.



--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] UnicodeDecodeError while parsing a .csv file.

2013-10-28 Thread bob gailer

On 10/28/2013 6:13 PM, SM wrote:
 Hello,
Hi welcome to the Tutor list

 I have an extremely simple piece of code

which could be even simpler - see my comments below

 which reads a .csv file, which has 1000 lines of fixed fields, one 
line at a time, and tries to print some values.


   1 #!/usr/bin/python3
   2 #
   3 import sys, time, re, os
   4
   5 if __name__==__main__:
   6
   7 ifd = open(infile.csv, 'r')

The simplest way to discard the first line is to follow the open with
8 ifd.readline()

The simplest way to track line number is

10 for linenum, line in enumerate(ifd, 1):

  11 line1 = line.split(,)

FWIW you don't need re to do this split

  12 total = 0
  19 print(LINE: , linenum, line1[1])
  20 for i in range(1,8):
  21 if line1[i].strip():
  22 print(line[i] , int(line1[i]))
  23 total = total + int(line1[i])
  24 print(Total: , total)
  25
  26 if total = 4:
  27 print(POSITIVE)
  28 else:
  29 print(Negative)
  31 ifd.close()

That should have () after it, since it is a method call.

 It works fine till  it parses the 1st 126 lines in the input file. 
For the 127th line (irrespective of the contents of the actual line), it 
prints the following error:

 Traceback (most recent call last):
   File p1.py, line 10, in module
 for line in ifd:
   File /usr/lib/python3.2/codecs.py, line 300, in decode
 (result, consumed) = self._buffer_decode(data, self.errors, final)
 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 
1173: invalid continuation byte
Do you get exactly the same message irrespective of the contents of the 
actual line?


Code points larger than 127 are represented by multi-byte sequences, 
composed of a leading byte and one or more continuation bytes. The 
leading byte has two or more high-order 1s followed by a 0, while 
continuation bytes all have '10' in the high-order position.


This suggests that a byte close to the end of the previous line is 
leading byteand therefore a continuation byte was expected but where 
the 0xe9was found.


BTWhen I divide 1173 by 126 I get something close to 9 characters per 
lne. That is not possible, as there would have to be at least 16 
characters in each line.


Best you send us at least the first 130 lines so we can play with the file.

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Want to keep to two decimal places for currency

2013-10-24 Thread bob gailer

On 10/24/2013 2:09 PM, Danny Yoo wrote:
Related: I saw a picture the other day on Google+ of an mailing 
envelope whose zip code was written in scientific notation.

That;s odd - since ZIP codes are character, not integer,

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] [OT] Programming practice was: Re: string list in alphabetical!

2013-10-22 Thread bob gailer
I am glad we are having this discussion. It helps me understand the 
plight of some of our posters.


I had the benefit of a good school system, plus attending a technical 
high school and a college of engineering.


In the early 90's I was an adjunct professor at the University of 
Denver's University College - evening school for adults seeking an 
MBA. Each class met for 2 hours once a week for 5 weeks. No labs. My job 
was to teach Pascal as a first programming language. My students had 
taken one prerequisite - Introduction To Programming. I built my class 
based on the students' having met the prerequisite. One class of mine 
were struggling with certain fundamental concepts. Turns out the Intro 
class had failed to do its job! One outcome is that I was fired for 
failing to teach Pascal.


BTW Python did not exist then, and I have always disliked Pascal.

As adjunct professor for a similar program at Regis University (Denver) 
I was given an Analysis class to teach. My supervisor created a brand 
new course. The first time I saw the materials was the first night of 
the class! No one had a chance to examine the materials beforehand! That 
class was -`difficult for me and the students.


On the bright side in the 80's I taught daytime adult classes in 
computing for the Boeing company. I was free to change classes that had 
poor materials to (IMHO) good materials. It was almost always fun and I 
almost always got really good evaluations.


I recall one student struggling with his first Basic program. I 
recommended he walk thru it line by line, and I demonstrated that 
technique. Amazed he exclaimed In that much detail?.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Tutor] string list in alphabetical!

2013-10-21 Thread bob gailer

On 10/21/2013 12:16 PM, Siva Cn wrote:

Hi Sammy,

Try this this may help you !

--
def sort_file1_to_file2(file1, file2):
.
input_content = []
with open(file1, 'r') as fp:
input_content = fp.read()

input_content = input_content.splitlines()

_dict = {ele[0].lower(): ele for ele in input_content}

out_content = \n.join([_dict[chr(idx)]
 for idx in range(97, 123)
 if chr(idx) in _dict])

with open(file2, 'w') as fp:
fp.write(out_content)

sort_file1_to_file2('file1.txt', 'file2.txt')

I am surprised to see this program. It seems unnecessarily complex and 
somewhat hard to read.

Especially for a rank beginner (the OP)
Also has an unnecessary statement (input_content = [])

IMHO it is more customary and a lot simpler to process the  lines in a 
file thusly:


  for line in open(file1, 'r'):
process the line

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Cannot understand object initiation

2013-10-12 Thread bob gailer

On 10/12/2013 11:01 AM, Kush Goyal wrote:

[[snip]
user = User.query.filter_by ( username = self.username.data ).first()

now this I do not understand.

Can a object be create by using a method of a class instead of the
class consturctor? I

Without seeing the code you reference (User module) I can hazard a guess:

This code is not creating an object - it is returning a reference to an 
existing object.


The key to the object is username, and first() returns the first 
instance should there be more than one,


User is some objectimported from myapplication.models.
query is a callable object that is an attribute of User.
filter_by is a callable object that is an attribute of query.
first is a callable object that is an attribute of filter_by.
Nothing in the above suggests object creation.

HTH

--
Bob Gailer
919-636-4239
Chapel Hill NC

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