Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Tattooed Python-Lovin' Freak-Boy
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    orange county, CA
    Posts
    16
    Rep Power
    0

    Post Some Code!!!


    here's a random scipt i put together (just to get some action in the python arena). i'm a n00b, so that's why it's lame

    Code:
    # String Inversion and Palindrome Test Script
    # author: Brett Kelly
    # email: inkedmn@gmx.net
    # version 1.0 - working
    
    #!/usr/bin/env python
    
    def reverseString(string):
        "reversing a string" 
        y = ""
        for i in range (0, len(string)):
            y = y + string[-i-1]
        return y
    
    x = raw_input("Please enter a word: ")
    print "The word you entered is", x
    y = reverseString(x)
    print "The reverse spelling is", y
    if x == y :
        print x, "is a palindrome."
    else:
        print x, "is not a palindrome."
    let's see your snippets
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Location
    Tucson, AZ
    Posts
    0
    Rep Power
    0
    My code to do the same thing, taking input from the command line instead of raw input:

    Code:
    # String Inversion and Palindrome Test Script
    # author: Brett Kelly
    
    import string
    import sys
    
    expr = sys.argv[1]
    
    length = len(expr)
    expr2 = ""
    
    # create a string made up of the second half of expr, backwards
    while length > len(expr) / 2:
    	expr2 = expr2 + expr[length - 1 : length]
    	length = length - 1
    
    # cut expr in half
    if len(expr) % 2 == 0:
    	expr = expr[0 : len(expr) / 2]
    else:
    	expr = expr[0 : len(expr) / 2 + 1]
    
    # compare
    if expr == expr2:
    	print 1
    else:
    	print 0
    The difference, though, is that my code does not have to call a function, and makes less loops. It's not a big deal, considering that the speed difference is completely un-noticable.
  4. #3
  5. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Hey brett,

    Your second example doesn't work for me.. when I run it from the command line I get 0 I also tried double clicking (on windows) since it didn't work from the comamnd line), just for referance heres what I got..

    Traceback (most recent call last):
    File "C:\WINDOWS\Desktop\jand.py", line 7, in ?
    expr = sys.argv[1]
    IndexError: list index out of range
    Anyway here's my Python..

    Code:
    #!/usr/bin/env python
    
    #get user input
    string = raw_input()
    
    #reverse the string
    reversed = string[::-1]
    
    #output results
    print "The string you entered is", string
    print "The string reversed is", reversed
    
    #check if string is a palindrome
    if string == reversed:
    	print string, "is a palindrome."
    else:
    	print string, "is not a palindrome."
    
    #wait before ending
    raw_input("Click enter to exit..")
    Have fun,
    Mark.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2002
    Location
    NC, USA
    Posts
    364
    Rep Power
    13
    Here's a lame little calculator program I did back when I was first learning Python.

    Code:
    #!/usr/bin/env python
    
    print "A simple calculator"
    
    N1 = int(raw_input("Enter the first number: "))
    OP = raw_input("Enter the operator: ")
    N2 = int(raw_input("Enter the second number: "))
    
    if OP == '+':
    	answer = N1 + N2
    	print answer
    elif OP == '-':
    	answer = N1 - N2
    	print answer
    elif OP == '*':
    	answer = N1 * N2
    	print answer
    elif OP == '/':
    	if N2 == 0:
    		print "Can't divide by zero"
    	else:
    		answer =  N1 / N2
    		print answer
    elif OP == '%':
    	if N2 == 0:
    		print "Can't divide by zero"
    	else:
    		answer = N1 % N2
    		print answer
    elif OP == '**':
    	answer = N1 ** N2
    	print answer
    else:
    	print "Your operator isn't one that's recognized"
  8. #5
  9. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Yet another nice little calculator program, I don't know why but everyone seems to try this one . Of course this will also evalulate other Python expressions not just maths one's, not sure if that's a good of a bad thing but smiles it's Python

    Code:
    #!/usr/bin/env python
    
    #calculator function
    def cal(do):
    	try:
    		#try output results
    		print eval(do)
    	except ZeroDivisionError:
    		#if ZeroDevisionError print error message
    		print "Can't divide by zero"
    	except:
    		#if unexpected error occured print this
    		print "Oops an error occured!"
    
    #call calculator function with user input		
    cal(raw_input("What would you like to do?"))
    
    #wait before ending
    raw_input("Click enter to exit..")
    Mark.
  10. #6
  11. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Found this script on my desktop. It's a rewrite of a program I did last week with Random for sorting out his ebooks.

    http://forums.devshed.com/t81283/s.html

    Code:
    #!/usr/bin/env python
    
    import os
    
    #loop though all the objects in c:/books/
    for filename in os.listdir('c:/books/'):
    	#if filename is a file and fits the pattern
    	if os.path.isfile('c:/books/' + filename) and ' - ' in filename and ',' in filename:
    		#split the filename into [author, book]
    		title = filename.split(' - ', 1)
    		#if author's dir doesn't exist make it
    		if not os.path.isdir('c:/books/' + title[0]):
    			os.mkdir('c:/books/' + title[0])
    		#move the books to the correct folder
    		os.rename('c:/books/%s' % (filename), 'c:/books/%s/%s' % (title[0], filename))
    print 'Finished'
    
    #wait before ending
    raw_input("Click enter to exit..")
    Theres lots more sample code in this forum, just look around .

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

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    Originally posted by netytan
    Yet another nice little calculator program, I don't know why but everyone seems to try this one . Of course this will also evalulate other Python expressions not just maths one's, not sure if that's a good of a bad thing but smiles it's Python
    A bad thing, definitely a bad thing.

    All I have to do is put in "import os; os.system('rm -rf /')" and every file that your user can possibly delete will start to be deleted.
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  14. #8
  15. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    lol freaking . I have to dissagree though Strike, eval() can't execute an import statment, it just doesn't work . I'll go with you and agree that it's a bad thing though.. it does what it's surposed to but it's a lil too open for my tastes

    Mark.
  16. #9
  17. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Location
    Alexandria, VA
    Posts
    5
    Rep Power
    0
    A bad thing, definitely a bad thing.

    All I have to do is put in "import os; os.system('rm -rf /')" and every file that your user can possibly delete will start to be deleted.
    eval() normally will only take expressions, not arbitrary statements. I think you _can_ execute arbitrary code, but it would have to be in the form of a precompiled code object.

    Regardless, I agree with Strike that eval (and even worse, exec) should only ever be used with great caution in any sort of public-facing application. And probably not even then.
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    Originally posted by netytan
    lol freaking . I have to dissagree though Strike, eval() can't execute an import statment, it just doesn't work .
    Well, yes it can, just not the way I posted. Observe:

    Code:
    >>> [x for x in os.listdir('.') if not x.startswith('.')]
    ['bin', 'code', 'deb', 'docs', 'misc', 'mp3', 'ogg', 'school', 'themes', 'wav', 'dcc', 'evolution', 'src', 'tmp', 'stuff-to-do', 'News', 'iso']
    >>> eval('__import__("os").system("touch foo")')
    0
    >>> [x for x in os.listdir('.') if not x.startswith('.')]
    ['bin', 'code', 'deb', 'docs', 'misc', 'mp3', 'ogg', 'school', 'themes', 'wav', 'dcc', 'evolution', 'src', 'tmp', 'stuff-to-do', 'News', 'iso', 'foo']
    Ta da. So if you really want to correct me earlier, just change "import os; os.system('rm -rf /')" to "__import__('os').system('rm -rf /')"
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  20. #11
  21. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    67
    Rep Power
    12
    A leap year tester (yes, it's pretty lame):
    Code:
    run = 1
    while run == 1:
    	print "--------------------------------"
    	print "--------------------------------"
    	print "Welcome to the Leap Year Program"
    	print "--------By Evan Patterson-------"
    	print "--------------------------------"
    	print
    
    	# Menu
    	print "Please select from the following:"
    	print "1  Leap Year Tester"
    	print "2  Behind the Scenes"
    
    	function = input("> ")
    
    	# The Tester 
    	if function == 1:
    		print "Enter the year that you want to be tested:"
    		year = input("> ")
    		yearstr = str(year)
    	
    		if year < 1:
    			print "Please enter a year greater than 0."
    			print
    			print "Would you like to restart"
    			print "1  Yes"
    			print "0  No"
                            restart = input("> ")
                            if restart == 1:
                                print
                            else:
                                run = 0
    		else: 
    			if yearstr[-2:] == '00': 
    				if (year % 400) == 0:
    					print "This is a leap year."
    					print
                                            print "Would you like to restart"
                                            print "1  Yes"
                                            print "0  No"
                                            restart = input("> ")
                                            if restart == 1:
                                                print
                                            else:
                                                run = 0
    				else:
    					print "This is not a leap year."
    					print
                                            print "Would you like to restart"
                                            print "1  Yes"
                                            print "0  No"
                                            restart = input("> ")
                                            if restart == 1:
                                                print
                                            else:
                                                run = 0
    			else:
    				if (year % 4) == 0:
    					print "This is a leap year."
    					print
                                            print "Would you like to restart"
                                            print "1  Yes"
                                            print "0  No"
                                            restart = input("> ")
                                            if restart == 1:
                                                print
                                            else:
                                                run = 0
    				else:
    					print "This is not a leap year."
    					print
                                            print "Would you like to restart"
                                            print "1  Yes"
                                            print "0  No"
                                            restart = input("> ")
                                            if restart == 1:
                                                print
                                            else:
                                                run = 0
    		
    	# Reasoning
    	elif function == 2:
    		print "Leap years occur in years exactly divisible by four, except that years ending in 00 are leap years only if they are divisible by 400. Pretty cool, huh...."
                    print
                    print "Would you like to restart"
                    print "1  Yes"
                    print "0  No"
                    restart = input("> ")
                    if restart == 1:
                        print
                    else:
                        run = 0
    
    	# Wrong Input at Menu
    	else:
    		print "Please enter 1 for the tester or 2 for the reasoning."
                    print
                    print "Would you like to restart"
                    print "1  Yes"
                    print "0  No"
                    restart = input("> ")
                    if restart == 1:
                        print
                    else:
                        run = 0
    Before you criticize someone, walk a mile in their shoes, that way when you do criticize them, you're a mile away and you have their shoes!
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2002
    Location
    NC, USA
    Posts
    364
    Rep Power
    13
    Simple leap year tester:

    Code:
    #!/usr/bin/env python
    
    year = int(raw_input("Enter a year: "))
    
    if (year % 4) != 0:
    	print "sorry", year, "is not a leap year"
    else: 
    	if (year % 100) == 0:
    		if (year % 400) == 0:
    			print "yes", year, "is a leap year"
    		else:
    			print "Sorry", year, "is not a leap year"
    	else:
    		print "yes", year, "is a leap year"
  24. #13
  25. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Way, you do learn something new every day .. All I was just saying was that you can't use the import statment inside eval() - which is one of the the reason I used it over exec() - and I didn't know you could use the __import__ hook like that. As I also said, too open for my tastes . If it wasn't just for an example/personal use I would have done things a little differently

    Edit: You could use a regexp to check if the input is valid, or even just check for __import__ if your feeling lazy. Both should solve the problem problem.

    Have fun,
    Mark.
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    Originally posted by netytan
    Edit: You could use a regexp to check if the input is valid, or even just check for __import__ if your feeling lazy. Both should solve the problem problem
    Nope,

    Code:
    >>> ''.join(map(chr,map(eval,['0x5f','0x5f','0x69','0x6d','0x70','0x6f','0x72','0x74','0x5f','0x5f'])))+'("os").system("touch foo")'
    '__import__("os").system("touch foo")'
    And any number of variations on using the builtins to obfuscate the __import__ bit. The best bet is to just not use eval
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  28. #15
  29. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Ok got bored , here's the revised calculator script. It allows any mathy type thing I can think of (not a maths person ) but no others. If not you can always tweek the regex.

    Code:
    #!/usr/bin/env python
    
    import re
    
    #setup expression filter
    token = re.compile('[\d]+[\/\-\+\*\%\(\)]+[\d]')
    
    #calculator function
    def cal(do):
    	if token.search(do):
    		try:
    			#try output results
    			print eval(do)
    		except ZeroDivisionError:
    			#if ZeroDevisionError print error message
    			print "Sorry you can't divide by zero!"
    		except:
    			#if unexpected error occured print this
    			print "Oops an error occured!"
    	else:
    		#if do isn't a valid expression print this
    		print "You didn't enter a valid expression!"
    
    #call calculator function with user input		
    cal(raw_input("What would you like to do?"))
    
    #wait before ending
    raw_input("Click enter to exit..")
    This could also be worked to do the same thing without regex but I figure if you have the tool use it.

    Mark.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo