标签:style blog http io color ar 使用 sp for
变量命名:_num = 12 def myfunction (): global _num #引用全局变量 num = _num + 1 print 'myfunction num=' + str(num) myfunction()
>>> print repr(123L) 123L >>> print str(123L) 123
运算符
1)
>>> 5/6 0 >>> 5//6 0 >>> 5.0/6 0.8333333333333334 >>> 5.0//6 0.02)
>>> from __future__ import division >>> 5/6 0.8333333333333334 >>> 5//6 0 >>> 5.0/6 0.8333333333333334 >>> 5.0//6 0.03)
>>> -3**2 -9 >>> -(3**2) -9幂运算符(**)比取反运算符(一元减运算符)的优先级要高,所以-3**2和-(3**2)是等价的。
>>> True == 1 True >>> False == 0 True
i = 1 while i <= 5: print('The ' + str(i) + '\'s print. ') i += 1 else: print('End...')
array = [(1, 2), (3, 4), (5, 6)] for (x, y) in array: print(x, y);
for line in open('test.txt'): print line
names = ['admin', 'guest'] passwords = ['admin', 'guest'] for i in range(len(names)): print("name: %s, password: %s" % (names[i], passwords[i]))
names = ['admin', 'guest'] passwords = ['admin', 'guest'] for name, password in zip(names,passwords): print("name: %s, password: %s" % (name, password))zip将两个序列“压缩”到一起,然后返回一个元组的列表。
names = ['admin', 'guest'] for index, name in enumerate(names): if 'admin' in name: names[index] = 'root' print("index: %s, name: %s" % (index, name)) print(names)enumerate的主要作用时在提供索引的地方迭代索引值对。
name = 'admin' del name print name这个程序运行结果会报错:NameError: name ‘name‘ is not defined
name = 'admin' key = name del name print key这个程序运行结果为admin。移除name后并不影响key。因为python中删除的只是名称,而不是值本身。
exec "print 'hello'"执行结果为:hello
def function_name(arg1,arg2,....): statement return value其中,返回值不是必须的。如果没有return语句,则python默认返回值为None。
def login(username, password): if (username == 'admin') and (password == 'admin'): print 'login success!' else: print 'login error.....'可以使用如下语句调用:
login('admin', 'admin')
def login(username="guest", password="guest"): if (username == 'admin') and (password == 'admin'): print 'login success!' else: print 'login error.....'
login('admin', 'admin') login('admin') login(password='admin') login()
login success! login error..... login error..... login error.....第一种方式提供了两个参数,将默认的两个值覆盖。
def print_array(names=[]): for name in names: print(name) keys = ['admin', 'guest'] print_array(keys)
def print_names(* names): for name in names: print(name) print_names('root') print_names('admin', 'guest')
def print_key_value(** key_value): keys = key_value.keys() for key in keys: print("key: %s, value: %s" % (key, key_value[key])) print_key_value(username = 'admin', password = 'admin')运行结果:
key: username, value: admin key: password, value: admin
标签:style blog http io color ar 使用 sp for
原文地址:http://blog.csdn.net/iam333/article/details/41243249