接着学:
三、运算符和表达式:
+:两个对象相加,可以是字符串相加。如,'a'+'b' 得到‘ab’
*:两个数相乘或是返回一个被重复若干次的字符串。如,‘ab’*3得到‘ababab’
/:整数的除法得到整数结果,浮点数除法得到浮点数结果。如,4/3=1, 4.0/3=1.3333333333333333
**:返回x的y次幂,注意与 ^ 区别
//:取整除,返回商的整数部分。如,4//3.0=1.0
位运算:左移<<、右移>>、按位与&、按位或|、按位异或^、按位翻转~
逻辑运算:not、and、or
关系运算:<、>、<=、>=、==、!=
优先级跟C、C++差不多
四、控制流:
根你想象中一样,Python中也是三种控制流语句——if语句、for语句、while语句。
用法跟C差不多,只是Python中用elif表示else if,if、elif、else从句都必须在逻辑航结尾处有一个冒号,下面跟着一个相应的语句块。
#example1(注释用#)if..elif..else循环
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
print "(but you do not win any prizes!)"
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that.'
#example2 if..else循环
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'print 'Done'
#example3 for..in循环for i in range(1, 5):
print i
else:
print 'The for loop is over'#example3的输出:
1
2
3
4
The for loop is over其中range(1,5)给出[1,2,3,4]步长为1,向上延伸到第二个数,即它不包含第二个数。
另外 range(1,5,2)给出[1,3],步长为第三个数,向上延伸到第二个数。
#example4
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'#example5
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
continue
print 'Input is of sufficient length'
五、函数
函数通过def关键字定义,关键字后跟一个函数的标识符名称,然后跟一对圆括号。圆括号之中可以包括一些变量名,改行以冒号结尾。接下来是一块语句,他们是函数体,当然缩进是必须的!
如:def func():
print 'Hello World!'
如果要定义一个全局变量,要使用global语句。pass语句相当于C中的continue。
文档字符串:
#example6
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x = int(x)
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__
输出
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.
在函数的第一个逻辑行的字符串是这个函数的文档字符串 。其中,文档字符串也适用于模块和类,文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。 强烈建议你在使用文档字符串时遵循这个惯例。你可以使用__doc__(注意双下划线)调用printMax函数的文档字符串属性(属于函数的名称)。一定要记住Python把每一样东西都作为对象,包括这个函数。
六、模块
模块可以从其他程序输入以便利用它的功能,这也是我们使用python标准库的方法。
#example7
import sys #相当于#include <system.h>
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
输出
The command line arguments are:
using_sys.py
we
are
arguments
The PYTHONPATH is ['/home/swaroop/byte/code', '/usr/lib/python23.zip',
'/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',
'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload',
'/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/gtk-2.0']
如果我们只想在程序本身被使用的时候运行主块,而在它被别的模块输入的时候不运行主块,可以通过模块的__name__属性完成。
#example8
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
输出
>>> import using_name #__name__属性不是__main__,所以执行的是else的打印语句
I am being imported from another module
如果你想要直接输入argv 变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以用from sys import *语句。以下两个例子的输出结果完全相同:
#example9
from mymodule import sayhi, version
sayhi()
print 'Version', version
#example9‘
import mymodule
mymodule.sayhi()print 'Version', mymodule.version
当然,可以使用内建的dir()函数来列出模块定义的标识符。标识符有函数、类和变量。当你为dir()提供一个模块名的时候,它返回模块定义额名称列表。如果不提供参数,它返回当前模块中定义的名称列表。
$ python
>>> import sys
>>> dir(sys) # 获取sys模块上的属性列表
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type',
'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval',
'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding',
'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache',
'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions']
>>> dir() # 获得当前模块的属性列表
['__builtins__', '__doc__', '__name__', 'sys']
>>>
>>> a = 5 # 创建一个新的变量a 并给它赋值为5
>>> dir() # 检验dir
['__builtins__', '__doc__', '__name__', 'a', 'sys'] # 列表中增加了相应的值
>>>
>>> del a # 删除一个变量或者名称
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
>>>