while+continue
1. 使用循环打印出0-9的数字
2. 打印0-10的数字不打印6
count=0
while count < 11:
if count ==3:
count+=1
continue #
print(count)
count+=1
ps:continue结束本次循环,并且回到while循环的条件处从新判断
2. while+else(了解)
count=0
while count < 10:
if count ==5:
count+=1
continue
print(count)
count+=1
else:
print('哈哈哈哈')
ps:当while循环没有被中断(break)的时候,就会执行
3. for循环
语法格式:
for 变量 in 可迭代对象: 字符串、列表、字典、元组
print(name)
for i in 'helloworld':
print(i)
PS:for后面的变量名命名的时候,如果没有特殊的含义,我们一般使用i,j,k,v,item等等
for i in 'helloworld':
print(i)
PS:for后面的变量名命名的时候,如果没有特殊的含义,我们一般使用i,j,k,v,item等等
range关键字

4数据类型内置方法
1. 整型
进制转换
print(bin(10)) # 0b1010
print(oct(10)) # 0o12
print(hex(10)) # 0xa
0b代表二进制 0o代表八进制 0x代表十六进制
2.浮点型
float同样可以用来做数据类型的转换
3. 字符串的内置方法(重点)
1. 把其他数据类型转为字符串
print(str(19))
print(str(19.1))
print(str([1, 2, 3, 4]))
print(str({'username':'kecin', 'age':18}))
print(str((1,2,3,4)))
print(str(True))
print(str({11,22,33}))
2.切片(顾头不顾尾,步长)
2.1 顾头不顾尾:取出索引为0到8的所有字符
>>> str1[0:9]
hello pyt
2.2 步长:0:9:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2、4、6、8的字符
>>> str1[0:9:2]
hlopt
2.3 反向切片
>>> str1[::-1] # -1表示从右往左依次取值
!nohtyp olleh
3.长度len
3.1 获取字符串的长度,即字符的个数,但凡存在于引号内的都算作字符)
>>> len(str1) # 空格也算字符
13
4.成员运算 in 和 not in
4.1 int:判断hello 是否在 str1里面
>>>'hello'instr1
True
4.2 not in:判断tony 是否不在 str1里面
>>>'tony'notinstr1
True
5.strip移除字符串首尾指定的字符(默认移除空格)
5.1 括号内不指定字符,默认移除首尾空白字符(空格、\n、\t)
>>> str1 = ' life is short! '
>>> str1.strip()
life is short!
5.2 括号内指定字符,移除首尾指定的字符
>>> str2 = '**tony**'
>>> str2.strip('*')
tony
6.切分split
6.1 括号内不指定字符,默认以空格作为切分符号
>>> str3='hello world'
>>> str3.split()
['hello', 'world']
6.2 括号内指定分隔字符,则按照括号内指定的字符切割字符串
>>> str4 = '127.0.0.1'
>>> str4.split('.')
['127', '0', '0', '1'] # 注意:split切割得到的结果是列表数据类型
7.循环
>>> str5 = '今天你好吗?'
>>> for line in str5: # 依次取出字符串中每一个字符
... print(line)
本文介绍了Python中的循环结构,包括while+continue的用法,展示了如何跳过特定循环次数。同时讲解了while+else的应用,以及for循环的基本语法。此外,还详细探讨了字符串的内置方法,如切片、长度计算、成员运算以及字符串的处理函数如strip和split。

2124

被折叠的 条评论
为什么被折叠?



