此笔记为拾零,非常适合有其他语言基础的Coder查找语法、规范使用。不过它不够详尽,对基本概念介绍极少,不推荐以此为第一语言学习资料,但不失为较好的复习资料。
输入输出
<string>input(<string>) #输入
>>> n = input('Please enter your age: ')
Please enter your age: 18
>>> type(n)
<class 'str'>
#默认输入格式为string,如需改变格式(如到整型):
n=int(input())
print(<string>) #输出
print(<int>)#输出
>>> print('smile','happy',13,15)
smile happy 13 15
>>> print('smile'+"happy")
smilehappy
#print()语句用","连接时自动加入空格,用"+"连接字符串时会直接连接。
引号
双引号中可以包含单引号,单引号中可包含双引号,三引号(“‘or”“”)可以包含单引号、双引号,可换行,可做注释使用。三者都可包含文字。
常用单引号surround strings
赋值符与等号
assignment token =
equal token ==
变量名规则
由数字、字母、下划线组成,区分大小写,第一个字符由字母或下划线组成
语句(Statement)
Every statement will be executed, but don’t produce any result.
assignment statement
for statement
while statement
Type fuction
Type Judgment
>>> type("Hello, World!")
<class 'str'>
>>> type(17)
<class 'int'>
>>>type(0)==int
True
Type conversion
>>> int("32")
32
>>> float(32)
32.0
>>> str(True)
'True'
>>> 'Happy'.lower()
'happy'
>>> 'happy'.upper()
'HAPPY'
len()
>>>len('Hello')
5
Evaluation of an expression
部分计算函数
>>> abs(-5)
5
>>> pow(2, 3)
8
>>> max(7, 11)
11
math.sqrt(x) # Use 'import math' First.
>>> eval('3+5')
8
计算符/操作符(Operators) 和计算数(Operands)
- 数字
Exponentiation Token ** Rem: 运算优先级仅次于括号
“/” always yields a floating point result.
Floor division “//”
Modulus operator “&” Rem: 运算优先级与乘法相同
>>>1//2
0
>>>1.0//2
0.0
>>>-1//2.0
-1.0
>>> 2.5//1
2.0
仅当两个操作数都为整型结果为整型,否之为浮点。
#向下取整函数
def num_takeint(x):
return(int(x//1)) #返回整型
#去尾取整函数 i.e.truncation towards zero
int(x) #type converter function
#Example
>>> x=3.3
>>> y=-3.3
>>> num_takeint(x)
3
>>> num_takeint(y)
-4
>>> int(x)
3
>>> int(y)
-3
>>>
- 字符串
>>> 'Fun'*3
'FunFunFun'
>>> 'all'+' love'
'all love'
- 运算顺序
像大多数语言一样,Python依然采用由右向左的运算方式。
>>> 2 ** 3 ** 2
512
>>> (2 ** 3) ** 2
64
- %
>>> string_1 = "Camelot"
>>> string_2 = "place"
>>> print ("Let's not go to %s. 'Tis a silly %s." % (string_1, string_2))
Let's not go to Camelot. 'Tis a silly place.
>>>
逻辑运算符 (Logical Operators)
x == y # Produce True if ... x is equal to y
x != y # ... x is not equal to y
x > y # ... x is greater than y
x < y # ... x is less than y
x >= y # ... x is greater than or equal to y
x <= y # ... x is less than or equal to y
经典逻辑符号 or and not
格式转换函数
>>> float(17)
17.0
>>> float("123.45")
123.45
>>> str(17)
'17'
>>> str(123.45)
'123.45'
列表
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]
>>> squares[0]
1
>>> squares[-1]
25
>>> squares[-3:] # -x: 得到列表下标为x及其之后的数
[9, 16, 25]
>>> squares[3:] # x: 得到列表下标为x及其之后的数
[16, 25]
>>> squares[2:4]
[9, 16]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> squares[0]=0
>>> squares
[0, 4, 9, 16, 25]
>>> squares.append(36) # 追加单个元素到List的尾部,只接受一个参数,参数可以是任何数据类型,被追加的元素在List中保持着原结构类型
>>> squares[3:5]=[] # 下标为3到下标为4
>>> squares
[0, 4, 9]
>>> a=[0, 0, 0, 3, 4]
>>> a[0]=[1,2] # 因此无法用此法删除单个元素
>>> a
[[1, 2], 0, 0, 3, 4]
>>> a[0:2]=[1,2,3] # 当转换元素数不同时,把相应位置元素用赋值符后元素替换
>>> a
[1, 2, 3, 0, 3, 4]
>>> list1
['a', 'b', 'c', 'd']
>>> list1.insert(1,'x')# 在特定位置插入元素
>>> list1
['a', 'x', 'b', 'c', 'd']
>>> a=[1,2]
>>> b=[3,4]
>>> a.extend(b) #连接两个列表,相当于a=a+b 注意:将两个list相加,需要创建新的list对象,从而需要消耗额外的内存,特别是当list较大时,尽量不要使用“+”来添加list,而应该尽可能使用List的append()方法
>>> a
[1, 2, 3, 4]
>>> a.pop() #删除列表最后元素,有返回值
4
>>> a
[1, 2, 3]
>>> del a[1] #删除指定下标元素
>>> a
[1, 3]
>>> a.remove(3) # 删除指定值元素
>>> a
[1]
>>> a=[1,2,3,1,1,1,1,1] # 但只会删除自左向右第一个
>>> a.remove(1)
>>> a
[2, 3, 1, 1, 1, 1, 1]
>>> a.remove(1)
>>> a
[2, 3, 1, 1, 1, 1]
# Slide(切片)总结
b = a[i:j] # 表示复制a[i]到a[j-1],以生成新的list对象。当i缺省时,默认为0,即 a[:3]相当于 a[0:3]。当j缺省时,默认为len(alist), 即a[1:]相当于a[1:len(alist)]
b = a[i:j:s] # i,j同上,s表示步长(也成步进),缺省为1。当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1。
b = a[::-1] # 得到倒序列表
>>> a
[2, 3, 1, 1, 1, 1]
>>> a.reverse() #另一种列表倒序的方法,注意:区别于切片,直接对列表对象操作会修改其值。
>>> a
[1, 1, 1, 1, 3, 2]
>>> reverse(a)
# range赋值方法
>>> list(range(1,5))
[1, 2, 3, 4]
循环结构
for
>>> for i in [1,2,3]:
... print(i)
1
2
3
>>> for i in range(2): # Executes the body with i = 0, then 1
... print(i)
0
1
while
while True:
STATEMENT
Break
The break statement is used to immediately leave the body of its loop.
for i in [12, 16, 17, 24, 29]:
if i % 2 == 1: # If the number is odd
break # ... immediately exit the loop
print(i)
print("done")
This prints:
12
16
done
Continue
This is a control flow statement that causes the program to immediately skip the processing of the rest of the body of the loop, for the current iteration. But the loop still carries on running for its remaining iterations:
for i in [12, 16, 17, 24, 29, 30]:
if i % 2 == 1: # If the number is odd
continue # Don't process it
print(i)
print("done")
This prints:
12
16
24
30
done
判断结构
if-else
if BOOLEAN EXPRESSION:
STATEMENTS_1 # Executed if condition evaluates to True
else:
STATEMENTS_2 # Executed if condition evaluates to False
if True:
pass # A placeholder.
else:
pass
多条件判断结构(Chained Conditionals)
if choice == "a":
function_one()
elif choice == "b":
function_two()
elif choice == "c":
function_three()
else:
print("Invalid choice.")
函数(广义的)
def fuction_1 (var1, var2)
""" Docstring """
return var
注意:parameter=形参(formal parameter), argument=实参(actual parameter)
在函数的任何地方,运行到return,直接返回。
时间
from datetime import datetime
now = datetime.now()
print '%s/%s/%s %s:%s:%s' % (now.month,now.day,now.year, now.hour, now.minute, now.second)
引用
https://docs.python.org/3/tutorial/
http://www.linuxde.net/2013/02/12497.html
https://segmentfault.com/q/1010000000330704