在Linux/Unix系统中,你可以在脚本顶部添加以下命令让Python脚本可以像SHELL脚本一样可直接执行:
#! /usr/bin/env python3.4
单行注释以#开头
多行注释用三个单引号(''')或者三个双引号(""")将注释括起来,可在一行,但不能在行尾
Python成员运算符(in、not in)
测试实例中包含了一系列的成员,包括字符串,列表或元组。
#!/usr/bin/python3
#coding=utf-8
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("1 - 变量 a 在给定的列表中 list 中")
else:
print ("1 - 变量 a 不在给定的列表中 list 中")
if ( b not in list ):
print ("2 - 变量 b 不在给定的列表中 list 中")
else:
print ("2 - 变量 b 在给定的列表中 list 中")
Python身份运算符(is、is not)
比较两个对象的存储单元是否相同
b = 30
if ( a is b ):
print ("3 - a 和 b 有相同的标识")
else:
print ("3 - a 和 b 没有相同的标识")
if ( a is not b ):
print ("4 - a 和 b 没有相同的标识")
else:
print ("4 - a 和 b 有相同的标识")
Python运算符优先级
运算符 | 描述 |
---|---|
** | 指数 (最高优先级) |
~ + - | 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) |
* / % // | 乘,除,取模和取整除 |
+ - | 加法减法 |
>> << | 右移,左移运算符 |
& | 位 'AND' |
^ | | 位运算符 |
<= < > >= | 比较运算符 |
<> == != | 等于运算符 |
= %= /= //= -= += *= **= | 赋值运算符 |
is is not | 身份运算符 |
in not in | 成员运算符 |
not or and | 逻辑运算符 |
在交互模式中,最后被输出的表达式结果被赋值给变量" _",需看成只读变量,不可对其赋值。
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
Python 字符串
续行符:\
换行符:\n(使用print输出时才会换行,否则不换行)
t_list = ["tony", 35, "feman", 178]
""" the value can not changed. """
t_tuple = ("jerry", 30, "man", 190)
t_set = {"tom", 20, "man", "tom", "tombed", "tom", "jack"} # the key is just only.
Python字典包含了以下内置方法:
序号 | 函数及描述 |
---|---|
1 | radiansdict.clear() 删除字典内所有元素 |
2 | radiansdict.copy() 返回一个字典的浅复制 |
3 | radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 |
4 | radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值 |
5 | key in dict 如果键在字典dict里返回true,否则返回false |
6 | radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组 |
7 | radiansdict.keys() 以列表返回一个字典所有的键 |
8 | radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default |
9 | radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 |
10 | radiansdict.values() 以列表返回字典中的所有值 |
Python3 条件控制
if 语句:使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
(在Python中没有switch – case语句)
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
Python 循环(for 和 while)
while 循环(Python中没有do..while循环)
while 判断条件:
statements
for语句(可遍历任何序列的项目,如列表、字符串等,用break退出循环,continue退出当前循环)
for <variable> in <sequence>:
<statements>
else:
<statements>
range()函数:会生成数列,可用于遍历数字序列,可指定步长、区间、
>>> for i in range(5):
... print(i)
...
pass语句:什么都不做,形同C中的“ ; ”一样
>>> while True:
... pass # 等待键盘中断 (Ctrl+C)
Python3 函数
基本格式:
def 函数名(参数列表):
函数体
def area(width, height):
return width * height
def print_welcome(name):
print("Welcome", name)
(1)变量作用域:函数内部的变量有局部作用域,定义在函数外的拥有全局作用域
(2)返回值:使用return返回,eg: return x,返回空: return
(3)可变参数列表:调用可变个数的参数.这些参数被包装进一个元组.在这些可变个数的参数之前,可以有零到多个普通的参数
def arithmetic_mean(*args):
sum = 0
for x in args:
sum += x
return sum
print(arithmetic_mean(45,32,89,78))
print(arithmetic_mean(8989.8,78787.78,3453,78778.73))