python

基本语法

2018-08-23  本文已影响26人  落地成佛
>>>a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
len(list)  列表元素个数 
max(list)返回列表元素最大值 
min(list)返回列表元素最小值 
list(seq)将元组转换为列表 
list.append(obj)在列表末尾添加新的对象
list.count(obj)统计某个元素在列表中出现的次数
list.index(obj)从列表中找出某个值第一个匹配项的索引位置 
list.insert(index, obj)将对象插入列表 
list.pop([index=-1]])移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 
list.remove(obj)移除列表中某个值的第一个匹配项 
list.reverse()反向列表中元素 
list.sort(cmp=None, key=None, reverse=False)对原列表进行排序 
list.clear()清空列表 
list.copy()复制列表
if True:
    print ("Answer")
    print ("True")
       print("false")#出错
str='Runoob'
print(str)                 # 输出字符串Runoob
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符Runoo
print(str[0])              # 输出字符串第一个字符R
print(str[2:5])            # 输出从第三个开始到第五个的字符noo
print(str[2:])             # 输出从第三个开始的后的所有字符noob
print(str * 2)             # 输出字符串两次RunoobRunoob
print(str + '你好')        # 连接字符串Runoob你好
print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
hello
runoob(换行了)
print(r'hello\nrunoob')     # 在字符串前面添加一个 r,表示原始字符串,不会发生转hello\nrunoob
在 python 用 import 或者 from...import 来导入相应的模块。
将整个模块(somemodule)导入,格式为: import somemodule
从某个模块中导入某个函数,格式为: from somemodule import somefunction
从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
 
print(student)   # 输出集合,重复的元素被自动去掉 {'Mary', 'Jim', 'Rose', 'Jack', 'Tom'}
 
# 成员测试 结果:Rose 在集合中
if 'Rose' in student :
    print('Rose 在集合中')
else :
    print('Rose 不在集合中')
 
 
# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')

print(a - b)     # a和b的差集
print(a | b)     # a和b的并集
print(a & b)     # a和b的交集
print(a ^ b)     # a和b中不同时存在的元素
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2]     = "2 - 菜鸟工具"
 
tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}
 
 
print (dict['one'])       # 输出键为 'one' 的值
print (dict[2])           # 输出键为 2 的值
print (tinydict)          # 输出完整的字典
print (tinydict.keys())   # 输出所有键
print (tinydict.values()) # 输出所有值
#-----------------------------字典使用技巧-------------------------
 knights = {'gallahad': 'the pure', 'robin': 'the brave'}
 for k, v in knights.items():
    print(k, v)
#结果
gallahad the pure
robin the brave
#-----------------------------同时遍历两个或更多的序列,可以使用 zip() 组合-----------------
 questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
 for q, a in zip(questions, answers):
     print('What is your {0}?  It is {1}.'.format(q, a))

What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

if 语句

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

while 循环使用 else 语句
else 子句在穷尽列表或条件变为 false 时被执行,但被break终止时不执行

count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")
'''结果
0  小于 5
1  小于 5
2  小于 5
3  小于 5
4  小于 5
5  大于或等于 5
'''

函数

" -----------计算面积函数--------------------"
def area(width, height):
    return width * height
 
def print_welcome(name):
    print("Welcome", name)
 
print_welcome("Runoob")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))
"--------------------不定长参数-------------------------------"
# 加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1) #70
   print (vartuple) #(60, 50)
"----------------加了两个星号 ** 的参数会以字典的形式导入。----------------------"
# 可写函数说明
def printinfo( arg1, **vardict ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vardict)
"-----------------------匿名函数------------------------"
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2
 
# 调用sum函数
print ("相加后的值为 : ", sum( 10, 20 ))
print ("相加后的值为 : ", sum( 20, 20 ))
"------------------------函数修改外部变量-----------------"
num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num) #1
    num = 123
    print(num)#123
fun1()
print(num)#123

上一篇 下一篇

猜你喜欢

热点阅读