一:range 函数:
例:range(5)
1:作用:生成长度为5的一组数:0,1,2,3,4
2:python2中的range函数会返回一个列表:
>>> range(5)
[0, 1, 2, 3, 4]
python3中的range函数返回一个对象:
>>> range(5)
range(0,5)
3:语法规则:
range(stop): 0~stop-1
range(start, stop): start~stop-1
range(start, stop, step): start~stop-1, step为步长
二:for 循环:
1:语法:for 变量 in 循环范围:
循环需要执行的代码
或者:
for 变量 in 循环范围:
循环需要执行的代码
else:
循环执行结束执行的代码
例:求1~100之间所有偶数的和;
sum = 0
for i in range(2,101,2):
sum = sum + i
print(sum)
2550
2:循环中的跳出:
break: 跳出整个循环, 不会再循环里面的内容;
continue:跳出本次循环, continue后面的代码不再执行, 但是还会继续循环;
exit(): 结束程序的运行
这里对 break 与 continue 作比较说明:
break : for i in range(10):
if i == 5:
break
print(i) ###得到 i 依次为0,1,2,3,4,5 (到5结束,不再循环)
continue :for i in range(10):
if i == 5:
continue
print(i) ###得到 i 依次为0,1,2,3,4,6,7,8,9(没有5,因为跳 出了此次循环)
三:while 循环:
1:语法:while 条件语句:
满足条件执行的语句
else:
不满足条件执行的语句
例:求1+2+3+...+100
sum = 0
i = 1
while i <=100:
sum += i
i += 1
print(sum)
2:while 死循环:(应用于不定次数的执行一条或一段命令,不遇结束或者错误命令,则一直无限循环)
实现方法:
while True: 或者 while 2>1:(即永久成立的条件) 或者 while 1:
四:字符串:
1:三种定义:'hello python' 或者 "hello python" 或者 """hello python"""
2:转义符号:\n 换行;\“ 双引号;\t tab符;\‘单引号
3:字符串特性:s=hello ; c=python
索引:正向索引:s[1] : 'e'
反向索引:s[-1] :'o'
切片:
语法规则:s[i,j,k] # s[i,j] i:开始的位置;j:结束的位置
# 从 i 开始到 j 结束, 步长为 k ;
# 如果 i 省略, 则从头开始切片;
# 如果 j 省略, 一直切片到字符串最后;
s[1:]:'ello'
s[:1]:'h'
s[:-1]:'hell'
s[::-1]:'olleh' #反转
s[:]:#字符串拷贝
4:成员操作符:
'h' in s :Ture
'oo' in s:Flase
'oo' not in s:Ture
'h' not in s:Flase
5:字符串连接:
s + " " + c:'hello python'
6:字符串重复:
print("*"*10 + "学生管理系统" + "*"*10)
**********学生管理系统**********
7:字符串长度:
len(s) : 5
8:字符串的常用方法:
通过help()或者dir()命令,可以得到字符串的常用方法:
>>> s="hello world"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
例:s.istitle() : False 判断是否为标题
s.center(50,"*") :'*******************hello world********************'
s.rjust(50,"*") '***************************************hello world'
s.upper():'HELLO'
s.strip(l):'heo word'
s.find('h'): 0
s.replace('h','l') :'lello world'
s.count('l')
"*".join(s):'h*e*l*l*o* *w*o*r*l*d'
python第二天笔记整理
猜你喜欢
转载自blog.csdn.net/wx_xu0924/article/details/81587935
今日推荐
周排行