SunQuest
           Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
  #1  
Old December 11th, 2001, 06:30 PM
inkedmn inkedmn is offline
Tattooed Python-Lovin' Freak-Boy
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: orange county, CA
Posts: 16 inkedmn User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via ICQ to inkedmn Send a message via AIM to inkedmn
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

Reply With Quote
  #2  
Old September 8th, 2003, 03:10 AM
schlagdogg schlagdogg is offline
Junior Member
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2003
Location: Tucson, AZ
Posts: 0 schlagdogg User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation 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.

Reply With Quote
  #3  
Old September 8th, 2003, 07:40 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
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..

Quote:

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.

Reply With Quote
  #4  
Old September 8th, 2003, 08:19 AM
damonbrinkley damonbrinkley is offline
Modz
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2002
Location: NC, USA
Posts: 364 damonbrinkley User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 m 18 sec
Reputation Power: 6
Send a message via AIM to damonbrinkley
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"

Reply With Quote
  #5  
Old September 8th, 2003, 09:39 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to 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

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.

Reply With Quote
  #6  
Old September 8th, 2003, 09:58 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
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.

Reply With Quote
  #7  
Old September 8th, 2003, 10:29 AM
Strike Strike is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: Houston, TX
Posts: 383 Strike User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 7
Send a message via ICQ to Strike Send a message via AIM to Strike Send a message via Yahoo to Strike
Quote:
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.

Reply With Quote
  #8  
Old September 8th, 2003, 10:37 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
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.

Reply With Quote
  #9  
Old September 8th, 2003, 10:47 AM
FiveGrainJa FiveGrainJa is offline
Junior Member
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Location: Alexandria, VA
Posts: 5 FiveGrainJa User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Quote:
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.

Reply With Quote
  #10  
Old September 8th, 2003, 12:48 PM
Strike Strike is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: Houston, TX
Posts: 383 Strike User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 7
Send a message via ICQ to Strike Send a message via AIM to Strike Send a message via Yahoo to Strike
Quote:
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 /')"

Reply With Quote
  #11  
Old September 8th, 2003, 02:13 PM
Baltor's Avatar
Baltor Baltor is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 67 Baltor User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 41 m
Reputation Power: 5
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!

Reply With Quote
  #12  
Old September 8th, 2003, 02:26 PM
damonbrinkley damonbrinkley is offline
Modz
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2002
Location: NC, USA
Posts: 364 damonbrinkley User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 m 18 sec
Reputation Power: 6
Send a message via AIM to damonbrinkley
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"

Reply With Quote
  #13  
Old September 8th, 2003, 03:33 PM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
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.

Reply With Quote