python开发新手扫盲
数字和运算
// :计算除法对结果取整(向下取整)
>>> -33//2
-17
>>> 5//3
1
%:取模运算符(对除法求余数)
**:求幂运算符(求次方)
>>> 8%4
0
>>> 6**2
36
=:赋值(不是数学意义上的等于)
逻辑运算符:and(与)、or(或)、not(非)布尔bool类型的运算
>>> not True
False
>>> True and false
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
True and false
NameError: name 'false' is not defined
>>> True and False
False
>>> True or False
True
字符串
字符串" "引起来,若字符串本身有引号,则用\‘(标记字符串内部的引号)
'I\'m feeling very happy'
"I'm feeling very happy"
PS:单引号’'和双引号""几乎相同,一般表示较短的字符串
字符串中有单引号,若引用单引号,则字符串中的单引号’表示;
若引用双引号,则字符串中的单引号就用’表示即可
>>> 'I\'m'
"I'm"
>>> "I'm"
"I'm"
‘’’ ‘’’:三引号连用可跨行输入;
>>> print('''READ ME
line1
line2
line3
''')
READ ME
line1
line2
line3
len():计算字符串长度
字符串[]:显示字符串在第n个字母
greeting = "hello"
>>> greeting[0]
'h'
>>> len(greeting)
5
>>> greeting[3]
'l'
>>> greeting[-1]
'o'
>>> greeting[-5]
'h'
字符串[ : ] :截取字符串,前闭后开【)。
>>> greeting[1:4]
'ell'
>>> greeting[:4]
'hell'
>>> greeting[:]
'hello'
+号:连接字符串
*号:字符串 * (int类型),N个字符串组合
in: 字符串a in 字符串b,a字符串是否是b字符串的子串
not in:字符串a not in 字符串b,a字符串是否不是b字符串的子串
(详情查阅python文档)
>>> "zhang"+"ming"
'zhangming'
>>> "zhang"*7
'zhangzhangzhangzhangzhangzhangzhang'
>>> "zhan"in"zhang"
True
>>> "zhan" in "zhao"
False
>>> "z"not in "zhang"
False
>>> "za" not in "zhang"
True
startswith()方法: 判断字符串开头
endswith()方法: 判断字符串结尾
>>> "hello".startswith("h")
True
>>> "hello".startswith("H")
False
>>> "hello".endswith("o")
True
>>> "hello".endswith("e")
False
count(): 字符串计算
>>> "hello".count("l")
2
hello中l出现了2次
join(列表): 字符串插入
>>> ";".join(["a","b","c"])
'a;b;c'
format(): 格式化字符串,()中的值替换{};
>>> "{} {}".format("Hello","world")
'Hello world'
条件语句
python规定使用缩进来表示代码逻辑层次(建议4个空格表示缩进)
if else 后面必带冒号
也请记得缩进一致
x=42
>>> if x<5:
... print("x<5")
... else:
... if x<10:
... print("x>=5 and x<10")
... else:
... if x<50:
... print("x>=10 and x<50")
... else:
... print("x>=50")
...
x>=10 and x<50
elif语句:表示else ……if……
>>> x=42
>>> if x<5:
... print("x<5")
... elif x<10:
... print("x>=5 and x<10")
... elif x<50:
... print("x>=10 and x<50")
... else:
... print("x>=50")
...
x>=10 and x<50
>>>
循环语句
1.while 循环语句
x=1
>>> total=0
>>> while x<=100:
... x=x+1
... total=total+x
...
>>> print(x)
101
关键字:else
x=1
>>> total=0
>>> while x<=100:
... x=x+1
... total=total+x
... else:
... print(x)
...
101
关键字:break,跳出当前循环
关键字:continue,终止当前循环,直接进入下次循环
2.for语句
for x in 循环:方便用于数组、字典等可遍历的对象
示例1:循环遍历找到最大值
for x in counts:
#将counts列表中的值赋给x
largest = 0
>>> counts = [1,2,3,4,5,6,7,8]
>>> for x in counts:
... if x >largest:
... largest = x
...
>>> print(largest)
8
示例2:1-101相加
>>> total =0
>>> for x in range(1,101):
... total = total + x
...
>>> print(total)
5050
python中的range()函数:
python range() 函数可创建一个整数列表,一般用在 for 循环中。
函数语法 range(start, stop[, step]) 参数说明:
start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5); stop: 计数到 stop结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
函数初探
def:函数定义关键词
函数的作用域:全局变量、局部变量
>>> d=10
>>> def add3(a,b,c):
... return(a+b+c+d)
...
>>> add3(1,2,3)
16
>>> d=10