Re: [Tutor] Is it possible to...

2005-07-10 Thread Alan G
> I was just wondering if it is possible to use Python as a language 
> to password protect a webpage? 

Yes it is possible but you will need to have a web server that can 
run Pyhon and there aren't too many of those on the internet...

OTOH if its a privately owned web server then password protection 
is usually a standard configuration item of the web server, you 
just edit a file and tell it to password protect a particular 
file or folder. Certainly Apache and Xitami work like that, 
no coding needed.

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can I use def without ( ) at the end?

2005-07-10 Thread Alan G
Nathan,

>  How do I make Python get a def? Is it the "get" function, or 
> something
>  else? I need to know so that I can get a def for that computer
>  MasterMind(tm) game that I'm writing.

This sounds like you really don't understand what def does.
Can I suggest you take time out to read about functions in one
of the tutorials, it will likely save a lot of time in the long run.

You can try my tutorial "Modules and Functions" is the topic,
or the official tutorial, or virtually any other.

>  BTW, I took your advice, and wrote some definitions for my Giant
>  Calculator program.

def is not a definition in the general sense, it is a function
definition. You call functions with parens and get a result back.
Your earlier questions showed that you don't really understand
that concept yet.

>  Might make the code easier to read, but harder to code
>  because I have to keep going to the top to read the menu. Not that 
> fun,

If your editor supports split screens (eg. emacs, vim)  then you
can simply do that and have the top 'frame' display the menu.

Other common tricks include setting a bookmark at the menu and
using the goto bookmark feature(if you have one) to jump straight
there and then go to bottom to get back to your new code.

If you have a folding editor like Scite (or Pythonwin) then
you can collapse all definitions except the menu and the one you are
working on which is often enough too.

Finally you can always open two editor sessions on the same file,
one for reading and one for working in.

Lots of options depending on your tools.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's going on with this code? Error message supplied.

2005-07-10 Thread Alan G
Nathan,

> Subject: [Tutor] What's going on with this code? Error message 
> supplied.
>

> Here is the error message:
>
> Traceback (most recent call last):
>  File "D:\GC.py", line 67, in ?
>if option == 1:
> NameError: name 'option' is not defined

The error message tells you what is wrong, option is not defined at 
the
point where you are using it. Pythopn starts executing code from the 
top
so when it comes to your line

if option == 1

it doesn't know about anything called option, you haven't created it 
yet.
In fact you only ever create it inside the main_menu() function. But 
names
created inside functions are only seen inside the function  - they are
called "local" because they are localised to the function. You need
to create a variable outside the function, then return the value from
the function to that variabl;e like this:

option = main_menu()   # assign the value thus creating option
if option == 1:# now you can test it


But your program has another problem.

> print main_menu()

main_menu is a function which prints a menu. You do not need to
use print here. There are print commands inside the function.
In fact what this says is print the return value of main_menu()
and, as it stands, you don't have a return value so Python will
print 'None', which you don't want.

> def main_menu():
>print "OPTIONS MENU"
>print "1) Calculate"
> ...
>print "5) Quit"
>option = input("What option would you like:" )
 return option

And finally to get my code above to work you need to return
the option value as shown above.

You might want to rethink using input() too sibnce it has some
security issues,

option = int(raw_input())

is safer and for youur purposes does the same thing.

Take some time to work through a tutorial, that should explain these
issues. In the long run it will be faster than writing code and
posting every problem here, then waiting for an answer!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looks like Giant Calc is a bust.

2005-07-10 Thread Alan G
> The Giant Calculator runs now, just not as I want it to. 
> I can't seem to get it past the main menu. 

See my other post. You are never returning the choice from 
the function so option is never changed from 0...

--
option = 0

def main_menu():
   print "OPTIONS MENU"
   print "1) Calculate"
   print "2) Shapes"
   print "3) Temperature"
   print "4) Formulas"
   print "5) Quit"
   option = input("What option would you like:" ) 


#Code for main part of program.
print main_menu()
if option == 1:
--

You have created an option variable but you never change it.
you need to set option to the return value from main_menu()
and modify main_menu() to return the value.

One other option, but its bad proctice, is to declare option 
as global inside main_menu(), but returning the value is 
much better.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] UnicodeDecodeError when copying files with Umlauten

2005-07-10 Thread Severin Kacianka
Hello, 

I finally could solve the problem on my own. These two articles helped me a 
lot:
http://www.onlamp.com/pub/a/python/excerpt/pythonckbk_chap1/
http://www.reportlab.com/i18n/python_unicode_tutorial.html

I simply had to ensure that all the file names I got from the m3u file were in 
unicode format. I do that by simply running "unicode" over every filename I 
extract from the m3u files:
self.pathList.append(unicode(eachLine[:-1],"latin-1"))

Severin
-- 
They that can give up essential liberty to obtain a little temporary safety 
deserve neither liberty nor safety.
Benjamin Franklin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Learning Python with a Simple IM

2005-07-10 Thread Jorge Louis De Castro




Hello,
 
I am a Java Developer that wants to learn 
Python by doing. I am loving this initial vibe I'm getting 
out of Python. However, because I feel programmers of a 
certain languages bring with them certain vices when moving to other 
languages, I'd like to have feedback from seasoned Python programmers regarding 
my code.
Using some socket examples I've googled here and 
there I wrote the very simple Instant-Messaging-wannabe program below. I 
was advised to post the code here and get feedback from this 
community.
In my next iteration with this code I'll 
be changing the client to include a server thread listening instead of 
polling the server.
 
Regards
jorge
 
 
THE SIMPLE IM CLIENT
 
import socket, threading, time, msvcrt
 
print "Please enter the following 
information"_url = raw_input("URL: ")_port = raw_input("Port: 
")print "Starting IIM client on port: " + _port
 
socketOut = socket.socket(socket.AF_INET, 
socket.SOCK_STREAM)socketOut.connect((_url, int(_port)))
 
# clear screen here
 
print "Enter your user details"_from = 
raw_input("User id: ")_to = raw_input("Buddy id: ")
 
print '\n'print "Connecting to 
server..."print '\n'
 
# send user details and receive 
responsesocketOut.sendall('@@@'+_from+'##'+_to)response 
= socketOut.recv(8192)
 
def listener():    while 
1:    
time.sleep(5)    
socketOut.sendall('$$$'+_from)    
response = socketOut.recv(8192)    if 
response != " 
":    print 
"\n" + response
 
if response == 'AUTH_OK':    data = 
""    th = 
threading.Thread(target=listener)    
th.setDaemon(1)    th.start()    print 
"Background polling thread started"    while 1:
 
    if 
msvcrt.kbhit():    
ch = msvcrt.getche()    
else:    ch = 
None    if 
ch:    if ch 
!= 
'\r':    
data += ch    
else:    
print 
'\n'    
socketOut.sendall('###'+_from+'##'+data)    
response = 
socketOut.recv(8192)    
if response != " 
":    
print 
response    
data = ""
 
else:    print "Auhentication 
failed!"    
socketOut.close()
 
 
 
 
THE SIMPLE IM SERVER
 
import SocketServer
 
_port = 8881_clients = {}
 
# a connected clientclass Client:    # queue of 
messages sent to this client    queue = 
[]    def __init__(self, _sock, _src, 
_dest):    print "Creating IM 
client"    self.socket = 
_sock    print "Incoming socket: %s" 
% self.socket    self.user = 
_src    print "Username: " + 
self.user    # buddies should be a 
list    self.buddy = 
_dest    print "Buddy: " + 
self.buddy    print "Created IM 
client"
 
# the server handling requestsclass 
Broker(SocketServer.BaseRequestHandler):    def 
handle(self):    print "Connected 
from", self.client_address    while 
True:    
receivedData = 
self.request.recv(8192)    
if not 
receivedData:    
break    
    # if 
handshake packet, extract client 
details    if 
receivedData.startswith('@@@',0,3):    
print "Received handshake 
packet"    
# strip handshake 
code    
receivedData = receivedData.replace('@@@', 
'', 
1).lstrip()    
l = 
receivedData.split('##',1)    
socket = 
self.request    
src = 
"">    
dest = 
l[1]    
c = Client(socket, src, 
dest)    
# use username as key on 
hashmap    
_clients[src] = 
c    
# send success 
message    
socket.sendall('AUTH_OK')    
print "Client " + src + " authenticated"
 
    # if 
polling packet, extract sender details and send 
messages    
if 
receivedData.startswith('$$$',0,3):    
# strip polling 
message    
print "Received polling 
packet"    
src = "" '', 
1).lstrip()    
# only poll if more than 1 
user    
if len(_clients) > 
1:    
    
# use username as key on 
hashmap    
_clients[src] = 
c    
if len(c.queue) < 
1:    
c.socket.sendall(" 
")    
else:    
msgs = 
""    
for q in 
c.queue:    
msgs += q + 
'\n'    
# send queued 
messages    
c.socket.sendall(msgs)    
c.queue = 
[]    
print "Sent all pending messages for " + 
c.user    
else:    
socket.sendall(" ")
 
    # if 
message packet, extract data and append to target 
queue    if 
receivedData.startswith('###',0,3):    
print "Received message 
packet"    
receivedData = receivedData.replace('###', '', 
1).lstrip()    
l = 
receivedData.split('##',1)    
src = 
"">    
text = 
l[1]   

Re: [Tutor] Is it possible to...

2005-07-10 Thread Byron
Alan G wrote:

>> I was just wondering if it is possible to use Python as a language to 
>> password protect a webpage?   
>
>
> Yes it is possible but you will need to have a web server that can run 
> Pyhon and there aren't too many of those on the internet...
>  
>

However, there are some hosters that do allow Python scripts.  If you 
search google for "web hosters" + Python, you will find a variety of 
them.  One that looks interesting is:  
http://www.synergyconnect.com/Linux_Plans/Linux/Linux_Web_Hosting_Plans/


> OTOH if its a privately owned web server then password protection is 
> usually a standard configuration item of the web server, you just edit 
> a file and tell it to password protect a particular file or folder. 
> Certainly Apache and Xitami work like that, no coding needed.
>

I agree.  This is by far, the best option -- however, if Nathan is 
wanting to learn how to password protect a page using Python technology, 
I would recommend that he check out the following page:

http://www.devshed.com/c/a/Python/Python-on-the-Web/

HTHs,

Byron
---


-- 
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.323 / Virus Database: 267.8.11/44 - Release Date: 7/8/2005

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's going on with this code? Error message supplied.

2005-07-10 Thread Byron
Hi Nathan,

It appears that you are just starting to learn the Python programming 
language.  May I suggest that you check out the following FREE resources 
-- they will help to get you started and running smoothly with Python.

Learning With Python
http://www.greenteapress.com/thinkpython/

After you have gone though that tutorial, I would then recommend the 
following advanced materials:
http://www.devshed.com/c/b/Python/

HTHs (Hope this helps),

Byron
---



-- 
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.323 / Virus Database: 267.8.11/44 - Release Date: 7/8/2005

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Learning Python with a Simple IM

2005-07-10 Thread Alan G
Hi Jorge,

> I am a Java Developer that wants to learn Python by doing.
> I am loving this initial vibe I'm getting out of Python.
> However, because I feel programmers of a certain languages
> bring with them certain vices when moving to other languages,

Absolutely right, thats why its good to learn several languages
- to see the world from different angles! ;-)

> print "Please enter the following information"
> _url = raw_input("URL: ")

Using an underscore in front of a variable is usually done in a class 
to
make the member "invisible" - a wee bit like private in Java, but
much less rigorous. Its not often used for normal variables in a 
program.

> print '\n'
> print "Connecting to server..."
> print '\n'

Using a tripple quioted string might be easier here:

print '''
Connecting to seerver
'''

>def listener():
>while 1:
>time.sleep(5)
>socketOut.sendall('$$$'+_from)
>response = socketOut.recv(8192)
>if response != " ":
>print "\n" + response

There is no break in this loop so it will run forever.
That might be what you want, but usually I'd put some kind of
breakout mechanism even on a long running server daemon.

>if msvcrt.kbhit():
>ch = msvcrt.getche()

I may be wrong but I don;t think you need the kbhit() function,
getch[e]() will block and wait for a keypress.

>else:
>ch = None

Which in turn means ch should never be None...
Although it might never exist if kbhit is not True since getche
will never be called and thus ch will never be created!

Alan G.
(Recovering from G8 riots 300m from his house!)

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's the invalid syntax? [What's the error mesaage?]

2005-07-10 Thread Nathan Pinno
  I fixed this bug by myself, I had forgotten to add a print on a line by 
itself.
  - Original Message - 
  From: "Danny Yoo" <[EMAIL PROTECTED]>
  To: "Nathan Pinno" <[EMAIL PROTECTED]>
  Cc: 
  Sent: Sunday, July 10, 2005 12:29 AM
  Subject: Re: [Tutor] What's the invalid syntax? [What's the error 
mesaage?]


  >
  >
  > On Sat, 9 Jul 2005, Nathan Pinno wrote:
  >
  >> What's the invalid syntax?
  >>
  >> Here's the code (Part of my Guess the Numbers game):
  >>
  >> if a0 == x0 and a1 == x1 and a2 == x2 and a3 == x3:
  >> print "Congratulations! Way to go?"
  >> answer = raw input("Play again: (Y)es or (N)o Type the 
letter of your choice. ")
  >
  >
  > Hi Nathan,
  >
  > Next time you ask this kind of question, show us the error message.
  > Brian has asked you before on other questions in the past; his
  > recommendation is a good one in general.
  >
  > Error message are not content-less, despite what you might think.  They
  > usually have some kind of useful information associated with them, and
  > they they really often provide key clues to what's broken.
  >
  >
  > Let's try an example to demonstrate this idea.  Let's say that we write 
a
  > program like this:
  >
  > ##
  > def test_syntax_error():
  >print "hello world"
  >goodbye world
  > ##
  >
  > When we run this, Python says that there's a problem here.  But it
  > actually says more than "it doesn't work"; it gets specific:
  >
  > ##
  >  File "", line 3
  >goodbye world
  >^
  > SyntaxError: invalid syntax
  > ##
  >
  > Python is saying: "Up to line 2 of the program, things look 
syntactically
  > ok.  I, the Python system, hit a problem on line three.  Here, I'll show
  > the line to you; maybe you'll see what's wrong immediately.  Look around
  > there for the syntax error.  If it helps here's more info: I got 
confused
  > as soon as I saw the word 'world'; I was not expecting that word there."
  >
  > Of course, if Python really did say something like that in full English,
  > it would be too verbose.  So it does take some practice in reading
  > something terse like an error message, and actually understanding what 
it
  > means.  But many of us on the tutor list have that experience.
  >
  > I hope this makes it clear: if you see an error message, include it!
  > It's actually really useful for us when we try to help you with 
problems.
  >
  >
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another newbie question from Nathan.

2005-07-10 Thread Nathan Pinno
  Hi all,

  How do I make Python get a def? Is it the "get" function, or something

else? I need to know so that I can get a def for that computer 
MasterMind(tm) game that I'm writing.

  BTW, I took your advice, and wrote some definitions for my Giant 
Calculator program. Might make the code easier to read, but harder to
code 
because I have to keep going to the top to read the menu. Not that fun,
but 
necessary for a smooth program, I guess.

  Nathan Pinno

  "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
  > On Sat, 02 Jul 2005 00:25:00 -0600, Nathan Pinno wrote:
  >>   Hi all.
  >>   How do I make the computer generate 4 random numbers for the
guess? I 
want
  >> to know because I'm writing a computer program in Python like the
game
  >> MasterMind.
  > First you get the computer to generate one random number. Then you
do it
  > again three more times.
  > If you only need to do it once, you could do it this way:
  > import random  # you need this at the top of your program
  > x0 = random.random()
  > x1 = random.random()
  > x2 = random.random()
  > x3 = random.random()
  > But if you need to do it more than once, best to create a function
that
  > returns four random numbers in one go.
  > def four_random():
  >"""Returns a list of four random numbers."""
  >L = []  # start with an empty list
  >for i in range(4):
  >L.append(random.random())
  >return L
  > and use it this way:
  > rand_nums = four_random()
  > # rand_nums is a list of four numbers
  > print rand_nums[0]  # prints the first random number
  > print rand_nums[3]  # prints the last one
  > or like this:
  > alpha, beta, gamma, delta = four_random()
  > # four names for four separate numbers
  > Steven.
  > http://mail.python.org/mailman/listinfo/python-list


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's going on with this code? Error message supplied.

2005-07-10 Thread Nathan Pinno
  Here's an error message:

File "D:\GC.py", line 78
  cal_opt = cal_menu()
  ^
  SyntaxError: invalid syntax

  The relevant code:

  option = main_menu()
  if option == 1:
  cal_menu()
  cal_opt = cal_menu()
  if cal_opt == 1:

  How do I fix this error?

  Nathan
  - Original Message - 
  From: "Alan G" <[EMAIL PROTECTED]>
  To: "Nathan Pinno" <[EMAIL PROTECTED]>; 
  Sent: Sunday, July 10, 2005 2:16 AM
  Subject: Re: [Tutor] What's going on with this code? Error message 
supplied.


  > Nathan,
  >
  >> Subject: [Tutor] What's going on with this code? Error message
  >> supplied.
  >>
  >
  >> Here is the error message:
  >>
  >> Traceback (most recent call last):
  >>  File "D:\GC.py", line 67, in ?
  >>if option == 1:
  >> NameError: name 'option' is not defined
  >
  > The error message tells you what is wrong, option is not defined at
  > the
  > point where you are using it. Pythopn starts executing code from the
  > top
  > so when it comes to your line
  >
  > if option == 1
  >
  > it doesn't know about anything called option, you haven't created it
  > yet.
  > In fact you only ever create it inside the main_menu() function. But
  > names
  > created inside functions are only seen inside the function  - they are
  > called "local" because they are localised to the function. You need
  > to create a variable outside the function, then return the value from
  > the function to that variabl;e like this:
  >
  > option = main_menu()   # assign the value thus creating option
  > if option == 1:# now you can test it
  >
  >
  > But your program has another problem.
  >
  >> print main_menu()
  >
  > main_menu is a function which prints a menu. You do not need to
  > use print here. There are print commands inside the function.
  > In fact what this says is print the return value of main_menu()
  > and, as it stands, you don't have a return value so Python will
  > print 'None', which you don't want.
  >
  >> def main_menu():
  >>print "OPTIONS MENU"
  >>print "1) Calculate"
  >> ...
  >>print "5) Quit"
  >>option = input("What option would you like:" )
  > return option
  >
  > And finally to get my code above to work you need to return
  > the option value as shown above.
  >
  > You might want to rethink using input() too sibnce it has some
  > security issues,
  >
  > option = int(raw_input())
  >
  > is safer and for youur purposes does the same thing.
  >
  > Take some time to work through a tutorial, that should explain these
  > issues. In the long run it will be faster than writing code and
  > posting every problem here, then waiting for an answer!
  >
  > Alan G
  > Author of the Learn to Program web tutor
  > http://www.freenetpages.co.uk/hp/alan.gauld
  >
  >
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Why does my code show this?

2005-07-10 Thread Nathan Pinno




  Hey all,
   
  Thought I'd try a mini-calc. Here's the code:
   
  # This is a small calculator.print "Mini Calculator"print "By 
  Nathan Pinno"printprint "CALCULATE MENU"print "1) Add"print 
  "2) Subraction"print "3) Multiplication"print "4) Division w/o 
  remainder"print "5) Division with remaider"print "6) 
  Exponation"print "7) Square roots"print "8) Exit"cal_opt = 
  int(raw_input("What option would you like: "))if cal_opt == 
  "1":    X = input("First number:" )    Y 
  = input("Second number:" )    print X, "+", Y, "= ",X + 
  Y    cal_opt = int(raw_input("Option: "))elif cal_opt 
  == "2":    X = input("First number:" 
  )    Y = input("Second number:" )    
  print X, "-", Y, "= ",X - Y    cal_opt = 
  int(raw_input("Option: "))elif cal_opt == "3":    X = 
  input("First number:" )    Y = input("Second number:" 
  )    print X, "*", Y, "= ",X * Y    
  cal_opt = int(raw_input("Option: "))elif cal_opt == 
  "4":    X = input("First number:" )    Y 
  = input("Second number:" )    if Y == 
  0:    print "Division by zero ot 
  allowed!"    Y = input("Second 
  number:" )    
  else:    print X, "/", Y, "= ",X / 
  Y    cal_opt = 
  int(raw_input("Option: "))elif cal_opt == "5":    X = 
  input("First number:" )    Y = input("Second number:" 
  )    if Y == 
  0:    print "Division by zero ot 
  allowed!"    Y = input("Second 
  number:" )    
  else:    print X, "/", Y, "= ",X / 
  Y," R ", X % Y    cal_opt = 
  int(raw_input("Option: "))elif cal_opt == "6":    X = 
  input("First number:" )    Y = input("Power:" 
  )    print X, "**", Y, "= ",X**Y    
  cal_opt = int(raw_input("Option: "))elif cal_opt == 
  "7":    X = input("Number to find the square root of:" 
  )    print "The square root of", X, " = 
  ",X**0.5    cal_opt = int(raw_input("Option: "))elif 
  cal_opt == "8":    print 
  "Goodbye!"else:    print "That's not an option. Try 
  again."    cal_opt = int(raw_input("Option: "))
  Here is the screen output:
   
  Mini CalculatorBy Nathan Pinno
   
  CALCULATE MENU1) Add2) Subraction3) Multiplication4) 
  Division w/o remainder5) Division with remaider6) Exponation7) 
  Square roots8) ExitWhat option would you like: 7That's not an 
  option. Try again.Option: 33*412>>> 
   
  Why does it run this way instead of going to the proper equation?
   
  Appreciating the help so far,
  Nathan Pinno

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why does my code show this?

2005-07-10 Thread geon




Nathan Pinno napsal(a):

  
  
  
  
cal_opt = int(raw_input("What option would you like: "))
if cal_opt == "1":
       ..

  



your problem is in these two lines (and even more, but if you solve
this, the others you get for free).
try run just these two lines and guess, think about what kind of
variable is  in cal_opt.



  
elif cal_opt == "2":
    X = input("First number:" )
    Y = input("Second number:" )
    print X, "-", Y, "= ",X - Y
    cal_opt = int(raw_input("Option: "))

  

the other trouble might be on the last line - note that "if" is not
"while". :-)

before creating your own program would be better to go through some
nice tutorial,  to get some experience.

nice pytime
geon



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another newbie question from Nathan.

2005-07-10 Thread Adam Bark
If I understand your problem correctly all you need to do is use the name of the function to call it ie:

def func():
    print "hello world"

func()

would give the output

"hello world"On 7/10/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
  Hi all,  How do I make Python get a def? Is it the "get" function, or somethingelse? I need to know so that I can get a def for that computerMasterMind(tm) game that I'm writing.  BTW, I took your advice, and wrote some definitions for my Giant
Calculator program. Might make the code easier to read, but harder tocodebecause I have to keep going to the top to read the menu. Not that fun,butnecessary for a smooth program, I guess.  Nathan Pinno
  "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in messagenews:[EMAIL PROTECTED]  > On Sat, 02 Jul 2005 00:25:00 -0600, Nathan Pinno wrote:
  >>   Hi all.  >>   How do I make the computer generate 4 random numbers for theguess? Iwant  >> to know because I'm writing a computer program in Python like thegame  >> MasterMind.
  > First you get the computer to generate one random number. Then youdo it  > again three more times.  > If you only need to do it once, you could do it this way:  > import random  # you need this at the top of your program
  > x0 = random.random()  > x1 = random.random()  > x2 = random.random()  > x3 = random.random()  > But if you need to do it more than once, best to create a functionthat  > returns four random numbers in one go.
  > def four_random():  >"""Returns a list of four random numbers."""  >L = []  # start with an empty list  >for i in range(4):  >L.append
(random.random())  >return L  > and use it this way:  > rand_nums = four_random()  > # rand_nums is a list of four numbers  > print rand_nums[0]  # prints the first random number
  > print rand_nums[3]  # prints the last one  > or like this:  > alpha, beta, gamma, delta = four_random()  > # four names for four separate numbers  > Steven.  > 
http://mail.python.org/mailman/listinfo/python-list___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] adding quotation marks around variables

2005-07-10 Thread Robert



Hello all, I am a college student and I am currently 
working on a two numbers program for our class, The purpose of this program is 
to take user input and do some math functions. 
 
I have figured out how to do the math but I need to 
display these two variables with quotation marks around them. 
 
Also I need to add these two variables together 
 and display the hexadecimal of these two variables???
 
Also how do you display wheather one variable is greater 
than or less than or equal to the other variable?
 
 
Below is an example of the items i need help 
with?
 


The two numbers were "X" and 
"Y." The first number was (< > =) the second number. 
The hexadecimal sum of the two numbers is XXX.
 
Any help with this would be gratly appreciated! 

Thanks 
Robert
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding quotation marks around variables

2005-07-10 Thread jfouhy
Quoting Robert <[EMAIL PROTECTED]>:

> I have figured out how to do the math but I need to display these two
> variables with quotation marks around them. 
> 
> Also I need to add these two variables together and display the
> hexadecimal of these two variables???
> 
> Also how do you display wheather one variable is greater than or less
> than or equal to the other variable?

Hi Robert,

I recommend you have a look through the online Python tutorial
(http://python.org/doc); in particular, section 3:
http://docs.python.org/tut/node5.html

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding quotation marks around variables

2005-07-10 Thread Brian van den Broek
Robert said unto the world upon 10/07/2005 17:31:
> Hello all, I am a college student and I am currently working on a
> two numbers program for our class, The purpose of this program is
> to take user input and do some math functions.
> 
> I have figured out how to do the math but I need to display these
> two variables with quotation marks around them.
> 
> Also I need to add these two variables together  and display the
> hexadecimal of these two variables???
> 
> Also how do you display wheather one variable is greater than or
> less than or equal to the other variable?
> 
> 
> Below is an example of the items i need help with?
> 
> 
> 
> 
> 
> 
> The two numbers were "X" and "Y."
> 
> The first number was (< > =) the second number.
> 
> The hexadecimal sum of the two numbers is XXX.
> 
> Any help with this would be gratly appreciated! Thanks Robert
> 


Hi Robert,

for displaying strings with variable content, string formatting is a 
real boon. See  for 
details.

But here is a bit to give you the idea:

 >>> def silly_example():
name = raw_input('What is your name?\n')
if name[0].isalpha():
if name[0].lower() in ('aeiou'):
char_type = 'a vowel'
else:
char_type = 'a consonant'
else:
char_type = "something other than a letter"
print "Hello, %s. Your name begins with %s." %(name, char_type)


 >>> silly_example()
What is your name?
Brian
Hello, Brian. Your name begins with a consonant.
 >>> silly_example()
What is your name?
Alberto
Hello, Alberto. Your name begins with a vowel.
 >>> silly_example()
What is your name?
42
Hello, 42. Your name begins with something other than a letter.
 >>>


See if you can get somewhere with these ideas. If you get stuck, post 
some code, and someone will be glad to help more.

Best,

Brian vdB


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding quotation marks around variables

2005-07-10 Thread Brian van den Broek
Robert said unto the world upon 10/07/2005 17:31:
> Hello all, I am a college student and I am currently working on a two numbers 
> program for our class, The purpose of this program is to take user input and 
> do some math functions. 
> 
> I have figured out how to do the math but I need to display these two 
> variables with quotation marks around them. 
> 
> Also I need to add these two variables together  and display the hexadecimal 
> of these two variables???
> 
> Also how do you display wheather one variable is greater than or less than or 
> equal to the other variable?
> 
> 
> Below is an example of the items i need help with?
> 
> 
> 
> 
> The two numbers were "X" and "Y." 
> 
> The first number was (< > =) the second number. 
> 
> The hexadecimal sum of the two numbers is XXX.
> 
> Any help with this would be gratly appreciated! 
> Thanks 
> Robert
> 

Darn, overlooked the desire to embed quotes:

 >>> print "Formated strings can %s like this ', too" %"include"
Formated strings can include like this -too
 >>> print 'or %s %s"' %('like', 'this')
or like this"
 >>> print '''Or both %s -- ' and " -- if %s''' %('kinds of quotes', 
'you use triple-quote strings')
Or both kinds of quotes -- ' and " -- if you use triple-quote strings
 >>>

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's going on with this code? Error message supplied.

2005-07-10 Thread Alan G

>  Here's an error message:
> 
>File "D:\GC.py", line 78
>  cal_opt = cal_menu()
>  ^
>  SyntaxError: invalid syntax
> 
>  The relevant code:
> 
>  option = main_menu()
>  if option == 1:
>  cal_menu()
>  cal_opt = cal_menu()

Consistent indentation is all important in Python
Move the linees under the if statement into alignment:

  if option == 1:
  cal_menu()
  cal_opt = cal_menu()

My tutor discusses this in the topic on 'Loops'

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why does my code show this?

2005-07-10 Thread Alan G
>  cal_opt = int(raw_input("What option would you like: "))

Here you get the input and convert it to a number (int() )
which is fine.

>  if cal_opt == "1":

But here you compare it to a string (see the quotes).

So either remove the convertion to int() around raw_input or 
remove the quotes around the values. The things you compare 
must be the same type.

>  That's not an option. Try again.
>  Option: 3
>  3*4
>  12

I'm not sure how the multiplication appeared though! 

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] please help

2005-07-10 Thread Srinivas Iyyer
Hello group, 
after 4 months my brain became rusty by not solving
problems. 
I need some help to regain my basic skills. 

my problem:

I have a file that looks like this:

//
AB32456\tTransaction from India
\t 43 \t 34
\t 34 \t 65
\t 12 \t 35
//
AV32567\tTransaction from Singapore
\t 43 \t 34
\t 34 \t 65
\t 12 \t 35
//
AK34678\tTransaction from HongKong
\t 43 \t 34
\t 34 \t 65
\t 12 \t 35


Characterstics:
Every transaction seperated by '//'
Column 1 is container name
Column 2 - Description of transaction and quantities
(in next lines)

What I have to do:
//
AB32456\tTransaction from India
AB32456\t 43 \t 34
AB32456\t 34 \t 65
AB32456\t 12 \t 35
//
AV32567\tTransaction from Singapore
AV32567\t 43 \t 34
AV32567\t 34 \t 65
AV32567\t 12 \t 35
//
AK34678\tTransaction from HongKong
AK34678\t 43 \t 34
AK34678\t 34 \t 65
AK34678\t 12 \t 35


The line that Ive been writing (of course wrong
script):

f1 = open('myfile','r')
stuff = f1.read().split('\n')
for i in stuff:
   if i != '//':
trcode = line.split('\t')[0]
trquant = line.split('\t')[1]
print trcode+'\t'+trquant


This is completely garbage and i am getting no where.
Please help me.. 

thank you





Sell on Yahoo! Auctions – no fees. Bid on great items.  
http://auctions.yahoo.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Single Underscore

2005-07-10 Thread Kevin Reeder
What's the significance of naming a variable with a single
underscore as its first character? For example, I'm looking at
find.py in the standard library and it has variables named _debug
and _prune.

Kevin 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Single Underscore

2005-07-10 Thread Chinook
Kevin Reeder wrote:

>What's the significance of naming a variable with a single
>underscore as its first character? For example, I'm looking at
>find.py in the standard library and it has variables named _debug
>and _prune.
>
>Kevin 
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Kevin,

If it is naming conventions then possibly they mean a private property 
or method.
http://jaynes.colorado.edu/PythonGuidelines.html

Lee C

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Single Underscore

2005-07-10 Thread jfouhy
Quoting Kevin Reeder <[EMAIL PROTECTED]>:

> What's the significance of naming a variable with a single
> underscore as its first character? For example, I'm looking at
> find.py in the standard library and it has variables named _debug
> and _prune.

Basically, it means "These variables are internal and not part of the API;
please do not use them in your code because they may change without warning".

The reference here is PEP-8, the Python style guide:
http://www.python.org/peps/pep-0008.html

Excerpt:

"""
In addition, the following special forms using leading or trailing
underscores are recognized (these can generally be combined with any
case convention):

- _single_leading_underscore: weak "internal use" indicator
  (e.g. "from M import *" does not import objects whose name
  starts with an underscore).

- single_trailing_underscore_: used by convention to avoid
  conflicts with Python keyword, e.g.
  "Tkinter.Toplevel(master, class_='ClassName')".

- __double_leading_underscore: class-private names as of Python 1.4.

- __double_leading_and_trailing_underscore__: "magic" objects or
  attributes that live in user-controlled namespaces,
  e.g. __init__, __import__ or __file__.  Sometimes these are
  defined by the user to trigger certain magic behavior
  (e.g. operator overloading); sometimes these are inserted by the
  infrastructure for its own use or for debugging purposes.  Since
  the infrastructure (loosely defined as the Python interpreter
  and the standard library) may decide to grow its list of magic
  attributes in future versions, user code should generally
  refrain from using this convention for its own use.  User code
  that aspires to become part of the infrastructure could combine
  this with a short prefix inside the underscores,
  e.g. __bobo_magic_attr__.
"""

"class-private" (double leading underscore) basically means extra effort is
expended in making the variable hard to see.  It's still not enforced, though. 
This is easiest to explain with an example:

>>> class Foo(object):
...  __x = 3
...  def p(self):
...   print self.__x
...
>>> f = Foo()
>>> f.__x
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'Foo' object has no attribute '__x'
>>> f.p()
3
>>> f._Foo__x
3

Google for python name-mangling if you want to know more about this :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2005-07-10 Thread Danny Yoo


On Sun, 10 Jul 2005, Srinivas Iyyer wrote:

> I have a file that looks like this:
>
> //
> AB32456\tTransaction from India
> \t 43 \t 34
> \t 34 \t 65
> \t 12 \t 35
> //

[some lines cut]


> What I have to do:
> //
> AB32456\tTransaction from India
> AB32456\t 43 \t 34
> AB32456\t 34 \t 65
> AB32456\t 12 \t 35

[some lines cut]


Ok, so it looks like we want to then remember the first column at the
beginning of a transaction, and then have duplicate that value for the
rest of the transaction.  Let's look at what you have so far.

> f1 = open('myfile','r')
> stuff = f1.read().split('\n')
> for i in stuff:
>if i != '//':
> trcode = line.split('\t')[0]
> trquant = line.split('\t')[1]


It might help to simplify the problem a little.  I think you might be
getting stuck because you're trying to handle the '\\' end of a
transaction as well as the column value-trickling stuff, so there's a bit
of mixing going on.


One way to simplifying a problem is to concentrate on handling a single
thing.  Let's say that we have a list of lines from a single transaction:

##
sample_data = ["AB32456\tTransaction from India",
   "\t 43 \t 34",
   "\t 34 \t 65",
   "\t 12 \t 35"]
##

Can you transform these lines so that the AB32456 value trickles into the
other lines of the transaction?  Don't worry about "//" stuff at all in
this subproblem.

Try handling this first: it's the core of your program anyway, so might as
well figure that part out.  *grin*


If you have more questions, please feel free to ask.  Best of wishes to
you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding quotation marks around variables

2005-07-10 Thread Alan G
> Hello all, I am a college student and I am currently working 
> on a two numbers program for our class, The purpose of this 
> program is to take user input and do some math functions. 

So why not show us what you have come up with so far and we'll 
work from there?

> I have figured out how to do the math but I need to display 
> these two variables with quotation marks around them. 

Personally I'd use string formatting for that.
Take a look at the Simple Sequences topic ofmy tutorial for examples.

> Also I need to add these two variables together  and display 
> the hexadecimal of these two variables???

Again string formatting can help.

> Also how do you display wheather one variable is greater 
> than or less than or equal to the other variable?

Use a branch with a boolean expression.
The Branching topic of my tutor covers that.

Have a go and let us see where you are having problems. 
You will learn much faster if you try it before asking.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2005-07-10 Thread Alan G
> The line that Ive been writing (of course wrong
> script):
> 
> f1 = open('myfile','r')
> stuff = f1.read().split('\n')
> for i in stuff:
>   if i != '//':
>trcode = line.split('\t')[0]
>trquant = line.split('\t')[1]
>print trcode+'\t'+trquant
> 

You use i in the for loop but line in the code block inside?

try

for line in file('myfile'):
   if line != '\\':
  trcode = line.split('\t')[0]
  etc...

HTH,

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Single Underscore

2005-07-10 Thread Kevin Reeder
Thanks for the info. I'll look into the links provided.

> http://jaynes.colorado.edu/PythonGuidelines.html
> http://www.python.org/peps/pep-0008.html

Kevin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why does my code show this?

2005-07-10 Thread Nathan Pinno
  Thanks to all in the group. Mini_calc is now up and running successfully 
and is now available to download from my site.

  Thanks again,
  Nathan
  - Original Message - 
  From: "Alan G" <[EMAIL PROTECTED]>
  To: "Nathan Pinno" <[EMAIL PROTECTED]>; 
  Sent: Sunday, July 10, 2005 5:03 PM
  Subject: Re: [Tutor] Why does my code show this?


  >>  cal_opt = int(raw_input("What option would you like: "))
  >
  > Here you get the input and convert it to a number (int() )
  > which is fine.
  >
  >>  if cal_opt == "1":
  >
  > But here you compare it to a string (see the quotes).
  >
  > So either remove the convertion to int() around raw_input or
  > remove the quotes around the values. The things you compare
  > must be the same type.
  >
  >>  That's not an option. Try again.
  >>  Option: 3
  >>  3*4
  >>  12
  >
  > I'm not sure how the multiplication appeared though!
  >
  > Alan G.
  >
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor