$ python ## Run the python interpreter
Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 6 ## set a variable in this interpreter session
>>> a ## entering an expression prints its value
6
>>> a + 2
8
>>> a = 'hi' ## a can hold a string just as well
>>> a
'hi'
>>> len(a) ## call the len() function on a string
2
>>> foo(a) ## try something that doesn't work
Traceback (most recent call last):
File "", line 1, in ?
NameError: name 'foo' is not defined
>>> ctrl-d ## type ctrl-d to exit (ctrl-z on Windows)
#!/usr/bin/python
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print 'Hello there', sys.argv[1]
# Command line args are in sys.argv[1], sys.argv[2] ..
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
从shell执行它:
$ python hello.py Guido
Hello there Guido
$ ./hello.py Alice # without needing 'python' first (Unix)
Hello there Alice
# Defines a "repeat" function that takes 2 arguments.
def repeat(s, exclaim):
"""Returns the string s repeated 3 times.
If exclaim is true, adds exclamation marks.
"""
result = s + s + s
if exclaim:
result = result + '!!!'
return result
# Notice also how the lines that make up the function or if-statement
# are grouped by all having the same indentation.
"def"语句使用圆括号和缩进定义一个函数。 下面的多行注释(docstring)标示了该函数的说明,可以通过__doc__这个特殊内置变量获得。 docstring可以是单行也可以是多行。在函数体内定义的变量属于本地变量,与其他函数的变量可以同名但没有任何冲突。
下面的代码调用了这个函数并打印结果:
help(sys.exit) -- docs for the exit() function inside of sys
help('xyz'.split) -- it turns out that the module "str" contains the built-in string code, but if you did not know that, you can call help() just using an example of the sort of call you mean: here 'xyz'.foo meaning the foo() method that runs on strings
help(list) -- docs for the built in "list" module
help(list.append) -- docs for the append() function in the list module