Shinyshell Community Forums > Coding >
Python. ;D


[1]


May 22 02008, 12:57 GMT
Nick^
merciful justice

Nick's avatar
Location: Brisbane, Australia
Post count: 78
au
Anywho, just last night I finally opened up Komodo and started trying to write some Python code.

I first started off normally, with the:

#!/usr/bin/python 

import cgi

# print content type
print "Content-Type:text/html\n"
#!/usr/bin/python

import cgi

# print content type
print "Content-Type:text/html\n"
]]>


I then uploaded to my server, and obviously it didn't work. After much thinking, I remember about the UNIX line endings and found the option and changed it. Once again I uploaded the file and it still didn't work.. Hmm.. I then realised I had to uncheck the box which was titled "preserve current lines". Yet again, I uploaded and to my dismay it still didn't work. Finally, I remembered that I had to CHMOD the file to 755, so I did and it worked ;D Obviously, I'm just starting out with Python.

Anywho, I was wondering about a few things..

Firstly, how do you print variables and normally text within a single print statement? In PHP you could just go: print "Welcome, " . $username . "!"; but I have no idea how to do it in Python. Hah.

Secondly, how do the if statements work in Python? I think it's something like:

if variable: 

#conditionals
if variable:

#conditionals
]]>


But how do you let Python know that you're done with the if thingo? And yeah. If you could just explain the whole thing in general that would be nice.

Nextly (hah), how do the MySQL functions work in Python? I have no clue... Hah.

Finally, is there somewhere I can find a tutorial on Python? I've tried google, but it keeps coming up with the Python.org tutorial which I find to be really annoying. Any other suggestions? Maybe I don't need a tutorial though, hahahaha.

Anywho, yeah. XDD I suck at Python. D: Hopefully by the start of June I'll at least have enough knowledge to code a simple news system... Well, I can only help. xD


______________________________
Lazurane

May 22 02008, 14:28 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
Well placing variables into a string and then printing it is really easy. Take a look-see:

# username is a string, so you can do this two ways 
# (though the second is better, in my opinion)
print "Hello, " + username
print "Hello, %s" % username

# userid is an integer type, so you have to explicitly
# convert it to a string before you can treat it as string
print "Your user ID is: " + str(userid)
print "Your user ID is: %s" % userid
# username is a string, so you can do this two ways
# (though the second is better, in my opinion)
print "Hello, " + username
print "Hello, %s" % username

# userid is an integer type, so you have to explicitly
# convert it to a string before you can treat it as string
print "Your user ID is: " + str(userid)
print "Your user ID is: %s" % userid
]]>

As you can see, using the second method (which is just inserting variables into a string with special placeholders) is much easier, because you don't have to pay attention to the type of variable you're inserting - Python, unlike PHP or Perl, can't transparently convert one type into another (integer to string in this case). A percent sign in a string followed by a special letter indicates that it is a placeholder. The ones you'll need are: %s (placeholder for string), %d (placeholder for decimal number) and %% (just an "escaped" version of a percent sign).

If you've got more than one placeholder, you have to specify the parameters as a tuple:
"Hello, %s, your user ID is %d. Welcome to %s!" % (username, userid, website_name) 
"Hello, %s, your user ID is %d. Welcome to %s!" % (username, userid, website_name)
]]>

And that's the basic syntax. You can use this more flexible method by providing the parameters as a dictionary:

"My name is %(first)s %(last)s" %{'first':'John', 'last':'Doe'} 
"My name is %(first)s %(last)s" %{'first':'John', 'last':'Doe'}
]]>

It's really simple to use and much better than concatenating strings using the + operator. If you're a little mystified by this feature, you should know PHP (like C) has a similar feature (albeit not as easy to use), as a part of the printf() function.

Python requires you to indent your code to tell it where blocks are, as you could have noticed from my bitfield permission article. Most coders use four spaces. I used tabs for a while, but it turns out four spaces really is better. Here are some examples:
if rank == admin: 
print "Welcome to the Admin CP"
else:
"Kindly leave."
if rank == admin:
print "Welcome to the Admin CP"
else:
"Kindly leave."
]]>

while count < 100: 
print count
count += 1
while count < 100:
print count
count += 1
]]>

Of course for shorter statements it's often much easier to do this:
try: import cPickle as pickle 
except ImportError: import pickle

# also...
if not userid: print "Please log in"
else: print "Welcome!"
try: import cPickle as pickle
except ImportError: import pickle

# also...
if not userid: print "Please log in"
else: print "Welcome!"
]]>

Now connecting to a database and querying. It's a rather silly procedure that I have simplified by using an abstraction class. You will most likely be using the MySQLdb module for Python. The standard code for something like this would look like:

import sys, MySQLdb 

# first connect to the db
try:
connection = MySQLdb.connect(
host = "localhost",
port = 3306, # default MySQL port, can be ommited
user = "user",
passwd = "pass",
db = "database_name",
)
# handle any errors connecting
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)

# create a database cursor and run a query
cursor = connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("""
SELECT comment.*, user.username, user.rank
FROM comments AS comment
LEFT JOIN users AS user ON (user.userid = comment.author)
WHERE comment.section = %s
LIMIT 20
""", (comment_section,))

# fetch resulting rows
rows = cursor.fetchall()

# loop through the rows and print the contents of the comment
for comment in rows:
print comment["contents"]
print "<br />"

# close the cursor and connection when done
cursor.close()
connection.close()
import sys, MySQLdb

# first connect to the db
try:
connection = MySQLdb.connect(
host = "localhost",
port = 3306, # default MySQL port, can be ommited
user = "user",
passwd = "pass",
db = "database_name",
)
# handle any errors connecting
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)

# create a database cursor and run a query
cursor = connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("""
SELECT comment.*, user.username, user.rank
FROM comments AS comment
LEFT JOIN users AS user ON (user.userid = comment.author)
WHERE comment.section = %s
LIMIT 20
""", (comment_section,))

# fetch resulting rows
rows = cursor.fetchall()

# loop through the rows and print the contents of the comment
for comment in rows:
print comment["contents"]
print "<br />"

# close the cursor and connection when done
cursor.close()
connection.close()
]]>

My code:
import Electron.db 

comments = db.query_read("""
SELECT comment.*, user.username, user.rank
FROM comments AS comment
LEFT JOIN users AS user ON (user.userid = comment.author)
WHERE comment.section = %s
LIMIT 20
""", (comment_section,))

for comment in comments:
print comment["contents"]
print "<br />"
import Electron.db

comments = db.query_read("""
SELECT comment.*, user.username, user.rank
FROM comments AS comment
LEFT JOIN users AS user ON (user.userid = comment.author)
WHERE comment.section = %s
LIMIT 20
""", (comment_section,))

for comment in comments:
print comment["contents"]
print "<br />"
]]>

As you can tell, it's much easier to just write your own class to interact with the database. But that's pretty advanced stuff for your current level, so you should stick to what you can do for now. I may make this code available for download so people can use it if they like.

Also, I unfortunately do not know of any good Python tutorials (gasp)

May 23 02008, 06:59 GMT
Nick^
merciful justice

Nick's avatar
Location: Brisbane, Australia
Post count: 78
au
Thanks! It really has helped. :D

One more thing, what does "import" do exactly?

I know you use def: to define functions, but what does import do? xD
______________________________
Lazurane

May 23 02008, 10:04 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
The import keyword "imports" a module. I guess in a way it's similar to PHP's include.

There are many modules that come with python by default, and you can use them without installing anything extra. These are: sys, os, date, time, datetime, re, cgi, pickle, hashlib and many others of course.

Of course there are many useful modules you can find on the internet and add them to the import path of Python (either by using a really cool tool called easy_install from the UNIX terminal or by manually uploading them with FTP to a directory Python looks in when using import). MySQLdb is one of these.

And naturally you can write your own modules, such as is the case for Electron.db.

September 28 02009, 00:44 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

I don't understand how to add to a database.

#!/usr/bin/python 

print "Content-Type: text/html\n"

import MySQLdb, sys

correct = 5

name = "Peter"

if correct == 5:
# first connect to the db
try:
connection = MySQLdb.connect(
host = "mysql.aiirodesign.com",
port = 3306, # default MySQL port, can be ommited
user = "heheusername",
passwd = "********",
db = "aiiro_islanddocks_sql",
)
# handle any errors connecting
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)

# create a database cursor and run a query
cursor = connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("""
INSERT INTO quiz1 (name) values(%s)
""", % name )

# close the cursor and connection when done
cursor.close()
connection.close()
print "omg"
#!/usr/bin/python

print "Content-Type: text/html\n"

import MySQLdb, sys

correct = 5

name = "Peter"

if correct == 5:
# first connect to the db
try:
connection = MySQLdb.connect(
host = "mysql.aiirodesign.com",
port = 3306, # default MySQL port, can be ommited
user = "heheusername",
passwd = "********",
db = "aiiro_islanddocks_sql",
)
# handle any errors connecting
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)

# create a database cursor and run a query
cursor = connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("""
INSERT INTO quiz1 (name) values(%s)
""", % name )

# close the cursor and connection when done
cursor.close()
connection.close()
print "omg"
]]>

September 28 02009, 00:59 GMT
Faltzer
Member

Faltzer's avatar
Location: Glendale, New York
Post count: 38
us
#!/usr/bin/python 

import MySQLdb

print "Content-Type: text/html\n\n"

correct = 5
name = 'Peter'

if correct == 5:
# first connect to the db
try:
cursor = MySQLdb.connect(host = "***",
user = "***", passwd = "***",
db = "***").cursor()
# handle any errors connecting
except MySQLdb.Error, e:
exit('Error %d: %s' % (e.args[0], e.args[1]))

# create a database cursor and run a query
cursor.execute('INSERT INTO quiz1 (name) values(%s)', name)
cursor.close()
print "omg"

import MySQLdb

print "Content-Type: text/html\n\n"

correct = 5
name = 'Peter'

if correct == 5:
# first connect to the db
try:
cursor = MySQLdb.connect(host = "***",
user = "***", passwd = "***",
db = "***").cursor()
# handle any errors connecting
except MySQLdb.Error, e:
exit('Error %d: %s' % (e.args[0], e.args[1]))

# create a database cursor and run a query
cursor.execute('INSERT INTO quiz1 (name) values(%s)', name)
cursor.close()
print "omg" ]]>

______________________________
FHQ


[1]



Forum Information
  Currently Active Members [detailed] (0 members and ? guests)
-
Forum Statistics
Topics: 0, Posts: 0, Members: 108.
Welcome to our newest member, adamthephantump
Most members online was 5, on August 28 2009, at 21:49:28.
Legend
    Forums with unread topics in them are indicated by a strong yellow colouring around the forum icon.
    Forums with no unread topics have the standard pale yellow colouring around the forum icon.
    Forums with a blue arrow icon will redirect you to a non-forum page.
    Locked forums have a little padlock by their icon. You won't be able to post in these forums.
Shinyshell Home | Contact | Staff List | Archive | Top 

Conventional Login

Don't have an account? You may want to create one.

OpenID Login
OpenID login and registration is usable, but not finished.
What is OpenID?
Search

(advanced search)
Site Stats
  Total members: 108
  Latest member: adamthephantump
  Members currently online: 0
  Most online: 5 - Aug 28, 2009 (21:49)
  Front page hits: 88007
Developer info
  Site version: 3.5 Alpha
  16 queries - 9 templates
Under the Spotlight
Collide Site
Collide make fabulously dreamy electronic-industrial music, they're one of my favourite bands! Give them a chance to take control of your life - myspace | youtube - "Euphoria".

Collide Site - Hits: 4597

5/5 (2) | Rate this site?