for循环and基本数据类型与基本使用

for循环

 

1、什么是for循环
循环就是重复做某件事,for循环是python提供第二种循环机制

2、为何要有for循环
理论上for循环能做的事情,while循环都可以做
之所以要有for循环,是因为for循环在循环取值(遍历取值)比while循环更简洁

3、如何用for循环

for循环语法如下:

 1 for 变量名 in 可迭代对象: # 此时只需知道可迭代对象可以是字符串列表字典,我们之后会专门讲解可迭代对象
 2     代码一
 3     代码二
 4     ...
 5     
 6 #例1
 7 for item in ['a','b','c']:
 8     print(item)
 9 # 运行结果
10 a
11 b
12 c
13 
14 # 参照例1来介绍for循环的运行步骤
15 # 步骤1:从列表['a','b','c']中读出第一个值赋值给item(item=‘a’),然后执行循环体代码
16 # 步骤2:从列表['a','b','c']中读出第二个值赋值给item(item=‘b’),然后执行循环体代码
17 # 步骤3: 重复以上过程直到列表中的值读尽

 

案例一:打印数字0-6

1 # 简单版:for循环的实现方式
2 for count in range(6):  # range(6)会产生从0-5这6个数
3     print(count)
4     
5 # 复杂版:while循环的实现方式
6 count = 0
7 while count < 6:
8     print(count)
9     count += 1

案例二:遍历字典

1 # 简单版:for循环的实现方式
2 for k in {'name':'jason','age':18,'gender':'male'}:  # for 循环默认取的是字典的key赋值给变量名k
3     print(k)
4     
5 # 复杂版:while循环确实可以遍历字典,后续将会迭代器部分详细介绍

案例三:for循环嵌套

1 #请用for循环嵌套的方式打印如下图形:
2 *****
3 *****
4 *****
5 
6 for i in range(3):
7     for j in range(5):
8         print("*",end='')
9     print()  # print()表示换行

 

案例四:列表循环取值

#简单版:
1
l = ['alex_dsb', 'lxx_dsb', 'egon_nb'] 2 for x in l: # x='lxx_dsb' 3 print(x)
1 #复杂版:(while)
2  ['alex_dsb', 'lxx_dsb', 'egon_nb']
3 i=0
4 while i < 3:
5     print(l[i])
6     i+=1
二:总结for循环与while循环的异同
1、相同之处:都是循环,for循环可以干的事,while循环也可以干
2、不同之处:
while循环称之为条件循环,循环次数取决于条件何时变为假
for循环称之为"取值循环",循环次数取决in后包含的值的个数

案例五:for循环控制循环次数:range()

1 for i in range(30):
2     print('===>')

注意:for+else和for+break与continue也可以用于for循环,使用语法同while循环

 

 1 username='egon'
 2 password='123'
 3 for i in range(3):
 4     inp_name = input('请输入您的账号:')
 5     inp_pwd = input('请输入您的密码:')
 6 
 7     if inp_name == username and inp_pwd == password:
 8         print('登录成功')
 9         break
10 else:
11     print('输错账号密码次数过多')

for+continue:

1 for i in range(6):  # 0 1 2 3 4 5
2     if i == 4:
3         continue
4     print(i)
for循环嵌套:外层循环循环一次,内层循环需要完整的循环完毕
1 for i in range(3):
2     print('外层循环-->', i)
3     for j in range(5):
4         print('内层-->', j)
补充:终止for循环只有break一种方案
 1 print('hello %s' % 'egon')
 2 #1、print之逗号的使用
 3 print('hello','world','egon')
 4 #2、换行符
 5 print('hello
')
 6 print('world')
 7 #3、print值end参数的使用
 8 print('hello
',end='')
 9 print('word')
10 print('hello',end='*')
11 print('world',end='*')

一.数字类型int型

一)定义:

 1 # 1、定义:
 2 # 1.1 整型int的定义
 3 age=10  # 本质age = int(10)
 4 
 5 # 1.2 浮点型float的定义
 6 salary=3000.3  # 本质salary=float(3000.3)
 7 
 8 # 注意:名字+括号的意思就是调用某个功能,比如
 9 # print(...)调用打印功能
10 # int(...)调用创建整型数据的功能
11 # float(...)调用创建浮点型数据的功能

二)类型转换

 1 # 1、数据类型转换
 2 # 1.1 int可以将由纯整数构成的字符串直接转换成整型,若包含其他任意非整数符号,则会报错
 3 >>> s = '123'
 4 >>> res = int(s)
 5 >>> res,type(res)
 6 (123, <class 'int'>)
 7 
 8 >>> int('12.3') # 错误演示:字符串内包含了非整数符号.
 9 Traceback (most recent call last):
10   File "<stdin>", line 1, in <module>
11 ValueError: invalid literal for int() with base 10: '12.3'
12         
13 # 1.2 float同样可以用来做数据类型的转换
14 >>> s = '12.3'
15 >>> res=float(s)
16 >>> res,type(res)
17 (12.3, <class 'float'>)

三)使用

数字类型主要就是用来做数学运算与比较运算,因为此数字类型除了与运算符结合使用之外,并无需要掌握的内置方法

 

二.字符串类型

一)定义:

1 # 定义:在单引号双引号三引号内包含一串字符
2 name1 = 'jason'  # 本质:name = str('任意形式内容')
3 name2 = "lili"  # 本质:name = str("任意形式内容")
4 name3 = """ricky"""  # 本质:name = str("""任意形式内容""")

二)类型转换

1 # 数据类型转换:str()可以将任意数据类型转换成字符串类型,例如 
2 >>> type(str([1,2,3])) # list->str
3 <class 'str'>
4 >>> type(str({"name":"jason","age":18})) # dict->str
5 <class 'str'>
6 >>> type(str((1,2,3)))  # tuple->str
7 <class 'str'>
8 >>> type(str({1,2,3,4})) # set->str
9 <class 'str'>

三)使用

1)优先掌握的操作

 1 >>> str1 = 'hello python!'
 2 
 3 
 4 # 1.按索引取值(正向取,反向取):
 5 # 1.1 正向取(从左往右)
 6 >>> str1[6]
 7 p
 8 # 1.2 反向取(负号表示从右往左)
 9 >>> str1[-4]
10 h
11 # 1.3 对于str来说,只能按照索引取值,不能改
12 >>> str1[0]='H' # 报错TypeError
13 
14 
15 # 2.切片(顾头不顾尾,步长)
16 # 2.1 顾头不顾尾:取出索引为0到8的所有字符
17 >>> str1[0:9]  
18 hello pyt
19 # 2.2 步长:0:9:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2、4、6、8的字符
20 >>> str1[0:9:2]  
21 hlopt 
22 # 2.3 反向切片
23 >>> str1[::-1]  # -1表示从右往左依次取值
24 !nohtyp olleh
25 
26 # 3.长度len
27 # 3.1 获取字符串的长度,即字符的个数,但凡存在于引号内的都算作字符)
28 >>> len(str1) # 空格也算字符
29 13
30 
31 # 4.成员运算 in 和 not in    
32 # 4.1 int:判断hello 是否在 str1里面
33 >>> 'hello' in str1  
34 True
35 # 4.2 not in:判断tony 是否不在 str1里面
36 >>> 'tony' not in str1 
37 True
38 
39 # 5.strip移除字符串首尾指定的字符(默认移除空格)
40 # 5.1 括号内不指定字符,默认移除首尾空格
41 >>> str1 = '  life is short!  '
42 >>> str1.strip()  
43 life is short!
44 
45 # 5.2 括号内指定字符,移除首尾指定的字符
46 >>> str2 = '**tony**'  
47 >>> str2.strip('*')  
48 tony
49 
50 # 6.切分split
51 # 6.1 括号内不指定字符,默认以空格作为切分符号
52 >>> str3='hello world'
53 >>> str3.split()
54 ['hello', 'world']
55 # 6.2 括号内指定分隔字符,则按照括号内指定的字符切割字符串
56 >>> str4 = '127.0.0.1'
57 >>> str4.split('.')  
58 ['127', '0', '0', '1']  # 注意:split切割得到的结果是列表数据类型
59 
60 
61 # 7.循环
62 >>> str5 = '今天你好吗?'
63 >>> for line in str5:  # 依次取出字符串中每一个字符
64 ...     print(line)
65 ...
66 67 68 69 70 71

2)需要掌握的操作

1.strip,lstrip,rstrip

1 >>> str1 = '**tony***'
2 
3 >>> str1.strip('*')  # 移除左右两边的指定字符
4 'tony'
5 >>> str1.lstrip('*')  # 只移除左边的指定字符
6 tony***
7 >>> str1.rstrip('*')  # 只移除右边的指定字符
8 **tony

2.lower(),upper()

1 >>> str2 = 'My nAme is tonY!'
2 
3 >>> str2.lower()  # 将英文字符串全部变小写
4 my name is tony!
5 >>> str2.upper()  # 将英文字符串全部变大写
6 MY NAME IS TONY!

 

3.starts with,ends with

 1 >>> str3 = 'tony jam'
 2 
 3 # startswith()判断字符串是否以括号内指定的字符开头,结果为布尔值True或False
 4 >>> str3.startswith('t') 
 5 True
 6 >>> str3.startswith('j')
 7 False
 8 # endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
 9 >>> str3.endswith('jam')
10 True
11 >>> str3.endswith('tony')  
12 False

 

4.格式化输出之format

1 # format括号内在传参数时完全可以打乱顺序,但仍然能指名道姓地为指定的参数传值,name=‘tony’就是传给{name}
2 >>> str4 = 'my name is {name}, my age is {age}!'.format(age=18,name='tony')
3 >>> str4  
4 'my name is tony, my age is 18!'
5 
6 >>> str4 = 'my name is {name}{name}{name}, my age is {name}!'.format(name='tony', age=18)
7 >>> str4  
8 'my name is tonytonytony, my age is tony!'

format的其他使用方式(了解)

1 # 类似于%s的用法,传入的值会按照位置与{}一一对应
2 >>> str4 = 'my name is {}, my age is {}!'.format('tony', 18)
3 >>> str4 
4 my name is tony, my age is 18!
 1 # 把format传入的多个值当作一个列表,然后用{索引}取值
 2 >>> str4 = 'my name is {0}, my age is {1}!'.format('tony', 18)
 3 >>> str4
 4 my name is tony, my age is 18!
 5 
 6 >>> str4 = 'my name is {1}, my age is {0}!'.format('tony', 18)
 7 >>> str4  
 8 my name is 18, my age is tony!
 9 
10 >>> str4 = 'my name is {1}, my age is {1}!'.format('tony', 18)
11 >>> str4  
12 my name is 18, my age is 18!

5.split,rsplit

1 # split会按照从左到右的顺序对字符串进行切分,可以指定切割次数
2 >>> str5='C:/a/b/c/d.txt'
3 >>> str5.split('/',1)
4 ['C:', 'a/b/c/d.txt']  
5 
6 # rsplit刚好与split相反,从右往左切割,可以指定切割次数
7 >>> str5='a|b|c'
8 >>> str5.rsplit('|',1)
9 ['a|b', 'c']

 

6.join

1 #
2 >>> '%'.join('hello') # 从字符串'hello'中取出多个字符串,然后按照%作为分隔符号进行拼接
3 'h%e%l%l%o'
4 >>> '|'.join(['tony','18','read'])  # 从列表中取出多个字符串,然后按照*作为分隔符号进行拼接
5 'tony|18|read'

 

7.replace(替换)

 1 # 用新的字符替换字符串中旧的字符
 2 >>> str7 = 'my name is tony, my age is 18!'  # 将tony的年龄由18岁改成73岁
 3 >>> str7 = str7.replace('18', '73')  # 语法:replace('旧内容', '新内容')
 4 >>> str7
 5 my name is tony, my age is 73!
 6 
 7 # 可以指定修改的个数
 8 >>> str7 = 'my name is tony, my age is 18!'
 9 >>> str7 = str7.replace('my', 'MY',1) # 只把一个my改为MY
10 >>> str7
11 'MY name is tony, my age is 18!'

 

8.isdigit

1 # 判断字符串是否是纯数字组成,返回结果为True或False
2 >>> str8 = '5201314'
3 >>> str8.isdigit()
4 True
5 
6 >>> str8 = '123g123'
7 >>> str8.isdigit()
8 False

3)了解操作

  1 # 1.find,rfind,index,rindex,count
  2 # 1.1 find:从指定范围内查找子字符串的起始索引,找得到则返回数字1,找不到则返回-1
  3 >>> msg='tony say hello'
  4 >>> msg.find('o',1,3)  # 在索引为1和2(顾头不顾尾)的字符中查找字符o的索引
  5 1  
  6 # 1.2 index:同find,但在找不到时会报错
  7 >>> msg.index('e',2,4) # 报错ValueError
  8 # 1.3 rfind与rindex:略
  9 # 1.4 count:统计字符串在大字符串中出现的次数
 10 >>> msg = "hello everyone"
 11 >>> msg.count('e')  # 统计字符串e出现的次数
 12 4
 13 >>> msg.count('e',1,6)  # 字符串e在索引1~5范围内出现的次数
 14 1
 15 
 16 # 2.center,ljust,rjust,zfill
 17 >>> name='tony'
 18 >>> name.center(30,'-')  # 总宽度为30,字符串居中显示,不够用-填充
 19 -------------tony-------------
 20 >>> name.ljust(30,'*')  # 总宽度为30,字符串左对齐显示,不够用*填充
 21 tony**************************
 22 >>> name.rjust(30,'*')  # 总宽度为30,字符串右对齐显示,不够用*填充
 23 **************************tony
 24 >>> name.zfill(50)  # 总宽度为50,字符串右对齐显示,不够用0填充
 25 0000000000000000000000000000000000000000000000tony
 26 
 27 # 3.expandtabs
 28 >>> name = 'tony	hello'  # 	表示制表符(tab键)
 29 >>> name
 30 tony    hello
 31 >>> name.expandtabs(1)  # 修改	制表符代表的空格数
 32 tony hello
 33 
 34 # 4.captalize,swapcase,title
 35 # 4.1 captalize:首字母大写
 36 >>> message = 'hello everyone nice to meet you!'
 37 >>> message.capitalize()
 38 Hello everyone nice to meet you!  
 39 # 4.2 swapcase:大小写翻转
 40 >>> message1 = 'Hi girl, I want make friends with you!'
 41 >>> message1.swapcase()  
 42 hI GIRL, i WANT MAKE FRIENDS WITH YOU!  
 43 #4.3 title:每个单词的首字母大写
 44 >>> msg = 'dear my friend i miss you very much'
 45 >>> msg.title()
 46 Dear My Friend I Miss You Very Much 
 47 
 48 # 5.is数字系列
 49 #在python3中
 50 num1 = b'4' #bytes
 51 num2 = u'4' #unicode,python3中无需加u就是unicode
 52 num3 = '' #中文数字
 53 num4 = '' #罗马数字
 54 
 55 #isdigt:bytes,unicode
 56 >>> num1.isdigit()
 57 True
 58 >>> num2.isdigit()
 59 True
 60 >>> num3.isdigit()
 61 False
 62 >>> num4.isdigit() 
 63 False
 64 
 65 #isdecimal:uncicode(bytes类型无isdecimal方法)
 66 >>> num2.isdecimal() 
 67 True
 68 >>> num3.isdecimal() 
 69 False
 70 >>> num4.isdecimal() 
 71 False
 72 
 73 #isnumberic:unicode,中文数字,罗马数字(bytes类型无isnumberic方法)
 74 >>> num2.isnumeric() 
 75 True
 76 >>> num3.isnumeric() 
 77 True
 78 >>> num4.isnumeric() 
 79 True
 80 
 81 # 三者不能判断浮点数
 82 >>> num5 = '4.3'
 83 >>> num5.isdigit()
 84 False
 85 >>> num5.isdecimal()
 86 False
 87 >>> num5.isnumeric()
 88 False
 89 
 90 '''
 91 总结:
 92     最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
 93     如果要判断中文数字或罗马数字,则需要用到isnumeric。
 94 '''
 95 
 96 # 6.is其他
 97 >>> name = 'tony123'
 98 >>> name.isalnum() #字符串中既可以包含数字也可以包含字母
 99 True
100 >>> name.isalpha() #字符串中只包含字母
101 False
102 >>> name.isidentifier()
103 True
104 >>> name.islower()  # 字符串是否是纯小写
105 True
106 >>> name.isupper()  # 字符串是否是纯大写
107 False
108 >>> name.isspace()  # 字符串是否全是空格
109 False
110 >>> name.istitle()  # 字符串中的单词首字母是否都是大写
111 False

 

三.列表

一)定义

1 # 定义:在[]内,用逗号分隔开多个任意数据类型的值
2 l1 = [1,'a',[1,2]]  # 本质:l1 = list([1,'a',[1,2]])

二)类型转换

1 # 但凡能被for循环遍历的数据类型都可以传给list()转换成列表类型,list()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到列表中
2 >>> list('wdad') # 结果:['w', 'd', 'a', 'd'] 
3 >>> list([1,2,3]) # 结果:[1, 2, 3]
4 >>> list({"name":"jason","age":18}) #结果:['name', 'age']
5 >>> list((1,2,3)) # 结果:[1, 2, 3] 
6 >>> list({1,2,3,4}) # 结果:[1, 2, 3, 4]

三)使用

1)优先掌握的操作

 1 # 1.按索引存取值(正向存取+反向存取):即可存也可以取 
 2 # 1.1 正向取(从左往右) 
 3 >>> my_friends=['tony','jason','tom',4,5]
 4  >>> my_friends[0] 
 5 tony 
 6 # 1.2 反向取(负号表示从右往左) 
 7 >>> my_friends[-1] 
 8 5 
 9 # 1.3 对于list来说,既可以按照索引取值,又可以按照索引修改指定位置的值,但如果索引不存在则报错 
10 >>> my_friends = ['tony','jack','jason',4,5] 
11 >>> my_friends[1] = 'martthow' 
12 >>> my_friends ['tony', 'martthow', 'jason', 4, 5]
13 
14  # 2.切片(顾头不顾尾,步长) 
15 # 2.1 顾头不顾尾:取出索引为0到3的元素 
16 >>> my_friends[0:4] ['tony', 'jason', 'tom', 4]
17  # 2.2 步长:0:4:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2的元素 
18 >>> my_friends[0:4:2] ['tony', 'tom'] 
19 # 3.长度
20  >>> len(my_friends)
21  5 
22 # 4.成员运算in和not in
23  >>> 'tony' in my_friends 
24 True 
25 >>> 'xxx' not in my_friends 
26 True 
27 # 5.添加 
28 # 5.1 append()列表尾部追加元素 
29 >>> l1 = ['a','b','c'] 
30 >>> l1.append('d') 
31 >>> l1 ['a', 'b', 'c', 'd'] 
32 # 5.2 extend()一次性在列表尾部添加多个元素 
33 >>> l1.extend(['a','b','c']) 
34 >>> l1 ['a', 'b', 'c', 'd', 'a', 'b', 'c'] 
35 # 5.3 insert()在指定位置插入元素 
36 >>> l1.insert(0,"first") 
37 # 0表示按索引位置插值 
38 >>> l1 ['first', 'a', 'b', 'c', 'd', 'a', 'b', 'c'] 
39 # 6.删除 
40 # 6.1 del 
41 >>> l = [11,22,33,44] 
42 >>> del l[2] 
43 # 删除索引为2的元素 
44 >>> l [11,22,44] 
45 # 6.2 pop()默认删除列表最后一个元素,并将删除的值返回,括号内可以通过加索引值来指定删除元素 
46 >>> l = [11,22,33,22,44] 
47 >>> res=l.pop() >>> res 44 
48 >>> res=l.pop(1) 
49 >>> res 22 
50 # 6.3 remove()括号内指名道姓表示要删除哪个元素,没有返回值 
51 >>> l = [11,22,33,22,44] 
52 >>> res=l.remove(22) 
53 # 从左往右查找第一个括号内需要删除的元素 
54 >>> print(res) None 
55 # 7.reverse()颠倒列表内元素顺序 
56 >>> l = [11,22,33,44] 
57 >>> l.reverse() 
58 >>> l [44,33,22,11] 
59 # 8.sort()给列表内所有元素排序
60  # 8.1 排序时列表元素之间必须是相同数据类型,不可混搭,否则报错 
61 >>> l = [11,22,3,42,7,55] >>> l.sort() 
62 >>> l [3, 7, 11, 22, 42, 55] 
63 # 默认从小到大排序 
64 >>> l = [11,22,3,42,7,55] 
65 >>> l.sort(reverse=True) 
66 # reverse用来指定是否跌倒排序,默认为False 
67 >>> l [55, 42, 22, 11, 7, 3] 
68 # 8.2 了解知识:
69  # 我们常用的数字类型直接比较大小,但其实,字符串、列表等都可以比较大小,原理相同:都是依次比较对应位置的元素的大小,如果分出大小,则无需比较下一个元素,比如
70  >>> l1=[1,2,3]
71  >>> l2=[2,] 
72 >>> l2 > l1 True 
73 # 字符之间的大小取决于它们在ASCII表中的先后顺序,越往后越大 
74 >>> s1='abc' 
75 >>> s2='az' 
76 >>> s2 > s1
77  # s1与s2的第一个字符没有分出胜负,但第二个字符'z'>'b',所以s2>s1成立 True # 所以我们也可以对下面这个列表排序
78  >>> l = ['A','z','adjk','hello','hea'] 
79 >>> l.sort() 
80 >>> l ['A', 'adjk', 'hea', 'hello','z'] 
81 # 9.循环 # 循环遍历my_friends列表里面的值
82  for line in my_friends:
83  print(line)
84  'tony' 'jack' 'jason' 4 5

 

2)了解操作

1 >>> l=[1,2,3,4,5,6]
2 >>> l[0:3:1] 
3 [1, 2, 3]  # 正向步长
4 >>> l[2::-1] 
5 [3, 2, 1]  # 反向步长
6 
7 # 通过索引取值实现列表翻转
8 >>> l[::-1]
9 [6, 5, 4, 3, 2, 1]

五.元组

一)作用

元组与列表类似,也是可以存多个任意类型的元素,不同之处在于元祖的元素不能修改,即元组相当于不可变的列表,用于记录多个固定不允许修改的值,单纯用于取

二)定义

1 # 在()内用逗号分隔开多个任意类型的值
2 >>> countries = ("中国""美国""英国")  
3 # 本质:countries = tuple("中国","美国","英国")
4 # 强调:如果元组内只有一个值,则必须加一个逗号,否则()就只是包含的意思而非定义元组
5 >>> countries = ("中国",)  # 本质:countries = tuple("中国")

三)转换类型

1 # 但凡能被for循环的遍历的数据类型都可以传给tuple()转换成元组类型
2 >>> tuple('wdad') # 结果:('w', 'd', 'a', 'd') 
3 >>> tuple([1,2,3]) # 结果:(1, 2, 3)
4 >>> tuple({"name":"jason","age":18}) # 结果:('name', 'age')
5 >>> tuple((1,2,3)) # 结果:(1, 2, 3)
6 >>> tuple({1,2,3,4}) # 结果:(1, 2, 3, 4)
7 # tuple()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到元组中

四)使用

 1 >>> tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33) 
 2 # 1、按索引取值(正向取+反向取):只能取,不能改否则报错!  
 3 >>> tuple1[0]
 4 1
 5 >>> tuple1[-2]
 6 22
 7 >>> tuple1[0] = 'hehe'  # 报错:TypeError:
 8 
 9 # 2、切片(顾头不顾尾,步长)
10 >>> tuple1[0:6:2] 
11 (1, 15000.0, 22)
12 
13 # 3、长度
14 >>> len(tuple1)  
15 6
16 
17 # 4、成员运算 in 和 not in
18 >>> 'hhaha' in tuple1 
19 True
20 >>> 'hhaha' not in tuple1  
21 False 
22 
23 # 5、循环
24 >>> for line in tuple1:
25 ...     print(line)
26 1
27 hhaha
28 15000.0
29 11
30 22
31 33

六.字典

一)定义

二)类型转换

三)使用

七.集合

一)作用:集合 list tuple dict一样都可以存放多个值,但实际和主要用于:去重 关系运算

二)定义:

三)类型转换

四)使用

1)关系运算

原文地址:https://www.cnblogs.com/2722127842qq-123/p/12454036.html