python循环之for循环与基本的数据类型以及内置方法

一、循环之for循环

1.1  for循环的语法与基本使用

什么是for循环?为何要有for循环?如何使用for循环?

循环就是重复做某件事,for循环是python提供的第二种循环;一般for循环能做的,while循环都能做,之所以有for循环是因为在循环取值中比while更简洁。(for取值也叫遍历取值)

语法:

for 变量名 in 可迭代对象:    #可迭代对象可以是列表、字典、字符串、元组、集合

    代码1

    代码2

    。。。

小结:for循环与while循环的相同与不同之处

相同之处:都是循环。for循环能做的,while循环也能做

不同之处:while循环称之为条件循环,循环次数取决于条件何时变为假

                 for循环称之为迭代循环,循环次数取决于in后包含值的个数

for循环控制循环次数:  range()  #range(5)会产生0-4这5个数

1.2for循环的应用  

例:

username='egon'
password='123'
for i in range(3):
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')
    if inp_name==uesename and inp_pwd==password:
        print('登录成功')
        break
else:
    print('输错账号密码次数过多')
#for+break:同while循环一样
#for+else:同while循环一样
#for+continue:同while循环一样

1.3for循环嵌套

例:

for i in range(3):
    print('外层循环‘,i)
    for j in range(5):
        print('内层循环',j)
#for循环嵌套:外层循环一次,内层循环要完整的循环一遍
#终止for循环只能是break

二、数据类型

int:

作用:记录年龄、号码、身份证等

定义:age=10  # age=int(10)

类型转换:age=int(‘99’)  # 纯数字的字符串能转换成int

float:

作用:记录小数相关的,身高、体重等

定义: salary=3.1  # salary=float(3.1)

类型转换:res=float('3.1')    #带小数的字符串能转换成float 

小结:他们的使用方式就是数学运算以及比较运算

str

作用:记录描述性质的状态

定义:mag=‘hello’  # mag=str(‘msg’)

类型转换:res=str({‘a’:1})    #可以将任意类型转换成字符串

使用:内置方式

按索引取值:msg=‘hello world’正向取值--print(mag【0】);反向取值--print(msg【-1】)

切片:索引的取值拓展,从一个大字符串拷贝出一个子字符串

msg=‘hello world’  #顾头不顾尾

msg【0:5】 #打印出hello

步长:

msg=‘hello world’  

msg【0:5:2】 #打印出hlo

反向步长:

msg=‘hello world’  

msg【5:0:-1】 #打印出‘ 0lle’

res=msg【::-1】  #把字符串倒过来

长度:msg=‘hello world’  

print(len(msg))  #统计他的长度

成员运算:判断一个子字符串是否在一个大字符串中

移除空白的字符串:msg=‘  egon  ’

res=msg.strip() #去掉左右空格,只去2边,不去中间。不会改变原值,他是产生新值,字符串不可变类型

切分:把一个字符串按错每个按错某种分隔符进行切分,得到一个列表

分隔符:

info=‘egon:18:male’

res=info.split(‘:’) 默认分隔符为空格

res=info.split(‘:’,1) 只切分一次,剩下的不切

循环字符串

info=‘egon:18:male’

for x in info:

print(x)

msg=***egon***

strip:print(msg.strip(‘*’))  #去左右2边

lstrip:print(msg.lstrip(‘*’))  #去左边

rstrip:print(msg.rstrip(‘*’))  #去右边

msg=‘AbbCCC’

lower:(msg.lower())  #全变小写

upper:(msg.upper())  #全变大写

startswith:print('alex is sb'.startswith('alex'))  #判断是否以alex开头

endswith:print('alex is sb'.endswith('sb'))  #判断是否以sb结尾

join:把列表拼接成字符串,按照某个分隔符号,吧元素元素全为字符串的列表拼接成一个大字符串

l=['egon','18','male']

res=‘:’.join(l)   #打印出 egon:18:male

replace:替换

mag=‘you can you up no can no bb ’

print(msg.replace('you','YOU',1))    #把you替换成YOU,1不写默认全部替换

isdiqit:判断字符串是否由纯数字组成

print(‘123’.isdiqit())

猜你喜欢

转载自www.cnblogs.com/zhangjiahao996/p/12459696.html
今日推荐