|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
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
|
|||
|
|||
|
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
|
|||
|
|||
|
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. |
|
#3
|
||||
|
||||
|
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:
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. |
|
#4
|
|||
|
|||
|
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"
|
|
#5
|
||||
|
||||
|
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. |
|
#6
|
||||
|
||||
|
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. |
|
#7
|
|||
|
|||
|
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. ![]() |
|
#8
|
||||
|
||||
|
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. |
|
#9
|
|||
|
|||
|
Quote:
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. |
|
#10
|
|||
|
|||
|
Quote:
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 /')" |
|
#11
|
||||
|
||||
|
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! |
|
#12
|
|||
|
|||
|
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"
|
|
#13
|
||||
|
||||
|
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. |