#1
  1. Caress me down
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Location
    Pennsylvania
    Posts
    289
    Rep Power
    511

    need raw_input and protect bad input help


    i am a beginning programmer and i want to know the difference between input and raw_input is. by the looks of it before raw_input is used to protect from bad input but what exactly does it do?

    also how can i protect from bad input in a text entry field in tkinter? for example in my text entry field it asks you to input only 1 letter and it can only be a letter. i was thinking of using an if statement. like
    Code:
    if x in char:  #x is letter and char is list of alphabet
         run_program
    else:
         run_badinput
    i was thinking something like that but i saw someone use a "try" statement before. is that a better way and how do you use it?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    55
    Rep Power
    10

    raw_input fun


    I can't help you with the tkinter stuff, but the raw_input function allows you to accept user input; eg:

    words=raw_input("Type some stuff")
    #hello world!
    print words
    #hello world!

    On the kind of input you expect the user to enter, you can convert the data by putting str, int, etc. in front of the raw_input statement. What I like to do is take the raw_input given, copy it, and convert it to the type that works for the application, that way you have both to use, which is handy, depending on how you have to manipulate the user input. But again, that depends on what else is in your code.
    Hope this helps
    B.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    55
    Rep Power
    10

    ...and more fun


    I don't know much about tkinter modules and functions, but for python, I would write the line something like:

    Code:
    if x.isalpha()==True and len(x)==1:
         run_program
    if x.isalpha()==True and len(x)!=1:
         run_badinput
    of course you could also do it as just x.isalpha()==True, with contingencies on the len of x, but you get the idea.
    cheers
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    84
    Rep Power
    11
    in terms of taking input from the console, you should always use raw_input() rather than input(), as input() uses eval to convert the input to an integer which a mean person could use to their advantage if you want to get input in the form of an int that you can work with mathematically, use int(raw_input("Int: "))
  8. #5
  9. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    As rabbit mentioned input() is a nice security risk; one that should have never found its way into the language if you ask me . Given a prompt that uses input it's surprisingly easy to execute commands on the computer in question i.e.

    Code:
    Mark-Smiths-Computer:~ Mark$ ls
    Desktop         Downloads       Movies          Pictures        Public
    Documents       Library         Music           Projects        Sites
    Mark-Smiths-Computer:~ Mark$ python2.4 
    Python 2.4 (#1, Dec 12 2004, 22:12:51) 
    [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> input('Enter a Number: ') #Friendly user...
    Enter a Number: 20
    20
    >>> input('Enter a Number: ') #Not so friendly...
    Enter a Number: __import__('os').popen('ls').read()
    'Desktop\nDocuments\nDownloads\nLibrary\nMovies\nMusic\nPictures\nProjects\nPublic\nSites\n'
    >>>
    Note: this works because calling input() is the same as doing eval(raw_input()). Using eval is less dangerous than exec but you still need to be very careful where you use it .

    Everyone has to convert user input to a desired type at some point often many times in a program! If so you should write a function to handle the details for you and call it whenever you need to get input of that type . Here's an example of this:

    Code:
    #!/usr/bin/env python
    
    def castInput(prompt, cast):
        try:
            #Tries to cast the users input to the desired type. If this fails
            #(raises a ValueError) the function is called recursively until a
            #valid value is given.
            cast(raw_input(prompt))
        except ValueError:
            castInput(prompt, cast)
            
    if __name__ == '__main__':
        castInput('Enter a string: ', str) #Enter any value here.
        castInput('Enter an int: ', int)
        castInput('Eneter a float: ', float)
    As for your problem I would do something like this (below). This simply says if the length of the users input (x) is 1 then we're good. Otherwise we have a little problem.

    Code:
    if len(x) == 1:
        #Good input
    else:
        #Bad input
    Again I don't know much about TKinter sorry so I can't really help much there sorry.

    Hope this helps,

    Mark.
    programming language development: www.netytan.com Hula

  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    394
    Rep Power
    52
    Hi!

    I think there is no problem with "bad input" in an Entry in Tkinter, because entry.get() always returns a string.
    To check the input or restrict the input length, have a look at Fredrik Lundh's validating entry widget.

    Regards, mawe
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2005
    Posts
    78
    Rep Power
    10
    Originally Posted by burninator
    Code:
    if x.isalpha()==True and len(x)==1:
         run_program
    if x.isalpha()==True and len(x)!=1:
         run_badinput
    Any true expression evaluates to True. It's also good to not evaluate the same thing multiple times. You thus only need:
    Code:
    if x.isalpha():
        if len(x)==1:
            run_program()
        else:
            run_badinput()
    --OH.
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11
    or how about you do something like this.

    Code:
    from Tkinter import *
    import time
    
    root = Tk()
    
    char = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    
    def check():
        for x in text.get():
            if x in char:
                time.sleep(1)
                textx.set(x)
    
    text = StringVar(root)                        
    text.set("")
    
    textx = StringVar(root)                        
    textx.set("")
    
    Entry(root,textvariable=text).pack()
    
    Button(root,text="check",command=check()).pack()
    
    Label(root,textvariable=text).pack()
    Label(root,textvariable=textx).pack()
    
    root.mainloop()
    This code does not work directly something is wrong i still have to learn it again.

    But I would think something like that
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    394
    Rep Power
    52
    Hi!

    Code:
    from Tkinter import *
    import tkMessageBox
    
    max_len = 1
    
    def check():
        text = e.get()
        if text.isalpha() and len(text)<=max_len:
            tkMessageBox.showinfo(
                    "Good job","Yes, <%s> is a valid input." % text)
            # and do something else
        else: 
            tkMessageBox.showwarning("No","Bad Input!")
    
    root = Tk()
    e = Entry()
    e.pack(side=LEFT)
    Button(text="Check", command=check).pack(side=LEFT)
    root.mainloop()
    Regards, mawe

IMN logo majestic logo threadwatch logo seochat tools logo