Python循环语句-for/while

一、for循环

1、功能:

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

2、for循环语法:
for iterating_var in sequence:
   statements(s)
View Code

实例:

# l=['a','b','c']
# for i in range(3):
#     print(i,l[i])
View Code

 3、for循环与else连用:

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print ('%d 等于 %d * %d' % (num,i,j))
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print num           #'是一个质数'
  
#结果:
#10 等于 2 * 5
#11 是一个质数
#12 等于 2 * 6
#13 是一个质数
#14 等于 2 * 7
#15 等于 3 * 5
#16 等于 2 * 8
#17 是一个质数
#18 等于 2 * 9
#19 是一个质数
View Code
4、循环控制语句:
控制语句描述
break 语句 在语句块执行过程中终止循环,并且跳出整个循环
continue 语句 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。
pass 语句 pass是空语句,是为了保持程序结构的完整性。
 
 
 
 
 
5、for循环循环嵌套:
# for i in range(3): #i=2
#     for j in range(2): #j=1
#         print(i,j) #2,1
View Code
6、总结while循环与for循环:
#1.
#while循环:称之为条件循环,循环的次数取决于条件何时为False;
#for循环:称之为...循环,循环的次数取决于数据的包含的元素的个数。
#2.
#for循环专门用来取值,在循环取值方面比while循环要强大,以后但凡遇到循环取值的场景,就应该用for循环。
View Code

 

二、数字类型

1、整型:
# ======================================基本使用======================================
# 1、用途:记录年龄、等级、号码等
# 2、定义方式
#age=10 # age=int(10) int相当于一个制造整形的工厂
# 类型转换
# print(int(3.1))     #int对浮点型会进行取整输出
# res=int('1111111')  #int加工的字符串必须满足只含有阿拉伯数字的字符,不能含有以外字符
# print(res,type(res))
# res=float('111111.1')
# print(res,type(res))
# 了解(**)
# 十进制转成。。。进制
# print(bin(13))    #十进制转换为二进制
# print(oct(13))    #十进制转换为八进制
# print(hex(13))    #十进制转换为十六进制
# 3、常用操作+内置的方法
# ======================================该类型总结====================================
# 只能存一个值
# 不可变类型(值改变,id也变)
# x=10
# print(id(x))  
# x=11
# print(id(x))
View Code
2、浮点型:
# 1. 浮点型float
# ======================================基本使用======================================
# 1、用途:记录身高、体重、薪资等
# 2、定义方式
# salary=10.1 # salary=float(10.1)
# 类型转换
# print(float(10))
# print(float(1.1))
# print(float('1.1'))
# 3、常用操作+内置的方法
# ======================================该类型总结====================================
# 只能存一个值
# 不可变类型(值改变,id也变)
# x=10.3
# print(id(x))
# x=11.2
# print(id(x))
View Code
3、字符串类型:
#字符串类型str
# ======================================基本使用======================================
# 1、用途:记录描述性值的状态,比如名字、性别等
# 2、定义方式
#msg='hello world' #msg=str('hello world')
# 类型转换: 可以把任意类型专场字符串类型
# res1=str(10)
# res2=str(10.3)
# res3=str([1,2,3])
# res4=str({'x':1}) #res4="{'x':1}"
#
# print(type(res1))
# print(type(res2))
# print(type(res3))
# print(type(res4))
# ======================================该类型总结====================================
# 存一个值
# 有序   #这里的有序指的是字符串中的单个字符有序
# 不可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)
# x='aaa'
# print(id(x))
# x='bbb'
# print(id(x))
View Code

常用的操作加内置方法:

#优先掌握的操作:(*****)
1、按索引取值(正向取+反向取) :只能取
# msg='hello world'
# print(type(msg[0]))   #取出的字符还是为str类型
# print(msg[-1])
# msg[0]='H'    #此处要执行修改操作的化会发生报错
2、切片(顾头不顾尾,步长)
# msg='hello world'
# print(msg[0]+msg[1]+msg[2])
# print(msg[0:5])
# print(msg[0:5:2]) #其中0为起始位置 5为结束位置(顾头不顾尾)取不到索引为5的字符 2为步长
# print(msg[0:]) #不写默认到最后一个字符  
# print(msg[:]) #不写起始和结束位置元素默认从第一个切片到最后一个字符 
# print(msg[-1:-5:-1]) #-1 -2 -3 -4
# print(msg[::-1]) #-1 -2 -3 -4
3、长度len:统计的是字符串中字符的个数
# msg='h你d'
# print(len(msg))
4、成员运算in和not in:判断一个子字符串是否存在与一个大字符串中
# msg='hello world'
# print('ho' in msg)
# print('ho' not in msg)
5、移除空白strip:移除字符串左右两边的某些字符。strip后面跟一个参数(即要移除的字符,可以为多个)
# msg='      hello      '
# print(msg.strip(' '))
# print(msg.strip())    不写参数,默认参数为空格
# print(msg)
# name=input('name>>>: ').strip() #name='egon'
# pwd=input('password>>>: ').strip()
#
# if name == 'egon' and pwd == '123':
#     print('login successfull')
# else:
#     print('username or password error')
# msg='***h**ello**********'
# print(msg.strip('*'))
# msg='*-=+h/ello*(_+__'
# print(msg.strip('*-=+/(_'))
​
​
6、切分split: 把有规律的字符串切成列表从而方便取值,split(分隔符,切几次 不写默认切完)
# info='egon:18:180:150'
# res=info.split(':',1) 
# print(res)
# print(res[1])
# info='egon:18:180:150'
# res=info.split(':')
# print(res)
# s1=res[0]+':'+res[1]+':'+res[2]+':'+res[3]
# s1=''
# for item in res:
#     s1+=item
# print(s1)
# s1=':'.join(res)   专门用于字符串的拼接 参数为一个需要拼接的内容
# print(s1)
# ':'.join([1,2,3,4,5])
7、循环
# for i in 'hello':  
#     print(i)
​
​
需要掌握的操作(****1、strip,lstrip,rstrip  #同strip 一个去除左边元素,一个去除右边元素
# msg='*****hello****'
# print(msg.strip('*'))
# print(msg.lstrip('*'))
# print(msg.rstrip('*'))
2、lower,upper    #将英文字符(忽略其他字符)全部变为大写或小写
# msg='AaBbCc123123123'
# print(msg.lower())
# print(msg.upper())
3、startswith,endswith #判断开头结尾是不是特定字母(参数)  返回布尔值
# msg='alex is dsb'
# print(msg.startswith('alex'))
# print(msg.endswith('sb'))
4、format的三种玩法  
# msg='my name is %s my age is %s' %('egon',18)
# print(msg)
# msg='my name is {name} my age is {age}'.format(age=18,name='egon')
# print(msg)
# 了解
# msg='my name is {} my age is {}'.format(18,'egon')
# msg='my name is {0}{0} my age is {1}{1}{1}'.format(18,'egon')
# print(msg)
​
​
5、split,rsplit   
# cmd='get|a.txt|33333'
# print(cmd.split('|',1))
# print(cmd.rsplit('|',1))
​
​
6、replace  #替换掉字符串中的指定内容  替换完生成新字符串  并未改变以前的字符串
# msg='kevin is sb kevin kevin'
# print(msg.replace('kevin','sb',2))
7、isdigit #当字符串内为纯数字时结果为True,
# res='11111'
# print(res.isdigit())
# int(res)
# age_of_bk=18
# inp_age=input('your age: ').strip()
# if inp_age.isdigit():
#     inp_age=int(inp_age) #int('asdfasdfadfasdf')
#     if inp_age > 18:
#         print('too big')
#     elif inp_age < 18:
#         print('too small')
#     else:
#         print('you got it')
# else:
#     print('必须输入纯数字')
​
了解(**1、find,rfind,index,rindex,count
# print('xxxkevin is sb kevin'.find('kevin'))
# print('xxxkevin is sb kevin'.index('kevin'))
# print('xxxkevin is sb kevin'.rfind('kevin'))
# print('xxxkevin is sb kevin'.rindex('kevin'))
# res='xxxkevin is sb kevin'.find('kevasdfsadfin')
# print(res)
# res='xxxkevin is sb kevin'.index('kevasdfsadfin')
# print('kevin is kevin is kevin is sb'.count('kevin'))
2、center,ljust,rjust,zfill
# print('egon'.center(50,'*'))  居中
# print('egon'.ljust(50,'*'))
# print('egon'.rjust(50,'*')) 
# print('egon'.zfill(50))  用0填充
3、captalize,swapcase,title
# print('my name is kevin'.capitalize())  首字母大写
# print('AaBbCc'.swapcase())   字符串中英文字符(大写变为小写,小写变为大写)
# print('my name is kevin'.title())  每个单词的首字母大写
4、is其他
# name='egon123'
# print(name.isalnum()) #字符串由字母或数字组成
# print(name.isalpha()) #字符串只由字母组成
# print(name.islower())
# print(name.isupper())
# name='    '
# print(name.isspace())
#msg='I Am Egon'
#print(msg.istitle())
View Code

 

原文地址:https://www.cnblogs.com/peng-zhao/p/9995765.html