Re: [Tutor] input string to own console stdin

2017-11-15 Thread Alan Gauld via Tutor
On 15/11/17 22:16, Eddio 0141 wrote:
> Hi.
> I've been searching on google about inputting to own stdin and press enter
> but so far i haven't found anything at all.

You need to give us a bit more context. This doesn't look like
standard library stuff so which package are you using? (Is that
what chatterbot is?)

Also without seeing the code that doesn't work we can only
make wild guesses about whats going wrong.

One thing to consider is that if (as I assume) you are trying
to talk to another process from Python you need to be sending
your data on stdout for it to be read on the other process'
stdin. You will also need to ensure that Pipes are switched
on in subprocess and that your execution environment is
piping your stdout to their stdin. eg you start chatterbot
with something like:

$ python myscript.py|chatterbot

or

$ chatterbot < python myscript.py

But show us your code, it will make life easier for all of us.

> i have tried this
> [
> https://stackoverflow.com/questions/8475290/how-do-i-write-to-a-python-subprocess-stdin
> ]
> but even it doesn't give me an syntax error, it did absolutely nothing.

See, even that question doesn't make sense, since you *read*
from stdin not write to it. It sounds like a fundamental
concepts kind of thing...

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


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


Re: [Tutor] Input Files

2014-11-19 Thread Peter Otten
niyanax...@gmail.com wrote:

> How do I know write the loop code for the table for both inputfiles,
> Table1.txt and Table2.txt and make a third table from the elements
> multiplied in table1.txt and table2.txt. I'm trying to Check the size of
> the two tables to make sure they both have the same number of rows and
> columns o If the tables are not the same size print an error message 
> Once you have read the data from each file create a third table  The
> elements in the third table are the result of multiplying each element in
> the first table by the corresponding element in the second table:
> thirdTable [i] [j] = firstTable[i] [j] * secondTable[i] [j
> 
> 
> Here is my code so far:

> def main():
[snip]

Did you write this code yourself? I'm asking because

> for i in range(row):
> for j in range (column):
> table[i] [j] = int(table[i] [j])  # convert the string to
> an integer print(" %3d" % (table[i] [j]), end = " ")

the snippet above already loops over a single table. Assuming you have three 
tables called table1, table2, and table3 you can replace the

> table[i] [j] = int(table[i] [j])

part with

  table3[i][j] = table2[i][j] * table3[i][j]

As you see all values in table3 are overwritten and thus don't matter. 
Therefore you can cheat and instead of building it from scratch with two 
for-loops just read "Table 2.txt" a second time.

>def main(): 
>print("Table One") 
>(row1, column1, table1) = readInput("Table 1.txt") 
>print("Table Two") 
>(row2, column2, table2) = readInput("Table 2.txt") 

 # add code to compare row1 with row2 and column1 with column2 here

 (row3, column3, table3) = readInput("Table 2.txt") # sic!
 
 # add the table multiplication code here


This is not idiomatic Python, but once you have the script working in that 
basic form we can show you how to improve it with some of the cool features 
Python has to offer.

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


Re: [Tutor] input python 3.3

2014-02-04 Thread Dave Angel
 Ian D  Wrote in message:
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

When making an amendment to a post,  please reply to that post; 
 don't start a new thread,  especially with a new subject.  And
 please post in text, not html.

Others have answered your question,  but I wanted to point out
 that in 2.x,  the program really has no idea what type of value
 will be returned to input (). Could easily be float,  int, tuple,
 list, Nonetype,  or thousands of other things,  including many
 exceptions.  With 3.x it's a string,  and the programmer remains
 in control.  

-- 
DaveA

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


Re: [Tutor] input python 3.3

2014-02-04 Thread Alan Gauld

On 04/02/14 09:01, Ian D wrote:


I used to use 2.7 and the input was pretty when inputting a numeric
value, it would just get cast to an int.


Just to be picky it would get converted to an int not cast
as an int.

casting and converting are two very different things.
casting means treat a bit pattern in memory as if it is
a particular type regardless of how that bit pattern got there.
Converting to a type changes the bit pattern to give a value
that is in some way related to the original's meaning.

To give a simple example of the difference:

var = '2'  # the character two

castVar = ord(2)# treat the character as an int
convVar = int(var)  # convert '2' to 2

casting is often done in C/C++ because it is common to return
a pointer to a piece of data and the programmer has to tell the compiler 
how to treat that data. It looks like a conversion so

casting is often mistaken for conversion. But they are not
the same. (And C++ confused the issue further by introducing
"dynamic casts" which often are conversions!)

Sorry to be picky but failing to understand the difference
has caused many a bug in C programs and I've suffered enough
pain to be sensitive! :-)


Seems a backwards step unless (and am sure this is the case)it is
beneficial in so many other ways?


Peter has explained why the v2 Python input() was a bad idea.
Explicit conversion is much safer.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] input python 3.3

2014-02-04 Thread Peter Otten
Ian D wrote:

> Hello
>  
> I used to use 2.7 and the input was pretty when inputting a numeric value,
> it would just get cast to an int.
>  
> Seems that 3.3 I have to cast each input so :
> float(num1 = input("Enter a number")

You mean

num1 = float(input("Enter a number"))

  
> Is this just they way it is now? Is there a way to get back to just
> typing:
>  num1 = input("Enter a number ")
>  in python 33.
>  
> Seems a backwards step unless (and am sure this is the case)it is
> beneficial in so many other ways?

input() in Python 2 did not just recognize numbers, it allowed you to 
evaluate an arbitrary Python expression. For example:

$ touch important_file
$ ls
important_file
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> input("Enter a number: ")
Enter a number: __import__("os").remove("important_file")
>>> 
$ ls

Oops, the file is gone. I'm sure you can see why this is dangerous. 
Therefore the recommendation for Python 2 is to use raw_input() instead of 
input() -- and for Python 3 raw_input() was renamed to the more obvious 
input().

You can get the old input() behaviour with

num1 = eval(input(...))

which is still dangerous, but makes the risk more obvious.

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


Re: [Tutor] input loop

2013-09-01 Thread Alan Gauld

On 01/09/13 22:53, Nick Wilson wrote:


Enter command: print
--
Code Price   Quant   Value
--


The bit above needs to be printed once, at the start



TPW   2.00   5   10.00


This bit needs to be repeated for each share type



--
Total cost:  10.00
==


And this bit needs to be printed once at the end
after doing the calculations.


**(This is all even when displayed in Wing101)


That will depend on fonts used etc. If you really need it aligned neatly 
I recommend using html and displaying it in a browser,

but its a lot more work that way!



PROMPT_FOR_COMMAND = 'Enter command: '
PROMPT_FOR_CODE = 'Enter share code to add: '
PROMPT_FOR_PRICE = 'Enter share price: '
PROMPT_FOR_QUANTITY = 'Enter share quantity: '


Were you ever a COBOL programmer by any chance?


def main():
 """This is the main function for the program, ie, this function is
called
 first when the program is run"""


There is nothing in Python that will run this first. You need to call it 
explicitly. This is often done inside a name test clause:


if __name__ == "__main__":
main()




 command = input(PROMPT_FOR_COMMAND).lower()
 if command == 'add':
 return portfolio.append(process_add_code(portfolio))


Are you sure you want to return here?
That will terminate the main function without saving portfolio.
You may want to create a menu system where you repeatedly ask
for input until quit is selected.



 if command == "print" and len(portfolio) <= 1:
 print_portfolio_table(portfolio)
 return main()
 if command == "quit":
 print(MESSAGE_GOODBYE)


HTH

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] input loop

2013-09-01 Thread Dave Angel
On 1/9/2013 17:53, Nick Wilson wrote:

> Hi,

Welcome.

Please start over with a text message.  Your html email is useless to
me, and probably most people on this newsgroup.


    5      
10.00--Total
cost:                
 10.00==**(This
is all even when displayed in Wing101)So
thats all fine, but I'm wanting muiltiple more rows printed underneath
with other shares and their prices etc. Getting stuck
on that, I know i'll need a for loop to iterate over the input but
still wanting to get some help.here's the
rest of the code so
far.PROMPT_FOR_COMMAND
= 'Enter command: 'PROMPT_FOR_CODE = 'Enter share code to
add: 'PROMPT_FOR_PRICE = 'Enter share price:

-- 
DaveA

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


Re: [Tutor] Input into lists?

2013-08-16 Thread leam hall
Hey Dave, you're right. I worked through this with a for loop and set the
contents of a dict's key as the input.

Thanks!

Leam


On Thu, Aug 15, 2013 at 8:28 PM, Dave Angel  wrote:

> leam hall wrote:
>
> > I'm trying to take input from a file (CSV spreadsheet) and use the first
> > line inputs (header) as the names of lists. So far I'm not successful.
> :)
> >
> > How do I take line_list[0], the result of "line.split(',')" and use it as
> > the name of a list? Does that make sense?
> >
>
> No, it doesn't make sense.  You're trying to define a variable that has
> a name determined not by your source, but by a name in line 0 of the csv
> file.  How then are you going to use that variable?
>
> There are two possibilities:  Either you actually know those names and
> are using them in your code, or the names won't be known till runtime.
>
> If the latter, then make a dictionary of lists,
>
> mydict = {}
> for item in line_list:
> mydict[item] = []
>
> and then populate those lists from each line of the file.
>
> Now, if you're sure you know what the names are to be, then:
>
> names = mydict["name"]
> addresses = mydict["address"]
>
> or whatever.
>
>
>
>
> --
> DaveA
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Mind on a Mission 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input into lists?

2013-08-15 Thread Dave Angel
leam hall wrote:

> I'm trying to take input from a file (CSV spreadsheet) and use the first
> line inputs (header) as the names of lists. So far I'm not successful.   :)
>
> How do I take line_list[0], the result of "line.split(',')" and use it as
> the name of a list? Does that make sense?
>

No, it doesn't make sense.  You're trying to define a variable that has
a name determined not by your source, but by a name in line 0 of the csv
file.  How then are you going to use that variable?

There are two possibilities:  Either you actually know those names and
are using them in your code, or the names won't be known till runtime.

If the latter, then make a dictionary of lists,

mydict = {}
for item in line_list:
mydict[item] = []

and then populate those lists from each line of the file.

Now, if you're sure you know what the names are to be, then:

names = mydict["name"]
addresses = mydict["address"]

or whatever.




-- 
DaveA


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


Re: [Tutor] Input into lists?

2013-08-15 Thread Alan Gauld

On 13/08/13 16:46, leam hall wrote:

I'm trying to take input from a file (CSV spreadsheet) and use the first
line inputs (header) as the names of lists. So far I'm not successful.   :)


Have you tried the csv module?

Usually you use a dictionary keyed by the first line values though.
But i#'m sure you could tweak it to generate separate lists if thats 
really what you need.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Input handling?

2012-09-18 Thread Scott Yamamoto
Thanks for everything. I'll keep this in mind as I continue coding.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input handling?

2012-09-18 Thread eryksun
On Tue, Sep 18, 2012 at 1:23 PM, Scott Yamamoto
 wrote:
>
> 1) expect: raw_input to assign the variable to ""
> 2)No output to stderr; has a loading symbol after hitting enter without input
> (tried both input and raw_input)
> Doesn't affect active interpreter. Only affects the screen with the run 
> option.
> 3)

Except for a bug your code worked for me in Python 2.7.3.

> def simulation():
>   import random
>   from random import randrange
>   from time import sleep

You're not using randrange, plus you should move the imports to the
top of your module.

>   gender = raw_input("Gender: male/female \n")
>   if gender != "male" or "female":
> gender = "male"

This is the bug. You have the test expression "expr1 or expr2" where
expr1 is "gender != male" and expr2 is "female". A non-empty string is
always True by definition, so your test amounts to "expr1 or True",
which means the "if" block always executes.

>   Mlist = ["Jacob", "Mason", "William", ...]
>   Flist = ["Sophia", "Isabella", "Emma", ...]
>   Llist = ["Smith", "Johnson", "Williams", ...]

Consider moving these lists out of the function. They can all go
nicely in a dict, which you can set as a default argument.

>   username = raw_input("Input your full name: \n")
>   if username == "":
> if gender == "male":
>   username = random.choice(Mlist) + " " + random.choice(Llist)
> else:
>   username = random.choice(Flist) + " " + random.choice(Llist)

Using a dict for the names eliminates the need to test gender here. For example:


import random
import time

names = {
  "male": [
"Jacob", "Mason", "William", "Jayden", "Noah", "Michael",
"Ethan", "Alexander", "Aiden", "Daniel", "Anthony",
"Matthew", "Elijah", "Joshua", "Liam", "Andrew", "James",
"David", "Benjamin", "Logan",
  ],
  "female": [
"Sophia", "Isabella", "Emma", "Olivia", "Ava", "Emily",
"Abigail", "Madison", "Mia", "Chloe", "Elizabeth", "Ella",
"Addison", "Natalie", "Lily", "Grace", "Samantha", "Avery",
"Sofia", "Aubrey",
  ],
  "last": [
"Smith", "Johnson", "Williams", "Jones", "Brown", "Pavis",
"Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas",
"Jackson", "White", "Harris", "Martin", "Thompson", "Garcia",
"Martinez", "Robinson",
  ],
}

def simulation(names=names):
print "Welcome to The World."
time.sleep(1)
print "Now Loading..."
time.sleep(1.5)
# Intro page
gender = raw_input("\nGender [male|female]:\n").strip()
if gender not in ("male", "female"):
gender = "male"
username = raw_input("Input your full name:\n")
if not username:
username = " ".join(
random.choice(n) for n in (names[gender], names["last"]))
print "\nUsername: %s. Gender: %s." % (username, gender)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input handling?

2012-09-18 Thread Scott Yamamoto
0) using mobile yahoo mail
1) expect: raw_input to assign the variable to ""
2)No output to stderr; has a loading symbol after hitting enter without input 
(tried both input and raw_input)
Doesn't affect active interpreter. Only affects the screen with the run 
option.
3)
def simulation():
  import random
  from random import randrange
  from time import sleep
  print "Welcome to The World."
  sleep(1)
  print "Now Loading..."
  sleep(1.5)
  #Intro page
  print
  gender = raw_input("Gender: male/female \n")
  if gender != "male" or "female":
    gender = "male"
  Mlist = ["Jacob", "Mason", "William", "Jayden", "Noah", "Michael", "Ethan", 
"Alexander", "Aiden", "Daniel", "Anthony", "Matthew", "Elijah", "Joshua", 
"Liam", "Andrew", "James", "David", "Benjamin", "Logan"]
  Flist = ["Sophia", "Isabella", "Emma", "Olivia", "Ava", "Emily", "Abigail", 
"Madison", "Mia", "Chloe", "Elizabeth", "Ella", "Addison", "Natalie", "Lily", 
"Grace", "Samantha", "Avery", "Sofia", "Aubrey"]
  Llist = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Pavis", "Miller", 
"Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", 
"Harris", "Martin", "Thompson", "Garcia", "Martinez", "Robinson"]
  username = raw_input("Input your full name: \n")
  if username == "":
    if gender == "male":
      username = random.choice(Mlist) + " " + random.choice(Llist)
    else:
      username = random.choice(Flist) + " " + random.choice(Llist)
  print
  print "Username: %s. Gender: %s." % (username,gender)
simulation()___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input handling?

2012-09-18 Thread Oscar Benjamin
On Sep 18, 2012 10:02 AM, "Oscar Benjamin" 
wrote:
>
>
> On Sep 18, 2012 7:14 AM, "Steven D'Aprano" 
wrote:
> >

Apologies for gmail screwing up your name. I wish I could use mutt on this
machine.

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


Re: [Tutor] Input handling?

2012-09-18 Thread Oscar Benjamin
On Sep 18, 2012 7:14 AM, "Steven D'Aprano"  wrote:
>
> On Tue, Sep 18, 2012 at 12:04:22AM -0400, Dave Angel wrote:
> > Somehow you managed to put your other message in its own thread, instead
> > of adding to this one.
>
> Not all mail clients support threading, either when receiving or
> sending.
>
> But my mail client, mutt, shows Scott's emails threaded correctly.
> Perhaps your mail client is broken? What are you using?

Mutt goes above and beyond a correct implementation of threading by using
heuristics to fix broken threads. I know it parses the subject line but I'm
not sure what else it uses. The upshot is that if you use mutt you won't
see the same thing that would be shown in a client that has a strict
interpretation of threading (unless you disable the heuristics in your
muttrc).

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


Re: [Tutor] Input handling?

2012-09-17 Thread Dave Angel
On 09/18/2012 02:12 AM, Steven D'Aprano wrote:
> On Tue, Sep 18, 2012 at 12:04:22AM -0400, Dave Angel wrote:
>> On 09/17/2012 11:11 PM, Scott Yamamoto wrote:
>>> I've been trying to find possible erros with input(such as NameError or 
>>> SyntaxError) to handle them with an except clause. however, I've found 
>>> that hitting enter/return while prompted without inputting creates some 
>>> kind of problem.
>> username = raw_input("Input a username: ")
>>> Input a username: #hits enter, encounter problem here. Loops forever or 
>>> something
>>>
>>> Using python for ios
>>>
>> Somehow you managed to put your other message in its own thread, instead
>> of adding to this one.
> Not all mail clients support threading, either when receiving or 
> sending.
>
> But my mail client, mutt, shows Scott's emails threaded correctly. 
> Perhaps your mail client is broken? What are you using?
>
>  

I'm using Thunderbird 14 on Linux, and I'd love help in diagnosing why
some messages get properly threaded, and some do not.  For example, I've
seen several of your replies (not a very big fraction) apparently start
new threads.  And I've seen many other messages which didn't get in the
proper place in the thread, appearing at the same level as the message
they were replies to.

I will be upgrading to latest Thunderbird, but I'm planning on
installing a new Linux on a new hard disk, and haven't really gotten
started yet.

>> What version of Python are you running?  If it's 2.x, and if you're
>> using input(),
> Given that the OP clearly shows
>
> username = raw_input("Input a username: ")
>
> I think that we can safely assume that he is not using 2.x's input :)
>

His first message showed one line, typed in the interpreter, with no
clear statement of environment or problem.  However, the statement did
mention the input function.  I'd have disbelieved it except that...

His second message specifically changes to input.  Here it is again, for
our confusion:

"""Didnt show up at first. Result was an eof error (using input not raw_input)
Found with interactive interpreter
"""

I would have been replying to that one, except that it apparently
started a new thread, as did his third message.  That third one went
back to using raw_input, but it was a reply to my message stating the
hazards of input on Python 2.x


-- 

DaveA

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


Re: [Tutor] Input handling?

2012-09-17 Thread Steven D'Aprano
On Mon, Sep 17, 2012 at 09:19:41PM -0700, Scott Yamamoto wrote:
> 2.7.2 on python for ios(platform is darwin)
> problem reoccured

What problem? Your code works for me.

Please describe:

1) what you expect to happen
2) what actually happens
3) if there is a traceback, COPY AND PASTE the ENTIRE traceback, do not 
summarise or abbreviate it.


> Script:
> 
> import random
> username = ""
> def playername():
>   global username
>   Mlist = ["name1","name2","name3"]
>   Flist = ["name4","name5", "name6"]
>   Llist = ["Lname1","Lname2","Lname3"]
>   username = raw_input("input your desired username: ")
>   if username == "":
> username = random.choice(Mlist) + " " + random.choice(Llist)
> playername()


> Doesnt return the error during run
> Attempting implementation of try results in indentation errors in later lines

That's because your attempt to implement try is broken.

But why are you using a try? If your function has a bug, FIX THE BUG, 
don't just cover it up with a try...except.



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


Re: [Tutor] Input handling?

2012-09-17 Thread Steven D'Aprano
On Tue, Sep 18, 2012 at 12:04:22AM -0400, Dave Angel wrote:
> On 09/17/2012 11:11 PM, Scott Yamamoto wrote:
> > I've been trying to find possible erros with input(such as NameError or 
> > SyntaxError) to handle them with an except clause. however, I've found 
> > that hitting enter/return while prompted without inputting creates some 
> > kind of problem.
>  username = raw_input("Input a username: ")
> > Input a username: #hits enter, encounter problem here. Loops forever or 
> > something
> >
> > Using python for ios
> >
> 
> Somehow you managed to put your other message in its own thread, instead
> of adding to this one.

Not all mail clients support threading, either when receiving or 
sending.

But my mail client, mutt, shows Scott's emails threaded correctly. 
Perhaps your mail client is broken? What are you using?

 
> What version of Python are you running?  If it's 2.x, and if you're
> using input(),

Given that the OP clearly shows

username = raw_input("Input a username: ")

I think that we can safely assume that he is not using 2.x's input :)



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


Re: [Tutor] Input handling?

2012-09-17 Thread Scott Yamamoto
2.7.2 on python for ios(platform is darwin)
problem reoccured
Script:

import random
username = ""
def playername():
  global username
  Mlist = ["name1","name2","name3"]
  Flist = ["name4","name5", "name6"]
  Llist = ["Lname1","Lname2","Lname3"]
  username = raw_input("input your desired username: ")
  if username == "":
username = random.choice(Mlist) + " " + random.choice(Llist)
playername()

Doesnt return the error during run
Attempting implementation of try results in indentation errors in later lines___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input handling?

2012-09-17 Thread Dave Angel
On 09/17/2012 11:11 PM, Scott Yamamoto wrote:
> I've been trying to find possible erros with input(such as NameError or 
> SyntaxError) to handle them with an except clause. however, I've found 
> that hitting enter/return while prompted without inputting creates some kind 
> of problem.
 username = raw_input("Input a username: ")
> Input a username: #hits enter, encounter problem here. Loops forever or 
> something
>
> Using python for ios
>

Somehow you managed to put your other message in its own thread, instead
of adding to this one.

What version of Python are you running?  If it's 2.x, and if you're
using input(), then you're doing a (hazardous) eval on whatever the user
types.  So if the user doesn't type a valid expression, or if that
expression doesn't evaluate to a number, you'll get some exception. 
Clearly, you want raw_input(), which is looking for a string, and
doesn't mind empty strings from the user.

It would be useful (in the future) if you clearly stated what version of
Python you're using, what exactly was included in your script, and what
exception you got, with full traceback.  Much more useful to diagnose
than a vague - "some kind of problem."


-- 

DaveA

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


Re: [Tutor] Input handling?

2012-09-17 Thread Scott Yamamoto
Didnt show up at first. Result was an eof error (using input not raw_input)
Found with interactive interpreter___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input

2011-10-01 Thread Ed Hughes
Have a look at the Windows/Unix/Linux solution posted in the ActiveState
Python Recipes, (a fantastic resource),
here<http://code.activestate.com/recipes/134892/> -
a bit long winded maybe but it works fine under Linux and Windows for me.
It's pretty much based on the standard docs solution as already mentioned
for Linux/Unix. It use the tty and termios modules in Unix/Linux and the msvcrt
module in Windows, again, as already mentioned.

BgEddy

On 1 October 2011 11:00,  wrote:

> Send Tutor mailing list submissions to
>tutor@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>tutor-requ...@python.org
>
> You can reach the person managing the list at
>tutor-ow...@python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: Input (Steven D'Aprano)
>   2. Re: guess age programme (please help) (Steven D'Aprano)
>   3. fake defrag revisited (R. Alan Monroe)
>   4. Re: guess age programme (please help) (Alan Gauld)
>
>
> ------
>
> Message: 1
> Date: Sat, 01 Oct 2011 12:36:57 +1000
> From: Steven D'Aprano 
> To: tutor@python.org
> Subject: Re: [Tutor] Input
> Message-ID: <4e867cc9.3050...@pearwood.info>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Cameron Macleod wrote:
> > Hi,
> >
> > When you type
> >
> > Input("\n\nPress The Enter Key To Exit")
> >
> > it forces you to press the enter key to close the program. Why is it the
> > enter key instead of e.g. the 'esc' key?
>
> Because the convention is that you use the Enter key to ENTER
> information. That's why it is called Enter.
>
> Your question is kind of like asking "Why do you use a screw driver for
> driving screws, instead of a socket wrench?" 
>
> In all terminals I know of, the user's input is collected in a buffer
> until the Enter key is pressed. Until then, what the user types isn't
> available to the caller. This is how raw_input (Python 2) and input
> (Python 3) work.
>
> If you want to read the user's input character by character, as they are
> typed, it is actually quite tricky, but it can be done. You can install
> a full-blown GUI tool kit, like wxPython or Tkinter, and use that. Or
> you can use the curses module, which is a bit lighter than Tkinter but
> still pretty heavyweight. For Linux, there's a FAQ:
>
>
> http://docs.python.org/faq/library.html#how-do-i-get-a-single-keypress-at-a-time
>
> On Windows, you can use msvcrt.getch().
>
>
> --
> Steven
>
>
> --
>
> Message: 2
> Date: Sat, 01 Oct 2011 14:13:43 +1000
> From: Steven D'Aprano 
> To: tutor@python.org
> Subject: Re: [Tutor] guess age programme (please help)
> Message-ID: <4e869377.5030...@pearwood.info>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Hi Adrian,
>
> ADRIAN KELLY wrote:
> > Hi all,
> > can anyone help me with the attached programme.
>
> I'd love to, but I can't open it :(
>
> If the truth be known, I could open it if I spent the time and effort.
> But that actually is significant time and effort: in my email, your
> attachment looks like this:
>
> Content-Type: application/octet-stream
> Content-Transfer-Encoding: base64
> Content-Disposition: attachment; filename="guess age_game(broken)"
>
>
> DQpwcmludCgiXHRXZWxjb21lIHRvICdHdWVzcyBNeSBOdW1iZXInISIpDQpwcmludCgiSSdtIHRo
>
> aW5raW5nIG9mIGEgbnVtYmVyIGJldHdlZW4gMSBhbmQgMTAwLiIpDQpwcmludCgiVHJ5IHRvIGd1
>
> ZXNzIGl0IGluIGFzIGZldyBhdHRlbXB0cyBhcyBwb3NzaWJsZS5cbiIpDQoNCiMgc2V0IHRoZSBp
>
> bml0aWFsIHZhbHVlcw0KYWdlID0gMzUNCmd1ZXNzID0gIiAiDQp0cmllcyA9IDUNCg0KIyBndWVz
>
> c2luZyBsb29wDQp3aGlsZSBndWVzcyAhPSBhZ2U6DQogICAgDQogICAgZ3Vlc3MgPSBpbnB1dCgi
>
> VGFrZSBhIGd1ZXNzOiAiKQ0KICAgIGlmIGd1ZXNzID4gYWdlOg0KICAgICAgICBwcmludCAiTG93
>
> ZXIuLi4iLHRyaWVzLCJsZWZ0Ig0KICAgIGVsc2U6DQogICAgICAgIHByaW50ICJIaWdoZXIuLi4i
>
> LHRyaWVzLCJsZWZ0Ig0KICAgICAgICAgICAgDQogICAgdHJpZXM9dHJpZXMtMQ0KICAgDQoNCnBy
>
> aW50ICJcblxuWW91IGd1ZXNzZWQgaXQhICBUaGUgYWdlIHdhcyIsIGFnZSwiaXQgb25seSB0b29r
>
> IHlvdSAiK2B0cmllc2ArIiBhdHRlbXB0cyB0byBnZXQgaXQiDQoNCiAgDQppbnB1dCAoIlxuXG5Q
> cmVzcyB0aGUgZW50ZXIga2V5IHRvIGV4aXQuIikNCg==
>
>
> I hope you understand why I don't care enough to go to the time and
> effort of saving it to a file, decoding it, 

Re: [Tutor] Input

2011-09-30 Thread Steven D'Aprano

Cameron Macleod wrote:

Hi,

When you type

Input("\n\nPress The Enter Key To Exit")

it forces you to press the enter key to close the program. Why is it the
enter key instead of e.g. the 'esc' key?


Because the convention is that you use the Enter key to ENTER 
information. That's why it is called Enter.


Your question is kind of like asking "Why do you use a screw driver for 
driving screws, instead of a socket wrench?" 


In all terminals I know of, the user's input is collected in a buffer 
until the Enter key is pressed. Until then, what the user types isn't 
available to the caller. This is how raw_input (Python 2) and input 
(Python 3) work.


If you want to read the user's input character by character, as they are 
typed, it is actually quite tricky, but it can be done. You can install 
a full-blown GUI tool kit, like wxPython or Tkinter, and use that. Or 
you can use the curses module, which is a bit lighter than Tkinter but 
still pretty heavyweight. For Linux, there's a FAQ:


http://docs.python.org/faq/library.html#how-do-i-get-a-single-keypress-at-a-time

On Windows, you can use msvcrt.getch().


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


Re: [Tutor] Input

2011-09-30 Thread bodsda
You could also use something like pygame to wait and test for keypresses

Bodsda
(Top post is phone limitation, sorry) 
Sent from my BlackBerry® wireless device

-Original Message-
From: Mark Lybrand 
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Fri, 30 Sep 2011 13:27:27 
To: 
Cc: 
Subject: Re: [Tutor] Input

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

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


Re: [Tutor] Input

2011-09-30 Thread Mark Lybrand
There is apparently a livewires package that may be of someuse.
On Sep 30, 2011 1:25 PM, "Dave Angel"  wrote:
> On 09/30/2011 03:24 PM, Cameron Macleod wrote:
>> Hi,
>>
>> When you type
>>
>> Input("\n\nPress The Enter Key To Exit")
>>
>> it forces you to press the enter key to close the program. Why is it the
>> enter key instead of e.g. the 'esc' key?
>>
>>
>
> The input() function (not the Input()) function accepts a line of text
> from the user. That line is terminated by a newline, generated by the
> enter key.
>
> If you're trying to just wait for an "any-key", I don't know of any
> portable way to do it. There is a way in Windows, however.
>
>
>
> --
>
> DaveA
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input

2011-09-30 Thread Dave Angel

On 09/30/2011 03:24 PM, Cameron Macleod wrote:

Hi,

When you type

Input("\n\nPress The Enter Key To Exit")

it forces you to press the enter key to close the program. Why is it the
enter key instead of e.g. the 'esc' key?




The input() function (not the Input()) function accepts a line of text 
from the user.  That line is terminated by a newline, generated by the 
enter key.


If you're trying to just wait for an "any-key", I don't know of any 
portable way to do it.  There is a way in Windows, however.




--

DaveA

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


Re: [Tutor] input and raw input

2010-09-28 Thread John Chandler
you can use an re split...

import re
a=raw_input("Enter the number of your class in the school:")
regex = re.compile("[ ,]") #sets the delimeters to a single space or comma
m = regex.split(a)

if you want to use any white space character than you can use "[\s,]"

2010/9/23 Ahmed AL-Masri 

>  Hi,
> any one have an idea about how we can input many number in the one time and
> change it to list.
> for example:
>
> a=input("Enter the number of your class in the school:") # the number
> can be enter as: 12,13,14 or 12 13 14 with a space in between.
>
> now how I can put these numbers into list like b=[12,13,14] with len( a )
> =3
>
> I tried with that but it's working only for a numbers less than 10 ex.
> 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in
> example above.
>
> a=raw_input("Enter the number of your class in the school:")
> m=[]
>  for I range (len( a)):
> if a[I]==',':
> pass
> elif a[I]==' ':
> pass
> else:
> m.append(a[I])
> m=map(float,m)
> print m;print len( m )
> >> [1,2,3]
> >> 3
>
> looking forward to seeing your help,
> regards,
> Ahmed
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] input and raw input

2010-09-25 Thread Peter Otten
Brian Jones wrote:

> No need for the 're' module. Even in the case where both can be used
> together, you can still just use string methods:
> 
 s
> '12, 13 14'
 s.replace(',', '').split(' ')
> ['12', '13', '14']

I think to replace "," with " " and then split() without explicit separator 
is slightly more robust. Compare:
 
>>> s = "12,34, 56  789"
>>> s.replace(",", " ").split()
['12', '34', '56', '789']
>>> s.replace(",", "").split(" ")
['1234', '56', '', '789']

Peter

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


Re: [Tutor] input and raw input

2010-09-25 Thread Evert Rol
> > any one have an idea about how we can input many number in the one time and 
> > change it to list.
> > for example:
> >
> > a=input("Enter the number of your class in the school:") # the number 
> > can be enter as: 12,13,14 or 12 13 14 with a space in between.
> >
> > now how I can put these numbers into list like b=[12,13,14] with len( a ) =3
> 
> A string has a method split(); that may help you.
> In your case, where you want either a space or a comma as a separator, it 
> depends whether both can be used at the same time. If not, you can check for 
> the occurrence of one or the other separator and run split() with the correct 
> separator. If both can occur in the same line, you may want to use the regex 
> module instead: re.split()
> 
> No need for the 're' module. Even in the case where both can be used 
> together, you can still just use string methods: 
> 
> >>> s
> '12, 13 14'
> >>> s.replace(',', '').split(' ')
> ['12', '13', '14']

Good point.
To be finicky, you'll probably want to replace ',' by ' ' and let split work on 
whitespace instead of a single space. In case of tabs or a 12,13,14 input.


> > I tried with that but it's working only for a numbers less than 10 ex. 
> > 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in 
> > example above.
> >
> > a=raw_input("Enter the number of your class in the school:")
> > m=[]
> >  for I range (len( a)):
> > if a[I]==',':
> > pass
> > elif a[I]==' ':
> > pass
> > else:
> > m.append(a[I])
> > m=map(float,m)
> > print m;print len( m )
> > >> [1,2,3]
> > >> 3
> >
> > looking forward to seeing your help,
> > regards,
> > Ahmed
> >
> >
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> -- 
> Brian K. Jones
> My Blog  http://www.protocolostomy.com
> Follow me  http://twitter.com/bkjones

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


Re: [Tutor] input and raw input

2010-09-25 Thread Brian Jones
On Sat, Sep 25, 2010 at 9:40 AM, Evert Rol  wrote:

> > any one have an idea about how we can input many number in the one time
> and change it to list.
> > for example:
> >
> > a=input("Enter the number of your class in the school:") # the number
> can be enter as: 12,13,14 or 12 13 14 with a space in between.
> >
> > now how I can put these numbers into list like b=[12,13,14] with len( a )
> =3
>
> A string has a method split(); that may help you.
> In your case, where you want either a space or a comma as a separator, it
> depends whether both can be used at the same time. If not, you can check for
> the occurrence of one or the other separator and run split() with the
> correct separator. If both can occur in the same line, you may want to use
> the regex module instead: re.split()
>

No need for the 're' module. Even in the case where both can be used
together, you can still just use string methods:

>>> s
'12, 13 14'
>>> s.replace(',', '').split(' ')
['12', '13', '14']




> hth,
>
>  Evert
>
>
> > I tried with that but it's working only for a numbers less than 10 ex.
> 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in
> example above.
> >
> > a=raw_input("Enter the number of your class in the school:")
> > m=[]
> >  for I range (len( a)):
> > if a[I]==',':
> > pass
> > elif a[I]==' ':
> > pass
> > else:
> > m.append(a[I])
> > m=map(float,m)
> > print m;print len( m )
> > >> [1,2,3]
> > >> 3
> >
> > looking forward to seeing your help,
> > regards,
> > Ahmed
> >
> >
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Brian K. Jones
My Blog  http://www.protocolostomy.com
Follow me  http://twitter.com/bkjones
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and raw input

2010-09-25 Thread Evert Rol
> any one have an idea about how we can input many number in the one time and 
> change it to list.
> for example:
>  
> a=input("Enter the number of your class in the school:") # the number can 
> be enter as: 12,13,14 or 12 13 14 with a space in between.
>  
> now how I can put these numbers into list like b=[12,13,14] with len( a ) =3

A string has a method split(); that may help you.
In your case, where you want either a space or a comma as a separator, it 
depends whether both can be used at the same time. If not, you can check for 
the occurrence of one or the other separator and run split() with the correct 
separator. If both can occur in the same line, you may want to use the regex 
module instead: re.split()

hth,

  Evert

 
> I tried with that but it's working only for a numbers less than 10 ex. 1,2,3 
> or 1 2 3 but it's not when I go for numbers higher than 10 like in example 
> above.
>  
> a=raw_input("Enter the number of your class in the school:")
> m=[]
>  for I range (len( a)):
> if a[I]==',':
> pass
> elif a[I]==' ':
> pass
> else:
> m.append(a[I])
> m=map(float,m)
> print m;print len( m )
> >> [1,2,3]
> >> 3
>  
> looking forward to seeing your help,
> regards,
> Ahmed
>  
>  
>  
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] input problem

2010-09-14 Thread Alan Gauld


"ANKUR AGGARWAL"  wrote


Suppose i am taking input or various variables like
a=raw_input("...") //hello
b=raw_input("")//hi
but i want to run a common function when input is hello

so instead of
if a=="hello":
fun()
then again for b and then again for c then d and so on i have to 
apply the

code for the specific variable ,
i want to run the function whenever in the code input is "hello"
i am wondering is there is any way like
if input=="hello":
fun()


I don;t see how that changes from the previous example except
you changed a to input?

However I think you are asking about processing a collection
of data values (which happen to have been produced by raw_input()
but could equally have been read from a file).

The pattern for that case is the for loop:

for data in data_collection:
if data == "hello":
fun()

Or if you want to collect the results:

results = [fun() for data in data_collection if data == "hello"]

How you get the data into data_collecton I leave as an excercise! :-)


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] input problem

2010-09-13 Thread James Mills
On Tue, Sep 14, 2010 at 6:45 AM, ANKUR AGGARWAL  wrote:
> Suppose i am taking input or various variables like
> a=raw_input("...") //hello
> b=raw_input("")//hi
> c=raw_input("...")//hello
> d=raw_input("..")//hello
> but i want to run a common function when input is hello
> so instead of
> if a=="hello":
>  fun()
> then again for b and then again for c then d and so on i have to apply the
> code for the specific variable ,
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
>  fun()
> i hope you get my point.. Help me out please
> Thanks in advance

How about this design pattern:

def hello():
   print "Hello World!"

prompt = "..."
s = raw_input(prompt)
while s:
   if s == "hello":
  hello()
   elif s == "quit":
  break
   s = raw_input(prompt)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input problem

2010-09-13 Thread christopher . henk
ANKUR AGGARWAL wrote on 09/13/2010 04:45:41 PM:

> Suppose i am taking input or various variables like
> a=raw_input("...") //hello
> b=raw_input("")//hi
> c=raw_input("...")//hello
> d=raw_input("..")//hello
> but i want to run a common function when input is hello
> 
> so instead of
> if a=="hello":
>  fun()
> then again for b and then again for c then d and so on i have to apply 
the code for the specific variable , 
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
>  fun()
> i hope you get my point.. Help me out please

You put your inputs into a list and see if "hello" is in the list.
 
inputlist=[a,b,c,d]
if "hello" in inputlist:
fun()

or if you want to run fun() once for every "hello" you can then loop over 
the list.

inputlist=[a,b,c,d]
for inputitem in inputlist: 
if "hello" == inputitem:
fun()

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


Re: [Tutor] input problem

2010-08-22 Thread Nick Raptis

Please try and reply to the list instead of just me.


raw_input did not the trick.
fruit.count is the next exercise.
Oke, I deleted the initialazion and change teller into letter.

Roelof



Should be alright now.. Hmmm

Can you paste your exact code AND the error you're getting? As I 
understand you never get the prompts, right?


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


Re: [Tutor] input problem

2010-08-22 Thread Nick Raptis

On 08/22/2010 09:35 PM, Roelof Wobben wrote:

Hello,

I made this programm :

def count_letters(n,a):
count = 0
for char in n:
if char == a:
count += 1
return count
fruit=""
letter=""
fruit= input("Enter a sort of fruit: ")
teller = input("Enter the character which must be counted: ")
x=count_letters (fruit,letter)
print "De letter", letter , "komt", x , "maal voor in het woord", fruit

The problem is that I can't have the opportuntity for input anything.
I use python 2.7 on a Win7 machine with as editor SPE.

Roelof

Also, you have a typo in your code (teller instead of letter) so fix 
that too :)


A couple more comments:
- You don't have to initialize fruit and letter. Doesn't make sense in 
this context.


- Although I can see you made the count_letters() function as an 
exercise, there is a build in method of string that accomplishes the 
same effect.

Try x=fruit.count(letter)

- Give a bit of thought about what would happen if someone enters a 
whole string instead of a character for letter. How should your program 
accommodate that?


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


Re: [Tutor] input problem

2010-08-22 Thread Alex Hall
On 8/22/10, Roelof Wobben  wrote:
>
> Hello,
>
>
>
> I made this programm :
>
>
>
> def count_letters(n,a):
> count = 0
> for char in n:
> if char == a:
> count += 1
> return count
>
> fruit=""
> letter=""
> fruit= input("Enter a sort of fruit: ")
> teller = input("Enter the character which must be counted: ")
> x=count_letters (fruit,letter)
> print "De letter", letter , "komt", x , "maal voor in het woord", fruit
>
>
>
> The problem is that I can't have the opportuntity for input anything.
Try replacing the two lines where you say "input" with "raw_input" and
see if that works.
>
> I use python 2.7 on a Win7 machine with as editor SPE.
>
>
>
> Roelof
>
>
>   


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input problem

2010-08-22 Thread Nick Raptis

On 08/22/2010 09:35 PM, Roelof Wobben wrote:

Hello,

I made this programm :

def count_letters(n,a):
count = 0
for char in n:
if char == a:
count += 1
return count
fruit=""
letter=""
fruit= input("Enter a sort of fruit: ")
teller = input("Enter the character which must be counted: ")
x=count_letters (fruit,letter)
print "De letter", letter , "komt", x , "maal voor in het woord", fruit

The problem is that I can't have the opportuntity for input anything.
I use python 2.7 on a Win7 machine with as editor SPE.

Roelof


You are using Python 2.x, so you should use raw_input() instead of input().

Note that in Python 3.x, raw_input() has been renamed to just input(), 
with the old 2.x input() gone.


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


Re: [Tutor] Input() is not working as expected in Python 3.1

2010-02-15 Thread Yaraslau Shanhin
Thanks for try but print without () does not work at all, at least in newer
version of python (3.1)

Anyway source of problem is now discovered: Komodo Edit tool, in Python
shell (IDLE) everything works fine. Perhaps anyone has any ideas why?

On Mon, Feb 15, 2010 at 10:02 PM, Grigor Kolev wrote:

> В 10:06 -0500 на 15.02.2010 (пн), bob gailer написа:
> > Yaraslau Shanhin wrote:
> >
> >  > Hello All,
> >
> > Hello.
> >
> > Suggestion for future questions - just include enough to identify the
> > problem. We don't need to know that this is from a tutorial or what the
> > exercise is. Also (at least I prefer) plain text without formatting or
> > color.
> >
> > Sufficient therefore is:
> >
> > ---
> > using  Python 3.1:
> > text = str(input("Type in some text: "))
> > number = int(input("How many times should it be printed? "))
> >
> > Traceback (most recent call last):
> > File "test4.py", line 2, in 
> > number = int(input("How many times should it be printed? "))
> > ValueError: invalid literal for int() with base 10:
> > ---
> >
> > Now carefully read the message "invalid literal for int()". This tells
> > you the argument to int is not a string representation of an integer.
> > There is nothing wrong with input()!
> >
> > Since we don't know what you typed at the input() prompt we can't
> > diagnose it further. One way to solve problems like these is to capture
> > and print the output of input():
> >
> > text = str(input("Type in some text: "))
> > snumber = input("How many times should it be printed?")
> > print snumber
> >
> > A good robust alternative is to try int() and capture / report the
> failure:
> >
> > text = str(input("Type in some text: "))
> > snumber = input("How many times should it be printed?")
> > try:
> >   number = int(snumber)
> > except ValueError:
> >   print(number, "is not an integer.")
> > else:
> >   print (text * number)
> >
> Try this:
> >>>text = str(input("Type in some text: "))
> Type in some text:"some text"
> >>>snumber = int(input("How many times should it be printed?"))
> How many times should it be printed?3
> >>>print text*snumber
> --
> Grigor Kolev 
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input() is not working as expected in Python 3.1

2010-02-15 Thread Grigor Kolev
В 10:06 -0500 на 15.02.2010 (пн), bob gailer написа:
> Yaraslau Shanhin wrote:
> 
>  > Hello All,
> 
> Hello.
> 
> Suggestion for future questions - just include enough to identify the 
> problem. We don't need to know that this is from a tutorial or what the 
> exercise is. Also (at least I prefer) plain text without formatting or 
> color.
> 
> Sufficient therefore is:
> 
> ---
> using  Python 3.1:
> text = str(input("Type in some text: "))
> number = int(input("How many times should it be printed? "))
> 
> Traceback (most recent call last):
> File "test4.py", line 2, in 
> number = int(input("How many times should it be printed? "))
> ValueError: invalid literal for int() with base 10:
> ---
> 
> Now carefully read the message "invalid literal for int()". This tells 
> you the argument to int is not a string representation of an integer. 
> There is nothing wrong with input()!
> 
> Since we don't know what you typed at the input() prompt we can't 
> diagnose it further. One way to solve problems like these is to capture 
> and print the output of input():
> 
> text = str(input("Type in some text: "))
> snumber = input("How many times should it be printed?")
> print snumber
> 
> A good robust alternative is to try int() and capture / report the failure:
> 
> text = str(input("Type in some text: "))
> snumber = input("How many times should it be printed?")
> try:
>   number = int(snumber)
> except ValueError:
>   print(number, "is not an integer.")
> else:
>   print (text * number)
> 
Try this:
>>>text = str(input("Type in some text: "))
Type in some text:"some text"
>>>snumber = int(input("How many times should it be printed?"))
How many times should it be printed?3
>>>print text*snumber
-- 
Grigor Kolev 

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


Re: [Tutor] Input() is not working as expected in Python 3.1

2010-02-15 Thread Rich Lovely
On 15 February 2010 15:15, Yaraslau Shanhin  wrote:
> Code:
> text = str(input("Type in some text: "))
> number = int(input("How many times should it be printed? "))
> print (text * number)
> Output:
> Type in some text: some
> How many times should it be printed? 5
> Traceback (most recent call last):
>   File "test4.py", line 2, in 
>     number = int(input("How many times should it be printed? "))
> ValueError: invalid literal for int() with base 10: 'How many times should
> it be printed? 5'
>
> That is exactly how it looks like. It is happening all the time when I run
> program in Komodo Edit, but in IDLE everything works fine (interpreter is
> the same):
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)]
> on win32
> Type "copyright", "credits" or "license()" for more information.
 text = str(input("Type in some text: "))
> Type in some text: some
 number = int(input("How many times should it be printed? "))
> How many times should it be printed? 5
 print (text * number)
> somesomesomesomesome

> For your suggestion
> Code:
> text = str(input("Type in some text: "))
> snumber = input("How many times should it be printed?")
> try:
>  number = int(snumber)
> except ValueError:
>  print(ssnumber, "is not an integer.")
> else:
>  print (text * snumber)
>
>
> Output:
> Type in some text: some
> How many times should it be printed?5
> How many times should it be printed?5 is not an integer.
> On Mon, Feb 15, 2010 at 4:06 PM, bob gailer  wrote:
>>
>> Yaraslau Shanhin wrote:
>>
>> > Hello All,
>>
>> Hello.
>>
>> Suggestion for future questions - just include enough to identify the
>> problem. We don't need to know that this is from a tutorial or what the
>> exercise is. Also (at least I prefer) plain text without formatting or
>> color.
>>
>> Sufficient therefore is:
>>
>> ---
>> using  Python 3.1:
>> text = str(input("Type in some text: "))
>> number = int(input("How many times should it be printed? "))
>>
>> Traceback (most recent call last):
>> File "test4.py", line 2, in 
>>   number = int(input("How many times should it be printed? "))
>> ValueError: invalid literal for int() with base 10:
>> ---
>>
>> Now carefully read the message "invalid literal for int()". This tells you
>> the argument to int is not a string representation of an integer. There is
>> nothing wrong with input()!
>>
>> Since we don't know what you typed at the input() prompt we can't diagnose
>> it further. One way to solve problems like these is to capture and print the
>> output of input():
>>
>> text = str(input("Type in some text: "))
>> snumber = input("How many times should it be printed?")
>> print snumber
>>
>> A good robust alternative is to try int() and capture / report the
>> failure:
>>
>> text = str(input("Type in some text: "))
>> snumber = input("How many times should it be printed?")
>> try:
>>  number = int(snumber)
>> except ValueError:
>>  print(number, "is not an integer.")
>> else:
>>  print (text * number)
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
This is a known bug with Komodo (see
http://bugs.activestate.com/show_bug.cgi?id=71319).
The developers are working on it, by the looks of things.

-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.

10 re-discover BASIC
20 ???
30 PRINT "Profit"
40 GOTO 10
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input() is not working as expected in Python 3.1

2010-02-15 Thread Yaraslau Shanhin
Code:

text = str(input("Type in some text: "))
number = int(input("How many times should it be printed? "))
print (text * number)

Output:
Type in some text: some
How many times should it be printed? 5
Traceback (most recent call last):
  File "test4.py", line 2, in 
number = int(input("How many times should it be printed? "))
ValueError: invalid literal for int() with base 10: 'How many times should
it be printed? 5'


That is exactly how it looks like. It is happening all the time when I run
program in Komodo Edit, but in IDLE everything works fine (interpreter is
the same):


Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information.
>>> text = str(input("Type in some text: "))
Type in some text: some
>>> number = int(input("How many times should it be printed? "))
How many times should it be printed? 5
>>> print (text * number)
somesomesomesomesome
>>>

For your suggestion

Code:
text = str(input("Type in some text: "))
snumber = input("How many times should it be printed?")
try:
 number = int(snumber)
except ValueError:
 print(ssnumber, "is not an integer.")
else:
 print (text * snumber)



Output:
Type in some text: some
How many times should it be printed?5
How many times should it be printed?5 is not an integer.

On Mon, Feb 15, 2010 at 4:06 PM, bob gailer  wrote:

> Yaraslau Shanhin wrote:
>
> > Hello All,
>
> Hello.
>
> Suggestion for future questions - just include enough to identify the
> problem. We don't need to know that this is from a tutorial or what the
> exercise is. Also (at least I prefer) plain text without formatting or
> color.
>
> Sufficient therefore is:
>
> ---
> using  Python 3.1:
>
> text = str(input("Type in some text: "))
> number = int(input("How many times should it be printed? "))
>
> Traceback (most recent call last):
> File "test4.py", line 2, in 
>   number = int(input("How many times should it be printed? "))
> ValueError: invalid literal for int() with base 10:
> ---
>
> Now carefully read the message "invalid literal for int()". This tells you
> the argument to int is not a string representation of an integer. There is
> nothing wrong with input()!
>
> Since we don't know what you typed at the input() prompt we can't diagnose
> it further. One way to solve problems like these is to capture and print the
> output of input():
>
>
> text = str(input("Type in some text: "))
> snumber = input("How many times should it be printed?")
> print snumber
>
> A good robust alternative is to try int() and capture / report the failure:
>
>
> text = str(input("Type in some text: "))
> snumber = input("How many times should it be printed?")
> try:
>  number = int(snumber)
> except ValueError:
>  print(number, "is not an integer.")
> else:
>  print (text * number)
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input() is not working as expected in Python 3.1

2010-02-15 Thread bob gailer

Yaraslau Shanhin wrote:

> Hello All,

Hello.

Suggestion for future questions - just include enough to identify the 
problem. We don't need to know that this is from a tutorial or what the 
exercise is. Also (at least I prefer) plain text without formatting or 
color.


Sufficient therefore is:

---
using  Python 3.1:
text = str(input("Type in some text: "))
number = int(input("How many times should it be printed? "))

Traceback (most recent call last):
File "test4.py", line 2, in 
   number = int(input("How many times should it be printed? "))
ValueError: invalid literal for int() with base 10:
---

Now carefully read the message "invalid literal for int()". This tells 
you the argument to int is not a string representation of an integer. 
There is nothing wrong with input()!


Since we don't know what you typed at the input() prompt we can't 
diagnose it further. One way to solve problems like these is to capture 
and print the output of input():


text = str(input("Type in some text: "))
snumber = input("How many times should it be printed?")
print snumber

A good robust alternative is to try int() and capture / report the failure:

text = str(input("Type in some text: "))
snumber = input("How many times should it be printed?")
try:
 number = int(snumber)
except ValueError:
 print(number, "is not an integer.")
else:
 print (text * number)

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

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


Re: [Tutor] Input() is not working as expected in Python 3.1

2010-02-15 Thread Dave Angel

Yaraslau Shanhin wrote:

Hello All,

I am working with Python tutorial in wiki and one of the exercises is as
follows:

Ask the user for a string, and then for a number. Print out that string,
that many times. (For example, if the string is hello and the number is 3 you
should print out hellohellohello.)

Solution for this exercise is:

text = str(raw_input("Type in some text: "))
number = int(raw_input("How many times should it be printed? "))print
(text * number)



Since in Python raw_input() function was renamed to input() according
to PEP 3111  I have
respectively updated this code to:


text = str(input("Type in some text: "))
number = int(input("How many times should it be printed? "))print
(text * number)



However when I try to execute this code in Python 3.1 interpreter
error message is generated:


Type in some text: some
How many times should it be printed? 3
Traceback (most recent call last):
  File "test4.py", line 2, in 
number = int(input("How many times should it be printed? "))
ValueError: invalid literal for int() with base 10: 'How many times
should it be printed? 3'


Can you please advise me how to resolve this issue?

  
When I correct for your missing newline, it works for me.  I don't know 
of any version of Python which would copy the prompt string into the 
result value of input or raw_input() function.


Try pasting the exact console session, rather than paraphrasing it.

DaveA

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


Re: [Tutor] Input() is not working as expected in Python 3.1

2010-02-15 Thread Wayne Werner
On Mon, Feb 15, 2010 at 8:23 AM, Yaraslau Shanhin <
yaraslau.shan...@gmail.com> wrote:

> Hello All,
>
> I am working with Python tutorial in wiki and one of the exercises is as
> follows:
>
> Ask the user for a string, and then for a number. Print out that string,
> that many times. (For example, if the string is hello and the number is 3 you
> should print out hellohellohello.)
>
> Solution for this exercise is:
>
> text = str(raw_input("Type in some text: "))
> number = int(raw_input("How many times should it be printed? "))print (text * 
> number)
>
>
>
> Since in Python raw_input() function was renamed to input() according to PEP 
> 3111  I have respectively updated 
> this code to:
>
>
> text = str(input("Type in some text: "))
>
>
This str() is redundant - input returns a string by default.


>
> number = int(input("How many times should it be printed? "))print (text * 
> number)
>
>
>
> However when I try to execute this code in Python 3.1 interpreter error 
> message is generated:
>
>
> Type in some text: some
> How many times should it be printed? 3
> Traceback (most recent call last):
>   File "test4.py", line 2, in 
> number = int(input("How many times should it be printed? "))
> ValueError: invalid literal for int() with base 10: 'How many times should it 
> be printed? 3'
>
>
That means you're having an issue with getting something that isn't just a
number.

try:

number = input("How many ... ")
print (number)
number = int(number)
print (number)

HTH,
Wayne


>
> Can you please advise me how to resolve this issue?
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input validation

2009-09-04 Thread Rich Lovely
2009/9/3 Albert-Jan Roskam :
> Hi,
>
> I'm wondering what is the most common method of input validation. See the 
> example below.
> -Is the code below the most common/recognizable way something like this is 
> done?
> -Which of the options #1 and #2 is the preferred method? Option #2 looks less 
> esoteric, but #1 seems better when you have to check for several data types 
> simultaneously.
>
> Thanks!
> Albert-Jan
>
> import os.path, textwrap
>
> def main(param):
>    if validate_input(param) == "LT":
>        return param[-1]
>    elif validate_input(param) == "FILE":
>        f = open(param, "rb").readlines()
>        return " ".join(f)
>    elif validate_input(param) == "STR":
>        return textwrap.wrap(param)
>    else:
>        print "Invalid input!"
>        return None
>
> def validate_input (param):
>    if param.__class__ in (list, tuple): #option 1
>        return "LT"
>    elif isinstance(param, str):        # option 2
>        if os.path.isfile(param):
>            return "FILE"
>        else:
>            return "STR"
>    else:
>        return None
>
> print main(param=[1,2,3])
> print main(param="d:/temp/txt.txt")
> print main(param="yeah but yeah, but no")
> print main(param=1.0)
>
>
>
>
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

isinstance can take a tuple of types:

def validate_input (param):
   if isinstance(param, (list, tuple)): #option 1
   return "LT"
   elif isinstance(param, str):# option 2
   if os.path.isfile(param):
   return "FILE"
   else:
   return "STR"
   else:
   return None

Also, file-type objects aren't instances of str...

-- 
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input validation

2009-09-03 Thread Alan Gauld


"Albert-Jan Roskam"  wrote

I'm wondering what is the most common method of input validation. 


Any and all of the methods will work in different situations but its 
generally best to use duck typing and try to write code that works 
for any type as far as possible.


Then use exceptions to catch the ,erm, exceptions...

So you could do

try: param.readlines()
except AttributeError:   # not a file like object
 try param.uppercase()
 except AttributeError:   # not a string


And so on.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] input and output files from terminal

2008-04-17 Thread Alan Gauld

"Brain Stormer" <[EMAIL PROTECTED]> wrote

> Thanks for the file direction method but how do I get the names of 
> the files
> so I can use it inside my program.

I'm not sure I understand.

Thepoint of using redirection is that your code doesn't need to know
anything about the files, it just reads/writes to/from stdin/stdout.

The OS connects the bits together at runtime.

>> Easier to use file redirection:
>>
>> python test.py < inputfile > outputfile

So you can provide any name you like for inputfile
and outputfile when you execute the program.

If you want the program to read/write to a specific file then
use the standard open()/read/write functions

Or am I missing something?

Alan G. 


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


Re: [Tutor] input and output files from terminal

2008-04-17 Thread Brain Stormer
Actually, Let me take that back with the raw_input comment since it is not
the idle issue but I didn't want to the program to be interactive so I
didn't want to wait for someone to put the information and press enter.
Thanks for the file direction method but how do I get the names of the files
so I can use it inside my program.

On Mon, Apr 14, 2008 at 2:57 PM, Alan Gauld <[EMAIL PROTECTED]>
wrote:

>
> "Brain Stormer" <[EMAIL PROTECTED]> wrote
>
> >I have a python program which works fine when run using idle but I
> >would
> > like call the program from the terminal.
> >
> > python test.py -i inputfile -o outputfile
>
> Easier to use file redirection:
>
> python test.py < inputfile > outputfile
>
> The -i flag in particular might conflict with Pythons own -i option.
>
> > I tried with raw_input but that only works in idle.
>
> What makes you think that?
> raw_input is the normal way to get input from stdin.
>
> Can you explain what you did and what the result was?
> Perhaps with a short code example?
>
> Try this for example:
>
> 
>
> name = raw_input('What's your name? ')
> print "hello", name
>
> 
>
> That can be run in IDLE or in a command window
> or using file redirection as described above.
>
> Tell us how you get on...
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread Alan Gauld

"Brain Stormer" <[EMAIL PROTECTED]> wrote

>I have a python program which works fine when run using idle but I 
>would
> like call the program from the terminal.
>
> python test.py -i inputfile -o outputfile

Easier to use file redirection:

python test.py < inputfile > outputfile

The -i flag in particular might conflict with Pythons own -i option.

> I tried with raw_input but that only works in idle.

What makes you think that?
raw_input is the normal way to get input from stdin.

Can you explain what you did and what the result was?
Perhaps with a short code example?

Try this for example:



name = raw_input('What's your name? ')
print "hello", name



That can be run in IDLE or in a command window
or using file redirection as described above.

Tell us how you get on...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] input and output files from terminal

2008-04-14 Thread Brain Stormer
I used the optparse module since that is exactly what I wanted.  Here is my
code:

import sys
from optparse import OptionParser
import os

parser = OptionParser()
parser.add_option("-i", "--input", dest="infile",
help="input FILE to convert", metavar="FILE")
parser.add_option("-o", "--output", dest="outfile",
help="output FILE to convert to", metavar="FILE")
(options, args) = parser.parse_args()

if not os.path.isfile(options.infile):
print "Input files does not exit...Quitting"
sys.exit()
elif os.path.isfile(options.outfile):
print "Output file exists, Remove it first"
sys.exit()

Thanks everyone.


On Mon, Apr 14, 2008 at 1:14 PM, <[EMAIL PROTECTED]> wrote:

> look at the OptParse module, with this u can easily realize such things.
> http://docs.python.org/lib/module-optparse.html
>
>
> On Mon, Apr 14, 2008 at 12:55:07PM -0400, Brain Stormer wrote:
> > I have a python program which works fine when run using idle but I would
> > like call the program from the terminal.
> >
> > python test.py -i inputfile -o outputfile
> >
> > I tried with raw_input but that only works in idle.  Can this be
> achieved?
> > Thanks
>
> > ___
> > 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 maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread bhaaluu
On Mon, Apr 14, 2008 at 12:55 PM, Brain Stormer <[EMAIL PROTECTED]> wrote:
> I have a python program which works fine when run using idle but I would
> like call the program from the terminal.
>
> python test.py -i inputfile -o outputfile
>
> I tried with raw_input but that only works in idle.  Can this be achieved?
>  Thanks
>
> ___
>  Tutor maillist  -  Tutor@python.org
>  http://mail.python.org/mailman/listinfo/tutor

Please see:
http://www.faqs.org/docs/diveintopython/kgp_commandline.html

>From the book: Dive into Python.
Source code examples from the book:
http://diveintopython.org/download/diveintopython-examples-4.1.zip

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread linuxian iandsd
i think you need to try :

cat input.txt | /usr/bin/python test.py >output.txt
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input and output files from terminal

2008-04-14 Thread v2punkt0
look at the OptParse module, with this u can easily realize such things.
http://docs.python.org/lib/module-optparse.html


On Mon, Apr 14, 2008 at 12:55:07PM -0400, Brain Stormer wrote:
> I have a python program which works fine when run using idle but I would
> like call the program from the terminal.
> 
> python test.py -i inputfile -o outputfile
> 
> I tried with raw_input but that only works in idle.  Can this be achieved?
> Thanks

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

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


Re: [Tutor] Input

2008-01-16 Thread Ricardo Aráoz
Kent Johnson wrote:
> Ricardo Aráoz wrote:
> 
>> _validChars = {
>> 'X' :
>> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>> , '9' : '1234567890'
>> , '-' : '-1234567890'
>> , 'A' :
>> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>> , '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
>> _validKeys = _validChars.keys()
> 
> 
>> while maskChar not in _validKeys :
> 
> There is no need to make _validKeys, you can write
>   while maskChar not in _validChars
> which is actually more efficient, in general, because it is a hash table
> lookup instead of searching a list.
> 
> Kent
> 

Thanks Kent, I'll wait to see if there are more corrections and re-post
the corrected code.


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


Re: [Tutor] Input

2008-01-16 Thread Alan Gauld
"Tiger12506" <[EMAIL PROTECTED]> wrote
>> Of course I know and use reg. exps., the point of the function is 
>> not to
>> validate input but to force the proper input.
>
> So? Are you going to try to tell me that you can force particular 
> input
> without actually determining if its valid or not first? ;-)

regex is great for testing strings but the function posted tests
each character as it is input. Using regex you would need to
test the complete string after it was entered before getting
a reliable result.

I think thats the difference.

Alan G.



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


Re: [Tutor] Input

2008-01-16 Thread Ricardo Aráoz
Tiger12506 wrote:
>> Of course I know and use reg. exps., the point of the function is not to
>> validate input but to force the proper input.
> 
> So? Are you going to try to tell me that you can force particular input 
> without actually determining if its valid or not first? ;-)
> 
> Just a thought. 
> 


Are you going to try to tell me that it is better to check if ONE
character is valid with a reg.exp. that with a simple 'in' statement?

The purpose of the code is not to check input but to force it a
character at a time according to an input mask, it's a common enough
concept. Just do a bunch of raw_inputs inscribed in while loops with
their validations, then do it with this function and check the
readability of your code (not to talk about the length). Anyway it was
presented as a help for those who want it and as an exercise program to
be improved and learn from.


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


Re: [Tutor] Input

2008-01-15 Thread Tiger12506
> Of course I know and use reg. exps., the point of the function is not to
> validate input but to force the proper input.

So? Are you going to try to tell me that you can force particular input 
without actually determining if its valid or not first? ;-)

Just a thought. 

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


Re: [Tutor] Input

2008-01-15 Thread Kent Johnson
Ricardo Aráoz wrote:

> _validChars = {
> 'X' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
> , '9' : '1234567890'
> , '-' : '-1234567890'
> , 'A' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
> , '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
> _validKeys = _validChars.keys()


> while maskChar not in _validKeys :

There is no need to make _validKeys, you can write
   while maskChar not in _validChars
which is actually more efficient, in general, because it is a hash table 
lookup instead of searching a list.

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


Re: [Tutor] Input

2008-01-15 Thread Ricardo Aráoz
Tiger12506 wrote:
> Try regular expressions in the re module. This should make this code below 
> much much simpler. Downside is you have to learn a slightly different 
> syntax. Upside is - regular expressions are very powerful.
> 

Of course I know and use reg. exps., the point of the function is not to
validate input but to force the proper input.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input

2008-01-15 Thread Tiger12506
Try regular expressions in the re module. This should make this code below 
much much simpler. Downside is you have to learn a slightly different 
syntax. Upside is - regular expressions are very powerful.



> Last week someone had an issue with raw_input() and how to get input for
> a number. So I remembered my CP/M times and got to think of a little
> function I had there. The function is lost and my time is scarce but I
> made a little effort and here you have the results. It has loads of room
> for improvement and probably a few bugs but it's a starting point, and
> it should guarantee that you get the input you need.
> You just define your mask and the functions checks the input
> accordingly, it returns a string.
> You might improve it by displaying the mask, e.g. for mask = '.99'
> you might see in the screen .__ or for mask = '999-AAA::' you'd
> see ___-___::___ so the user will know the format of what's expected of
> him, also a beep on incorrect entry might prove nice.
>
> HTH
>
> ---
> import msvcrt
>
> _validChars = {
>'X' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>, '9' : '1234567890'
>, '-' : '-1234567890'
>, 'A' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>, '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
> _validKeys = _validChars.keys()
>
> def maskInput(mask, separators = True) :
>lmask = list(mask)
>lmask.reverse()
>usedMask = []
>retInput = ''
>c = ''
>maskChar = lmask.pop()
>try :
>while maskChar not in _validKeys :
>if separators :
>retInput += maskChar
>msvcrt.putch(maskChar)
>maskChar = lmask.pop()
>except IndexError : pass
>
>c = msvcrt.getch()
>while c != chr(13) :
>if maskChar and maskChar not in _validKeys and c in
> _validChars[lmask[-1]] :
>if separators :
>retInput += maskChar
>msvcrt.putch(maskChar)
>usedMask.append(maskChar)
>maskChar = lmask.pop()
>if usedMask and c == '\b' :
>try :
>if maskChar :
>lmask.append(maskChar)
>maskChar = usedMask.pop()
>retInput = retInput[:-1]
>msvcrt.putch(c)
>msvcrt.putch(' ')
>msvcrt.putch(c)
>while usedMask[-1] not in _validKeys :
>if maskChar :
>lmask.append(maskChar)
>maskChar = usedMask.pop()
>if separators :
>retInput = retInput[:-1]
>msvcrt.putch(c)
>msvcrt.putch(' ')
>msvcrt.putch(c)
>except IndexError : pass
>elif maskChar and c in _validChars[maskChar] :
>retInput += c
>msvcrt.putch(c)
>try :
>usedMask.append(maskChar)
>maskChar = lmask.pop()
>  #  while maskChar not in _validKeys :
>except IndexError :
>maskChar = ''
>c = msvcrt.getch()
>return retInput
>
> if __name__ == '__main__' :
>invar = maskInput('-.99')
>print
>print invar
>
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

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


Re: [Tutor] input file encoding

2007-09-11 Thread Tim Michelsen
> Not sure what you mean by "standard encoding" (is this an Ubuntu
> thing?) but essentially whenever you're pulling stuff into Python
As it was lined out by others I was printing to a linux terminal which 
had the encoding set to UTF-8.
Therefore and for further processing of the data I had to open it with 
the right encoding.


> In this case, assuming you have files in iso-8859-1, something
> like this:
> 

> 
> import codecs
> 
> filenames = ['a.txt', 'b.txt', 'c.txt']
> for filename in filenames:
>f = codecs.open (filename, encoding="iso-8859-1")
This piece of code did the trick. After a short adaption I had exactly 
what I wanted to achive.


Thanks you for your help.

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


Re: [Tutor] input file encoding

2007-09-11 Thread Kent Johnson
Tim Golden wrote:

> Ah, I see. I'm so used to Windows where there is, technically an encoding
> for the console window, but you can't really do anything about
> it (apart from the awkward chcp) and it isn't really in your face. I
> do *use* Linux sometimes, but I don't really think in it :)

Actually you would run into the same problems on Windows if you tried to 
print UTF-8 or Unicode data.

The only reason the Windows encoding is not in your face is that enough 
data is in ascii/latin-1/cp1252 that you can coast along in blissful 
ignorance. As soon as you have to deal with text in 
Japanese/Chinese/Korean/Russian/Turkish/Arabic/Greek/Hebrew/Thai/Klingon/etc 
you will have a rude awakening and a quick lesson in encoding awareness.

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


Re: [Tutor] input file encoding

2007-09-11 Thread Tim Golden
Kent Johnson wrote:
> Tim Golden wrote:

>> Not sure what you mean by "standard encoding" (is this an Ubuntu
>> thing?) 
> 
> Probably referring to the encoding the terminal application expects - 
> writing latin-1 chars when the terminal expects utf-8 will not work well.

Ah, I see. I'm so used to Windows where there is, technically an encoding
for the console window, but you can't really do anything about
it (apart from the awkward chcp) and it isn't really in your face. I
do *use* Linux sometimes, but I don't really think in it :)

 >> Tim Golden
>># you could do this:
>># text = text.encode ("utf-8")
>>print repr (text)
> 
> No, not repr, that will print with \ escapes and quotes.

I knew that (no, honestly ;). Since I wasn't sure what
the OP was after, I was using repr to *show* the escapes
and quotes really to indicate that he may not have wanted
them! (All right, I'll shut up now). Thanks for clarifying,
Kent.


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


Re: [Tutor] input file encoding

2007-09-11 Thread Kent Johnson
Tim Golden wrote:
> Tim Michelsen wrote:
>> Hello,
>> I want to process some files encoded in latin-1 (iso-8859-1) in my 
>> python script that I write on Ubuntu which has UTF-8 as standard encoding.
> 
> Not sure what you mean by "standard encoding" (is this an Ubuntu
> thing?) 

Probably referring to the encoding the terminal application expects - 
writing latin-1 chars when the terminal expects utf-8 will not work well.

Python also has a default encoding but that is ascii unless you change 
it yourself.

> In this case, assuming you have files in iso-8859-1, something
> like this:
> 
> 
> import codecs
> 
> filenames = ['a.txt', 'b.txt', 'c.txt']
> for filename in filenames:
>f = codecs.open (filename, encoding="iso-8859-1")
>text = f.read ()
>#
># If you want to re-encode this -- not sure why --

This is needed to put the text into the proper encoding for the 
terminal. If you print a unicode string directly it will be encoded 
using the system default encoding (ascii) which will fail:

In [13]: print u'\xe2'

Traceback (most recent call last):
   File "", line 1, in 
: 'ascii' codec can't encode 
character u'\xe2' in position 0: ordinal not in range(128)

In [14]: print u'\xe2'.encode('utf-8')
â

># you could do this:
># text = text.encode ("utf-8")
>print repr (text)

No, not repr, that will print with \ escapes and quotes.

In [15]: print repr(u'\xe2'.encode('utf-8'))
'\xc3\xa2'

And he may not want to change text itself to utf-8. Just
print text.encode('utf-8')

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


Re: [Tutor] input file encoding

2007-09-11 Thread Tim Golden
Tim Michelsen wrote:
> Hello,
> I want to process some files encoded in latin-1 (iso-8859-1) in my 
> python script that I write on Ubuntu which has UTF-8 as standard encoding.

Not sure what you mean by "standard encoding" (is this an Ubuntu
thing?) but essentially whenever you're pulling stuff into Python
which is encoded and which you want to treat as Unicode, you need
to decode it explicitly, either on a string-by-string basis or by
using the codecs module to treat the whole of a file as encoded.

In this case, assuming you have files in iso-8859-1, something
like this:


import codecs

filenames = ['a.txt', 'b.txt', 'c.txt']
for filename in filenames:
   f = codecs.open (filename, encoding="iso-8859-1")
   text = f.read ()
   #
   # If you want to re-encode this -- not sure why --
   # you could do this:
   # text = text.encode ("utf-8")
   print repr (text)



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


Re: [Tutor] Input from and output to a file

2007-02-07 Thread Kent Johnson
govind goyal wrote:
> hi,
>  
> 1) I want to read data not from  but from a file which is in 
> specified directory.
> 2) I want to redirect my output(which is by default STDOUT) to a file.
>  
> Can anybody suggest these queries?

One way to redirect stdin and stdout is just to do it on the commandline:
python myscript.py < myinput.txt > myoutput.txt

It is easy to read and write files in Python:
f = open('myinput.txt')
data = f.read()
f.close()

gets the contents of myinput.txt into data

f = open('myoutput.txt', 'w')
f.write(data)
f.close()

writes the contents of data to myoutput.txt.

There are many variations on this, any good tutorial will cover file I/O.

It is also possible to directly assign to sys.stdin and sys.stdout but 
I'm not sure that is the best solution for you...

Kent

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


Re: [Tutor] Input mask for console?

2006-09-14 Thread Chris Hengge
The chosen solution was posted by kent... he said getpass.getpass().
 
As far as a "sample" password... how do I display something I was asking how to hide? =P
 
>>> Enter Password: "nothing seen here" =D 
On 9/14/06, Tiago Saboga <[EMAIL PROTECTED]> wrote:
Em Quarta 13 Setembro 2006 21:55, Chris Hengge escreveu:> nevermind.. figured it out.. Thanks.
Hi Chris,It's not just for you, but I'd like to make a comment. When you write to thislist, remember that other people read your questions too, and may beinterested in the answers. By the way, I've learned a lot here just by
reading the q&a. But if we want it to be really useful to everybody, weshould try to post good questions (in your case, it was ok, but it could bebetter: you could have given the example of the password in the first mail)
*and* post the choosen solution.Thanks!Tiago.>> On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote:> > Chris Hengge wrote:> > > I need either a way to mask the input from a console, or a method to
> > > not display the typed characters to the screen. Someone point me in the> > > right direction?> >> > getpass.getpass() ?> >> > Kent> >> > ___
> > 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 maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input mask for console?

2006-09-14 Thread Tiago Saboga
Em Quarta 13 Setembro 2006 21:55, Chris Hengge escreveu:
> nevermind.. figured it out.. Thanks.

Hi Chris,

It's not just for you, but I'd like to make a comment. When you write to this 
list, remember that other people read your questions too, and may be 
interested in the answers. By the way, I've learned a lot here just by 
reading the q&a. But if we want it to be really useful to everybody, we 
should try to post good questions (in your case, it was ok, but it could be 
better: you could have given the example of the password in the first mail) 
*and* post the choosen solution.

Thanks!

Tiago.


>
> On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote:
> > Chris Hengge wrote:
> > > I need either a way to mask the input from a console, or a method to
> > > not display the typed characters to the screen. Someone point me in the
> > > right direction?
> >
> > getpass.getpass() ?
> >
> > Kent
> >
> > ___
> > 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 maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input mask for console?

2006-09-13 Thread Chris Hengge
I'm assuming I can use that like

usrpass = getpass.getpass(raw_input("Password: ")) 

On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote:
> Chris Hengge wrote:
> > I need either a way to mask the input from a console, or a method to not
> > display the typed characters to the screen. Someone point me in the
> > right direction?
> 
> getpass.getpass() ?
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Input mask for console?

2006-09-13 Thread Chris Hengge
nevermind.. figured it out.. Thanks.

On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote:
> Chris Hengge wrote:
> > I need either a way to mask the input from a console, or a method to not
> > display the typed characters to the screen. Someone point me in the
> > right direction?
> 
> getpass.getpass() ?
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Input mask for console?

2006-09-13 Thread Kent Johnson
Chris Hengge wrote:
> I need either a way to mask the input from a console, or a method to not
> display the typed characters to the screen. Someone point me in the
> right direction?

getpass.getpass() ?

Kent

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


Re: [Tutor] input with default value option

2006-04-11 Thread Alan Gauld
>> With raw_input(), it allows to input value. Can it be used to input value 
>> with default value option?
>>
> response = raw_input("Enter some data:")
> if not response: response = "default value"

This is one of the few places where I do use the short-circuit evaluation 
trick:

val = raw_input('> ') or myDefault

I reads well (IMHO) and works pretty much safely.

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] input with default value option

2006-04-10 Thread Danny Yoo


> With raw_input(), it allows to input value. Can it be used to input 
> value with default value option?

Hi Phon,

We can build your own function to do this.  Bob showed how to set up code 
so that the default's taken if the user just presses enter in his reply. 
Let's take a look at it again:

###
response = raw_input("Enter some data:")
if not response: response = "default value"
###


We can capture this as a function that takes in a question and a default 
answer:

##
def ask(question, default):
 response = raw_input(question)
 if not response:
 response = default
 return response
##


And now we have something that acts like raw_input(), but also gives the 
user the ability to get a default:

##
>>> ask("favorite color?", "Blue.  No yellow -- aaaugh!")
favorite color?red
'red'
>>> ask("favorite color?", "Blue.  No yellow -- aaaugh!")
favorite color?
'Blue.  No yellow -- aaaugh!'
>>> 
##

(In the second call to ask(), I just pressed enter.)


Does this make sense?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input with default value option

2006-04-10 Thread Bob Gailer
Keo Sophon wrote:
> Hi,
>
> With raw_input(), it allows to input value. Can it be used to input value 
> with default value option?
>   
response = raw_input("Enter some data:")
if not response: response = "default value"

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-24 Thread Alan Gauld
> Another newbe question! I use "while True: " to evaluate an
> expression, I see that you used while 1: .. what's the diffrence if
> any?!

Python only provided boolean literal values (True, False) relatively 
recently.
Long time Python programmers, especially those with a C background(*)
are used to writing 1 to mean True. It's a hard habit to break. But it means
exactly the same as True and since True is usually more readable its 
probably
better to use that. (In theory Python could change to make 1 and True non
compatible, but in truth thats extremely unlikely because it is such a
deeply embedded tradition and huge amounts of existing code would break!)

(*)
Strictly speaking the numeric definition is based on 0 being False and True
being "non-zero". Thus C programmers used to do this:

#define FALSE   0
#define TRUE !FALSE

This left the numeric value of TRUE up to the compiler, in most cases it 
would
be 1 but in some cases it could be -1 or very occasionally MAXINT (0x)
This led to strange behaviour such as:

if ((1-2) == TRUE) { // works in some compilers not in others!}

The correct way was to compare to FALSE or just use the result as a value:

if (2-1) {//this always works}

Pythons introduction of boolean type values should have gotten round all
that but unfortunately it doesn't:

>>> if (1-2): print 'True'
True
>>> if True: print 'True'
True
>>> if (1-2) == True: print 'True'
>>>

So unfortunately Pythons implementation of Boolean values is only
half True(sorry couldn't resist!:-). In a true boolean implementation
any non zero value should test equal to True...

No language is perfect!

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] Input checking [letters or numbers]

2005-12-23 Thread bob
At 11:28 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>On 12/23/05, Panagiotis Atmatzidis <[EMAIL PROTECTED]> wrote:
> > Hello Dany :-)
> >
> > On 12/23/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>[...]
> > >
> > >
> > > Hello Bob and Panagiotis,
> > >
> > > It might be good to make this number-reading thing a function, just to
> > > make it easier to reuse (and test!) it.  Let's call this input_number()
> > > for the moment.
> > >
> > > ###
> > > def input_number(prompt):
> > > """Reads an integer from the next line of input."""
> > > while 1:
> > > x = raw_input(prompt)
> > > if x.isdigit():
> > > return int(x)
> > > else:
> > > print 'Boo'
> > > ###
>[...]
> > > I added one more behavior so that input_number continues to ask 
> until it's
> > > satisified by a number.  Hope this helps!
> >
> > Yes, it really helps a lot. Now I can proceed with my script!!
>[...]
>
>Another newbe question! I use "while True: " to evaluate an 
>expression, I see that you used while 1: .. what's the diffrence if any?!

In this case, no difference. True and False are Python boolean 
constants, and also a subset of integer. So one may print True + 1 and see 2.

Conditional statements (while, if, elif) and the if clause of list 
comprehensions and generator expressions expect an expression that 
will be treated as True if not empty and False if empty. From the 
L:angRef: "In the context of Boolean operations, and also when 
expressions are used by control flow statements, the following values 
are interpreted as false: None, numeric zero of all types, empty 
sequences (strings, tuples and lists), and empty mappings 
(dictionaries). All other values are interpreted as true."

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread Kent Johnson
Panagiotis Atmatzidis wrote:
> Hello,
> 
> Can someone provide me with an error checking example about an x
> variable that needs to be number only? I used something like:
> 
>  def useridf():
>  print ""
>  print "WARNING: If you don't understand why this must be unique,
> exit and read the manual."
>  print ""
>  userid = input("x : ")
> 
> I know that "input" accepts only numbers, but I don't want the program
> to break if someone puts other chars in it. I want to, print "Only
> numbers are accepted." which is easy. But still I can't understand how
> to do the check using if/elif/else statements.

Another way to do this is to use raw_input() to get the input as a 
string, then just try to convert it to an int and catch any exception. 
This also works well encapsulated into a function:

def getInt(prompt):
   while 1:
 s = raw_input(prompt)
 try:
   return int(s)
 except ValueError:
   print 'Only numbers are accepted'

This approach will accept negative numbers as well as positive:

  >>> def getInt(prompt):
  ...   while 1:
  ... s = raw_input(prompt)
  ... try:
  ...   return int(s)
  ... except ValueError:
  ...   print 'Only numbers are accepted'
  ...
  >>> getInt('x: ')
x: ae
Only numbers are accepted
x: -4
-4

Kent

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread Panagiotis Atmatzidis
On 12/23/05, Panagiotis Atmatzidis <[EMAIL PROTECTED]> wrote:
> Hello Dany :-)
>
> On 12/23/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
[...]
> >
> >
> > Hello Bob and Panagiotis,
> >
> > It might be good to make this number-reading thing a function, just to
> > make it easier to reuse (and test!) it.  Let's call this input_number()
> > for the moment.
> >
> > ###
> > def input_number(prompt):
> > """Reads an integer from the next line of input."""
> > while 1:
> > x = raw_input(prompt)
> > if x.isdigit():
> > return int(x)
> > else:
> > print 'Boo'
> > ###
[...]
> > I added one more behavior so that input_number continues to ask until it's
> > satisified by a number.  Hope this helps!
>
> Yes, it really helps a lot. Now I can proceed with my script!!
[...]

Another newbe question! I use "while True: " to evaluate an
expression, I see that you used while 1: .. what's the diffrence if
any?!
--
Panagiotis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread bob
At 11:16 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>Hello there,
>
>Thank you for the prompt response.
>
>On 12/23/05, bob <[EMAIL PROTECTED]> wrote:
>[snip]
> > print input("x ; ")
> > and enter "Hello world"
>
> >>> x = input("x: ")
>x: hello world
>Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 1
> hello world
>  ^
>SyntaxError: unexpected EOF while parsing
>
>Just did.. and as you can see I get an error. I know because I read so
>in the tutorial I mentioned before.. I mean that it says so.. now I am
>taking the first steps into programming, hence I don't really know if
>there's another reason for input to break upon chars.

Enter "hello world" including the quotes.
input expects a Python expression.
hello world is not a Python expression
"hello world" is
[snip] 

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread Panagiotis Atmatzidis
Yeah works you're right. :-)

On 12/23/05, bob <[EMAIL PROTECTED]> wrote:
> At 11:16 AM 12/23/2005, Panagiotis Atmatzidis wrote:
> >Hello there,
> >
> >Thank you for the prompt response.
> >
> >On 12/23/05, bob <[EMAIL PROTECTED]> wrote:
> >[snip]
> > > print input("x ; ")
> > > and enter "Hello world"
> >
> > >>> x = input("x: ")
> >x: hello world
> >Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "", line 1
> > hello world
> >  ^
> >SyntaxError: unexpected EOF while parsing
> >
> >Just did.. and as you can see I get an error. I know because I read so
> >in the tutorial I mentioned before.. I mean that it says so.. now I am
> >taking the first steps into programming, hence I don't really know if
> >there's another reason for input to break upon chars.
>
> Enter "hello world" including the quotes.
> input expects a Python expression.
> hello world is not a Python expression
> "hello world" is
> [snip]
>
>


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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread Panagiotis Atmatzidis
Hello Dany :-)

On 12/23/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
> > x = raw_input("x : ")
> > if x.isdigit(): # ensure input is a number
> >y = int(x) # convert to integer
> > else:
> >print 'Boo"
>
>
> Hello Bob and Panagiotis,
>
> It might be good to make this number-reading thing a function, just to
> make it easier to reuse (and test!) it.  Let's call this input_number()
> for the moment.
>
> ###
> def input_number(prompt):
> """Reads an integer from the next line of input."""
> while 1:
> x = raw_input(prompt)
> if x.isdigit():
> return int(x)
> else:
> print 'Boo'
> ###
>
>
> Does this work?  Let's try it informally:
>
> ##
> >>> input_number('number please: ')
> number please: 1
> 1
> >>> input_number('number please: ')
> number please: 1234
> 1234
> >>> input_number('number please: ')
> number please: 1st
> Boo
> number please: 74
> 74
> >>>
> ##
>
> I added one more behavior so that input_number continues to ask until it's
> satisified by a number.  Hope this helps!

Yes, it really helps a lot. Now I can proceed with my script!!

Thank you for the reply,

Best Regards,

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread Panagiotis Atmatzidis
Hello there,

Thank you for the prompt response.

On 12/23/05, bob <[EMAIL PROTECTED]> wrote:
> At 10:15 AM 12/23/2005, Panagiotis Atmatzidis wrote:
> >Hello,
> >
> >Can someone provide me with an error checking example about an x
> >variable that needs to be number only? I used something like:
> >
> >  def useridf():
> >  print ""
> >  print "WARNING: If you don't understand why this must be unique,
> >exit and read the manual."
>
> You ask the user to exit but you don't tell him how to do that!
>
> >  print ""
> >  userid = input("x : ")
> >
> >I know that "input" accepts only numbers
>
> How did you "know" that? Try this:
> print input("x ; ")
> and enter "Hello world"

OSX atma ~ $ python
Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = input("x: ")
x: hello world
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 1
hello world
 ^
SyntaxError: unexpected EOF while parsing

Just did.. and as you can see I get an error. I know because I read so
in the tutorial I mentioned before.. I mean that it says so.. now I am
taking the first steps into programming, hence I don't really know if
there's another reason for input to break upon chars.

>>> x = input("x: ")
x: 12
>>>

>
> Truth is input() "accepts" anything and attempts to evaluate it as a
> Python expression. If that fails it raises an exception.

Okay.

>
> You should use raw_input() instead. This takes any input and returns
> it as a character string.

I already use raw_input for alphanumeric characters.

> x = raw_input("x : ")
> if x.isdigit(): # ensure input is a number
>y = int(x) # convert to integer
> else:
>print 'Boo"

Thank you for the sample code.

>
> >, but I don't want the program
> >to break if someone puts other chars in it. I want to, print "Only
> >numbers are accepted." which is easy. But still I can't understand how
> >to do the check using if/elif/else statements.
>
>

Best Regards,

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread Danny Yoo
> x = raw_input("x : ")
> if x.isdigit(): # ensure input is a number
>y = int(x) # convert to integer
> else:
>print 'Boo"


Hello Bob and Panagiotis,

It might be good to make this number-reading thing a function, just to
make it easier to reuse (and test!) it.  Let's call this input_number()
for the moment.

###
def input_number(prompt):
"""Reads an integer from the next line of input."""
while 1:
x = raw_input(prompt)
if x.isdigit():
return int(x)
else:
print 'Boo'
###


Does this work?  Let's try it informally:

##
>>> input_number('number please: ')
number please: 1
1
>>> input_number('number please: ')
number please: 1234
1234
>>> input_number('number please: ')
number please: 1st
Boo
number please: 74
74
>>>
##

I added one more behavior so that input_number continues to ask until it's
satisified by a number.  Hope this helps!

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


Re: [Tutor] Input checking [letters or numbers]

2005-12-23 Thread bob
At 10:15 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>Hello,
>
>Can someone provide me with an error checking example about an x
>variable that needs to be number only? I used something like:
>
>  def useridf():
>  print ""
>  print "WARNING: If you don't understand why this must be unique,
>exit and read the manual."

You ask the user to exit but you don't tell him how to do that!

>  print ""
>  userid = input("x : ")
>
>I know that "input" accepts only numbers

How did you "know" that? Try this:
print input("x ; ")
and enter "Hello world"

Truth is input() "accepts" anything and attempts to evaluate it as a 
Python expression. If that fails it raises an exception.

You should use raw_input() instead. This takes any input and returns 
it as a character string.
x = raw_input("x : ")
if x.isdigit(): # ensure input is a number
   y = int(x) # convert to integer
else:
   print 'Boo"

>, but I don't want the program
>to break if someone puts other chars in it. I want to, print "Only
>numbers are accepted." which is easy. But still I can't understand how
>to do the check using if/elif/else statements.

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


Re: [Tutor] input/output redirection

2005-09-08 Thread David Rock
* Lane, Frank L <[EMAIL PROTECTED]> [2005-09-08 09:49]:
> Hi List,
>  
> I wanted to take the stdout of a process and redirect it to stdin of a
> python script, then after playing with the input in the script I want to
> send it back to stdout (all of this to be done while the original
> process runs happily along).  I can't seem to figure out the correct
> syntax if this is possible.
>  
> e.g.
>  
> C:\> runner.exe | script.py
> C:\> runner.exe > script.py  # this overwrites your script!:-)

I use fileinput for most of my stdin text processing. It also give me
the flexibility of using it as a pipe OR assigning a wordlist of files
to the script instead.

http://www.python.org/doc/2.4.1/lib/module-fileinput.html

import fileinput
for line in fileinput.input():
process(line)


-- 
David Rock
[EMAIL PROTECTED]


pgp3RtUbUyLUC.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input/output redirection

2005-09-08 Thread Danny Yoo


On Thu, 8 Sep 2005, Lane, Frank L wrote:

> I wanted to take the stdout of a process and redirect it to stdin of a
> python script, then after playing with the input in the script I want to
> send it back to stdout (all of this to be done while the original
> process runs happily along).  I can't seem to figure out the correct
> syntax if this is possible.
>
> e.g.
>
> C:\> runner.exe | script.py


Hi Frank,

You've almost got it.  The syntax above should have worked.  But the
problem here is that you're running into a problem with the way Windows
runs Python scripts.  Alan Gauld ran into this a few weeks ago:

http://mail.python.org/pipermail/tutor/2005-August/041019.html

You may need to put a CMD wrapper around the Python script.  Apparently,
this makes Windows pleased enough to let it be used as part of a shell
pipeline.  The thread above should mention the workaround to get things
working.

Best of wishes!

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


Re: [Tutor] input/output redirection

2005-09-08 Thread Javier Ruere
Lane, Frank L wrote:
> Hi List,
>  
> I wanted to take the stdout of a process and redirect it to stdin of a
> python script, then after playing with the input in the script I want to
> send it back to stdout (all of this to be done while the original
> process runs happily along).  I can't seem to figure out the correct
> syntax if this is possible.
>  
> e.g.
>  
> C:\> runner.exe | script.py
> C:\> runner.exe > script.py  # this overwrites your script!:-)
>  
> e.g.
>  
> #!/usr/bin/env python
> import re
>  
> while 1:
> packet = sys.stdin.read()

  In the previous line, all input is read which is not ideal. Depending on the 
input a single line or part of it should be read so that the script can start 
working before runner.exe finishes.
  Now, once you have a workable chunck of the input, you can happily process it 
and write it out.

> if field in packet:
> # change it and put it back on the command window and get the
> next bunch of stuff
> sys.stdout.write()

  In the previous line, write is called with no arguments. It should recieve 
the string to output.

> I hope my question/intention is clear.

  The given code is not a working example. It would help if the code was more 
complete.

Javier

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


Re: [Tutor] input()

2005-04-29 Thread Alan Gauld
> Matrix = input("Matrix=")
> error=input("error=")
> alpha= input("alpha=")
>   using  Macpython it works fine but when I use a terminal all I get
is
> a blank line.

Can you tell us a bit more about how you areusing MacPython
and the terminal?

Macpython has a console which presents a Python prompt and you type
the commands as shown. If you want to run the program at the Terminal
you have two options:

1) write the program into a text file using vi, emacs, BB EDit or
similar.
   Then run the fuile using python:

$ python myscript.py

or

2) type python and type the commands in at the >>> prompt.

To use the script in the way you describe below you must go with
option (1)
and create a text file with the program in.

> When I try to enter at the command line I get this
> Matrix=error=alpha=


This actually looks like you are using a script file but then just
hiting
enter when prompted. Are you actually typing any input at the Terminal
prompt?
If so is it showing up anywhere?

> Also I need to redirect any output from the program into another
file,
> which is why I used the terminal in the first place. So, I guess I
have
> two problems
> 1. How do I redirect output using Macpython?

Thats difficult and I wouldn't even try. Running the program script
at the Termninal is the way to go.

> 2. How do I use input() while using a terminal?

First can you start Python in command prompt mode - so you get the >>>
prompt?

If so does using input() work there?

Second try a very simple program that asks the user for their name
and says hello back:

name = raw_input("What's your name? ")
print "Hello", name

[ Notice I used raw_input which is safer than input from a security
point
  of view, but you don;t need to worry too much about that just yet.]

Does that work as expected?

If so type it into a plain text file called hello.py
and try running it from the Terminal prompt by typing

python hello.py

Does that work?

Tell us how you get on.

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] input()

2005-04-29 Thread Ewald Ertl
Hi!

I don't have a Mac and so I don't know Macpython. 

on Fri, 29 Apr 2005 07:55:20 -0500  Servando Garcia <[EMAIL PROTECTED]> wrote :
-

Servando Garcia > Hello and  thanks in advance.
Servando Garcia >   I am trying to prompt the user for some input. I need 
three values 
Servando Garcia > from the user so,I used input() like so;
Servando Garcia > Matrix = input("Matrix=")
Servando Garcia > error=input("error=")
Servando Garcia > alpha= input("alpha=")
Servando Garcia >   using  Macpython it works fine but when I use a terminal 
all I get is 
Servando Garcia > a blank line. When I try to enter at the command line I get 
this
Servando Garcia > Matrix=error=alpha=
Here on my sun i get the following:

>>> a=input("hello=")
hello=5+6
>>> a
11


When calling help on input the result is the following:

>>> help(input)
Help on built-in function input:

input(...)
input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).


So the inputvalue is evaluated in python. 

Using raw_input() gives back the entered value: 

>>> a=raw_input("hello=")
hello=myInput
>>> a
'myInput'

Perhaps this work's also on a Mac



Servando Garcia > Also I need to redirect any output from the program into 
another file, 
Servando Garcia > which is why I used the terminal in the first place. So, I 
guess I have 
Servando Garcia > two problems

On a UNIX-Shell two programms are connected via the "|" - Pipe. 
The first one writes to stdout ( sys.stdout or print ) and the second 
reads from stdin

Servando Garcia >   1. How do I redirect output using Macpython?
Servando Garcia >   2. How do I use input() while using a terminal?
Servando Garcia > 
Servando Garcia > ___
Servando Garcia > Tutor maillist  -  Tutor@python.org
Servando Garcia > http://mail.python.org/mailman/listinfo/tutor
Servando Garcia > 


--- end --
HTH 

Ewald 

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


Re: [Tutor] Input to python executable code and design question

2005-01-10 Thread Danny Yoo


> >To help you out. You need some sort of error checking to be sure that
> >within your given range you won't get something like a math domain
> >error.
> >
> >
> Yes, I thought that:
> try:
> #function
> exception:
> pass


Hi Ismael,


Python's keyword for exception handling is 'except', so this can be
something like:

###
try:
some_function()
except:
pass
###


... Except that the 'except' block should seldom be so vacant like that.
*grin* There are two things we should try to do when exception handling:
handle only what we need, and report exception information when we do.


We really want to get the system to handle only domain errors, and
otherwise let the exception raise errors.  But because the block above
catches every Python error, even silly things like misspellings, it will
sweep programmer errors under the carpet.


For example, the code snippet:

###
>>> def sqrt(x):
... return y**0.5  ## bug: typo, meant to type 'x'
...
>>> try:
... sqrt("hello")
... except:
... pass
...
###

tries to make it look like we're catching domain errors, but the
overzealous exception catching disguises a really silly bug.


We can make the exception more stringent, so that we only catch domain
errors.  According to:

http://www.python.org/doc/lib/module-exceptions.html

there's are a few standard exceptions that deal with domains, like
ArithmeticError, ValueError, or TypeError.


Let's adjust the code block above so we capture only those three:

###
>>> try:
... sqrt("hello")
... except (ArithmeticError, ValueError, TypeError):
... pass
...
Traceback (most recent call last):
  File "", line 2, in ?
  File "", line 2, in sqrt
NameError: global name 'y' is not defined
###



Also, it might be a good idea to print out that a certain exception
happened, just so that you can tell the user exactly what's causing the
domain error.  The 'traceback' module can help with this:

http://www.python.org/doc/lib/module-traceback.html


For example:

###
try:
1 / 0
except:
print "There's an error!"
###

tells us that some wacky thing happened, but:


###
import traceback
try:
1 / 0
except:
print "Error:", traceback.format_exc()
###

tells us that the error was caused by a ZeroDivisionError.



Best of wishes to you!

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


Re: [Tutor] Input to python executable code and design question

2005-01-10 Thread Chad Crabtree
Ismael Garrido wrote:

> [EMAIL PROTECTED] wrote:
>
>> Quoting Ismael Garrido <[EMAIL PROTECTED]>:
>>
>>  
>>
>>> I am trying to make a program that will plot functions. For that,
I 
>>> need
>>> to be able to get an input (the function to be plotted) and
execute it.
>>>
> >
> >
> >So you want the user to be able to type something like "f(x) = 
> sin(2*x)" and
> >then your program will plot it --- is that correct?
>
> Yes, that's what I want.

I can understand you fear.   Check out this post that Danny made in 
October I found it very helpful.
http://mail.python.org/pipermail/tutor/2004-October/032364.html
This one by kent at the same time was good too.
http://mail.python.org/pipermail/tutor/2004-October/032340.html
I felt this was a very good and helpful.


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Jacob S.
I have grown to like VPython as the curve attribute really seems to do the
trick. If you get it working on a Tkinter canvas, I would like to see the
code as I haven't quite found a way to plot points on to one of those.  A
simple graph function in VPython... (it isn't the whole thing, believe
me...)  It already is more powerful than most graphing calculators--see
except comment.

def graphit(function):
m = curve(color=color.blue)
x = -15
while -15<=x<=15:
try:
m.append(pos=(x,eval(function),0))
except:
m = curve(color=color.red)  # This is to catch domain errors and
keep the curve from connecting points across asymptotes
x = x+0.05  # Yes it might be too high a precision, but I usually
use 0.005

I would like to see the executable. I don't know anything about Qbasic 4.5,
so I don't know if I could view the source, etc...
Tell me if you want cut and paste or attachment to see the program. By the
way, I don't want to give the impression that I'm anything much better
than a newbie myself. I just have a big mouth
It might help setting it up. It supports x functions and polar graphs as
well. Perhaps for the future I will try 3d graphs, since VPython supports
3d.
Hah! There's something I don't remember Tkinter Canvas being able to do.

Jacob

> Jacob S. wrote:
>
> >eval() is good and it can be done using it.
> >I wrote a -- IMHO -- really great functiongraphing program using vpython.
> >If you would like to see it, just reply and say so.
> >
> >
> Out of curiosity, I would like to see your program. There's always
> something to learn (and even more so for me, being a newbie)
>
> >Please tell me what you are using to plot the points. (big grin) Vpython,
> >wxpython, what?
> >I'm curious--it's just someone else is working on a project that I'm
working
> >on...
> >
> >
> At the moment, nothing :-s
> I'm learning Phyton, and I thought that this would be an interesting
> challenge. For what I've seen, Tkinter's Canvas 'could possibly' do the
> job. I still have to try it out. In case that didn't work, I was
> thinking in looking through wxpython.
>
>
> >To help you out.
> >You need some sort of error checking to be sure that within your given
range
> >you
> >won't get something like a math domain error.
> >
> >
> Yes, I thought that:
> try:
> #function
> exception:
> pass
>
>
> >If you want more suggestions, ask
> >Please, tell me how you're doing. It sounds interesting.
> >
> >
> At the moment, I have almost nothing. After John Fouhy's replies I have
> rewritten the few lines I had at least three times :o)
> It will be simple, I intend to support viewing specific parts of the
> function (instead of a fixed view), multiple graphs, perhaps an option
> to save/load functions. I first made a program like this in Qbasic 4.5,
> and thought doing it again in Python with an interface and more advanced
> options may be very entretaining. :-) I can send you the source/exe if
> you want (sadly you can't choose what you want to see in the exe
> version, the function must be hard-coded).
>
> Thanks
> Ismael
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

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


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Ismael Garrido
Jacob S. wrote:
eval() is good and it can be done using it.
I wrote a -- IMHO -- really great functiongraphing program using vpython.
If you would like to see it, just reply and say so.
 

Out of curiosity, I would like to see your program. There's always 
something to learn (and even more so for me, being a newbie)

Please tell me what you are using to plot the points. (big grin) Vpython,
wxpython, what?
I'm curious--it's just someone else is working on a project that I'm working
on...
 

At the moment, nothing :-s
I'm learning Phyton, and I thought that this would be an interesting 
challenge. For what I've seen, Tkinter's Canvas 'could possibly' do the 
job. I still have to try it out. In case that didn't work, I was 
thinking in looking through wxpython.


To help you out.
You need some sort of error checking to be sure that within your given range
you
won't get something like a math domain error.
 

Yes, I thought that:
try:
   #function
exception:
   pass

If you want more suggestions, ask
Please, tell me how you're doing. It sounds interesting.
 

At the moment, I have almost nothing. After John Fouhy's replies I have 
rewritten the few lines I had at least three times :o)
It will be simple, I intend to support viewing specific parts of the 
function (instead of a fixed view), multiple graphs, perhaps an option 
to save/load functions. I first made a program like this in Qbasic 4.5, 
and thought doing it again in Python with an interface and more advanced 
options may be very entretaining. :-) I can send you the source/exe if 
you want (sadly you can't choose what you want to see in the exe 
version, the function must be hard-coded).

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


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Jacob S.
I wondered when someone would ask something like this.

eval() is good and it can be done using it.
I wrote a -- IMHO -- really great functiongraphing program using vpython.
If you would like to see it, just reply and say so.

Pros and cons of calculating all first:
pro - easier to read code
con - user may feel insecure while the points are being calculated --
for example, say you type in a big, complicated function, and while the
computer
sits there and calculates the points, the user might feel that something is
wrong. On
the other hand, if you calculate each point on its own, points are
immediately put
on the screen so your user knows that the thing is working (if you get my
drift)

Please tell me what you are using to plot the points. (big grin) Vpython,
wxpython, what?
I'm curious--it's just someone else is working on a project that I'm working
on...

To help you out.
You need some sort of error checking to be sure that within your given range
you
won't get something like a math domain error.
Ex.

y = 'sqrt(x)'
x = -15
while -15<=x<=15:
print eval(y)

Gives you something like

Traceback blah, blah
...
Math domain error

If you want more suggestions, ask
Please, tell me how you're doing. It sounds interesting.

HTH,
Jacob Schmidt



> Hello
>
> I am trying to make a program that will plot functions. For that, I need
> to be able to get an input (the function to be plotted) and execute it.
> So, my question is, how do I use the input? I have found no way to
> convert the string to some kind of executable code.
>
> I did research the problem. And found two things, first, an
> unsatisfactory solution from:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217
> The code there, by means I cannot understand at all, executes a string
> as code. To be usable I have to make my code a huge string. It is not
> very elegant.
>
> The second possible solution I found was using eval, compile and/or
> exec. But I do not understand what do they do, or how to use them, for
> the matter.
>
> Related to the program I intend to do, which design would you say is
> more intelligent: one that first calculates the whole function, stores
> it, and then plots it; or one that calculates-plots-calc.-plot, and so on?
>
> Thanks for any information, and for your time.
> Ismael
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

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


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
Quoting Ismael Garrido <[EMAIL PROTECTED]>:

(Newbie looking scared) That's kind of hard for me... Parsing it myself
is too complex for me. Also, I hoped Python's math would do the job for
me, so I wouldn't have to make what's already done in Python.

Writing  (and understanding) grammar is probably easier than you think --- once
you get over the syntax.  And they are fantastically useful things for doing any
sort of parsing.  But no matter..
If you are interested in learning about parsing, I suggest looking at pyparsing - it is IMO the 
easiest of the Python parsing frameworks. It has an example that implements a four-function 
calculator so that would get you off in the right direction.

http://pyparsing.sourceforge.net/
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Kent Johnson
You can you the exec statement to execute Python code from a string. The string could be from user 
input. So for example a user could input 'x*x' and you could do
 >>> inp = 'x*x'
 >>> func='def f(x): return ' + inp
 >>> func
'def f(x): return x*x'
 >>> exec func
 >>> f(3)
9

Now you have f(x) defined as a regular function and you can plot it the same as a function you wrote 
in your code.

The user will have to use whatever variable name you expect. And this is a huge security hole, you 
shouldn't do it if you don't trust the users.

Kent
Ismael Garrido wrote:
Hello
I am trying to make a program that will plot functions. For that, I need 
to be able to get an input (the function to be plotted) and execute it. 
So, my question is, how do I use the input? I have found no way to 
convert the string to some kind of executable code.

I did research the problem. And found two things, first, an 
unsatisfactory solution from: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217
The code there, by means I cannot understand at all, executes a string 
as code. To be usable I have to make my code a huge string. It is not 
very elegant.

The second possible solution I found was using eval, compile and/or 
exec. But I do not understand what do they do, or how to use them, for 
the matter.

Related to the program I intend to do, which design would you say is 
more intelligent: one that first calculates the whole function, stores 
it, and then plots it; or one that calculates-plots-calc.-plot, and so on?

Thanks for any information, and for your time.
Ismael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread jfouhy
Quoting Ismael Garrido <[EMAIL PROTECTED]>:

> (Newbie looking scared) That's kind of hard for me... Parsing it myself
> is too complex for me. Also, I hoped Python's math would do the job for
> me, so I wouldn't have to make what's already done in Python.

Writing  (and understanding) grammar is probably easier than you think --- once
you get over the syntax.  And they are fantastically useful things for doing any
sort of parsing.  But no matter..
 
> For what I understood of Mr. Clarke's mail, eval() would do the job (in
> spite of the security problem, I'm not concerned about that). Is that 
> correct? I guess I'll go read about that a bit more.

Yeah, probably.  For example:

>>> from math import *
>>> x = 3
>>> y = 2
>>> eval("2*x + 3*sin(x + y)")
3.1232271760105847

Note that if I had done "import math" instead of "from math import *", it would
not have worked, because "sin" would not have been defined.

So you could do something like:

def evalAt(function, x):
   """ Evaluate a function (as a string) at a given point. """
   return eval(function)
# This is equivalent to: evalAt = lambda function, x: eval(function)

myFun = "2*x + 3*sin(x + y)"
evalFunction = lambda x: evalAt(myFun, x)
xPoints = [x / 1.0 for x in xrange(1)]
yPoints = map(evalFunction, xPoints)

One problem with this approach is that you are required to use 'x' as the
variable when you are typing in your function.

Oh, to answer your other question: It is almost certainly better to calculate
the points first, and then plot them.

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


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Ismael Garrido
[EMAIL PROTECTED] wrote:
Quoting Ismael Garrido <[EMAIL PROTECTED]>:
 

I am trying to make a program that will plot functions. For that, I need
to be able to get an input (the function to be plotted) and execute it.
>
>
>So you want the user to be able to type something like "f(x) = 
sin(2*x)" and
>then your program will plot it --- is that correct?

Yes, that's what I want.
>Maybe you could parse it yourself?  I have found SimpleParse quite 
easy to use
>--- http://simpleparse.sourceforge.net/ .  You will need to write your own
>grammar to describe functions

(Newbie looking scared) That's kind of hard for me... Parsing it myself 
is too complex for me. Also, I hoped Python's math would do the job for 
me, so I wouldn't have to make what's already done in Python.

For what I understood of Mr. Clarke's mail, eval() would do the job (in 
spite of the security problem, I'm not concerned about that). Is that 
correct? I guess I'll go read about that a bit more.

Thanks for your replies.
Ismael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Liam Clarke
Eep.


On Mon, 10 Jan 2005 13:04:33 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> I think you're looking for eval() - but that's a big security hole,
> and wouldn't handle f(x) notation overly well, unless you parse like
> John said.
> 
> 
> On Mon, 10 Jan 2005 12:52:24 +1300 (NZDT), [EMAIL PROTECTED]
> <[EMAIL PROTECTED]> wrote:
> > Quoting Ismael Garrido <[EMAIL PROTECTED]>:
> >
> > > I am trying to make a program that will plot functions. For that, I need
> > > to be able to get an input (the function to be plotted) and execute it.
> > > So, my question is, how do I use the input? I have found no way to
> > > convert the string to some kind of executable code.
> >
> > So you want the user to be able to type something like "f(x) = sin(2*x)" and
> > then your program will plot it --- is that correct?
> >
> > Maybe you could parse it yourself?  I have found SimpleParse quite easy to 
> > use
> > --- http://simpleparse.sourceforge.net/ .  You will need to write your own
> > grammar to describe functions --- something like this, I guess:
> >
> > eqn := fname, '(', varlist, ')=', expr
> > varlist := var, (',', var)*
> >
> > expr := atom, (binop, atom)?
> > atom := var / (fun, '(', expr, ')') / num
> > fun := 'sin' / 'cos' / 'tan' / ...
> >
> > var := char
> > fname := char+
> > num := digit+
> > binop := '+' / '*' / '/' / '-'
> >
> > char := [a-zA-Z]
> > digit := [0-9]
> >
> > although you will need to work on that to get the precedence right and avoid
> > undesired recursion and the like.  SimpleParse will give you a tree (made of
> > nested tuples) representing your function.  You can then have a go at 
> > converting
> > the tree to a function.
> >
> > I guess the standard way to do this would be something like:
> >
> > def convert(node):
> > functionName = node[0]
> > children = node[1]
> > if functionName == '*':
> > return convert(children[0]) * convert(children[1])
> > elif functionName == '+':
> > ...
> >
> > But you may be able to come up with something more clever.
> >
> > Hope this helps.
> >
> > --
> > John.
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> 
> --
> 'There is only one basic human right, and that is to do as you damn well 
> please.
> And with it comes the only basic human duty, to take the consequences.
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >