Helpful Information
 
 
Category: Python Programming
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 :D



# 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

My code to do the same thing, taking input from the command line instead of raw input:


# 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.

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..



#!/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.

Here's a lame little calculator program I did back when I was first learning Python.



#!/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"

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 :D



#!/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.

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



#!/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.

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 :D
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. :)

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.

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.

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:



>>> [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 /')"

A leap year tester (yes, it's pretty lame):

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

Simple leap year tester:



#!/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"

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.

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,



>>> ''.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 :)

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.



#!/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.

Here's my massive regex for valid python math expressions. It's pretty well-tested:


# Comment for the regexes:

# Numbers:
# \.\d+ : a number like ".023"
# | : or
# \d+(\.\d*)? : numbers like "1.23" or "10." or "1"
# L? : ends in L or not
number = "(\.\d+|\d+(\.\d*)?)L?"

# Operands:
# \(* : some or no leading parentheses
# -? : negative (or not)
#
# number goes here
#
# \)* : some or no trailing parentheses
operand = "(\(*-?" + number + "\)*)"

# Operators:
# [ : one of these single char operators
# % : modulus
# + : addition
# - : subtraction
# / : division
# * : multiplication
# ]| : or
# \*\* : exponentiation
operator = "([%+-/*]|\*\*)"

# Total regex:
#
# ^ : starts with
# \s* : any amount of space, or none at all
#
# some operand
#
# \s* : some or no space after this
# ( : and any number of operator/operand pairs after this
#
# operator goes here
#
# \s* : some or no spacing
#
# operand goes here
#
# \s* : any amount of trailing space, or none at all
# )+ : one or more operator/number pairs
# $ : must end here as well
self.regex = "^\s*" + operand + "\s*(" + operator + "\s*" + operand + "\s*)+$"

---edit----
this was scraped from one of my projects' source files, so the "self.regex" is what you want, but obviously it's just a string that you'd have to re.compile() first to get a proper RE object.










privacy (GDPR)