老齐python-基础6(循环 if while for)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了老齐python-基础6(循环 if while for)相关的知识,希望对你有一定的参考价值。
1、条件语句if
依据某个条件,满足这个条件后执行下面的内容
>>> if bool(conj): #语法 do something >>> a = 8 >>> if a == 8: print(a) 8
1.1 if...elif...else
基本结构:
if 条件 1: 语句块1 elif 条件2: 语句块2 elif 条件3: 语句块3 ... else 语句块4
if使用示例程序
#!/usr/bin/env python #调用系统环境的python #coding:utf-8 #支持中文 python3可省略 print("清输入任意一个整数数字:") number = int(input()) #用户交互输入函数 if number == 10: print("您输入的数字是:{}".format(number)) print("You are SMART") elif number > 10: print("您输入的数字是:{}".format(number)) print("This number is more than 10.") else: print("您输入的数字是:{}".format(number)) print("This number is less than 10.")
1.2三元操作符
三元操作,是条件语句中比较简练的一种赋值方式:
>>> name = "qiwsir" if 29 > 21 else "github" >>> name ‘qiwsir‘
如果抽象成为一个公式,三元操作符就是这样的: A = Y if X else Z
如果X为真,那么就执行 A = Y
如果X为假,就执行A = Z
>>> x = 2 >>> y = 8 >>> a = "python" if x > y else "qiwsir" >>> a ‘qiwsir‘ >>> b = "python" if x < y else "tajzhang" >>> b ‘python‘
2、for循环
for 循环规则: 操作语句
2.1实例:
>>> hello = "world" #赋值语句 >>> for i in hello: #必须是可迭代的类型 print(i) w o r l d
>>> for i in range(len(hello)): #得到hello引用字符串长度 为5 print(hello[i]) #对应每个索引输出值,直到最后一个 i=4为止 w o r l d
2.2多种序列类型for循环:
1)循环列表:
>>> names = ["Newton","Einstein","Hertz","Maxwell","Bohr","Cavendish","Feynman"] >>> for name in names: print(name,end="-*-") #end方法help(print) Newton-*-Einstein-*-Hertz-*-Maxwell-*-Bohr-*-Cavendish-*-Feynman-*- >>> for i in range(len(names)): print(names[i]) Newton Einstein Hertz Maxwell Bohr Cavendish Feynman >>>
2)循环字典:
>>> d = dict([("website","www.itdiffer.com"),("lang","python"),("author","laoqi")]) >>> d {‘website‘: ‘www.itdiffer.com‘, ‘lang‘: ‘python‘, ‘author‘: ‘laoqi‘} >>> for k in d: #获取key print(k) website lang author >>> d.keys() dict_keys([‘website‘, ‘lang‘, ‘author‘]) >>> for k in d.keys(): #相同方法 print(k) website lang author >>> for k,v in d.items(): #获取键值 print (k + "-->" + v) website-->www.itdiffer.com lang-->python author-->laoqi
2.3判断对象是否是可迭代的
>>> import collections >>> isinstance(321,collections.Iterable) False >>> isinstance([1,2,3],collections.Iterable) True >>> isinstance({"name":"canglaoshi","work":"php"},collections.Iterable) True
2.4 range(start,stop[,step])
start:开始数值,默认为0,也就是如果不写这项,则认为start=0
stop:结束的数值,这是必须要写的
step:变化的步长,默认是1,坚决不能为0
>>> range(0,9,2) range(0, 9, 2) >>> type(range(0,9,2)) #是一个Range类型的对象 <class ‘range‘>
>>> list(range(0,9,2))
[0, 2, 4, 6, 8
如果是从0开始,步长为1,可以写成range(9)
start=0,step=2,stop=9,值从0开始 结束是start + (n-1)step
>>> range(0,-9,-1) range(0, -9, -1) >>> list(range(0,-9,-1)) [0, -1, -2, -3, -4, -5, -6, -7, -8]
2.5并行迭代
可迭代(iterable):在python中的表现就是用for循环,从对象中获得一定数量的元素.
求两个可迭代对象每个元素的和zip():
>>> c = [1,2,3] >>> d = [9,8,7,6] >>> zip(c,d) <zip object at 0x105912b88> >>> list(zip(c,d)) [(1, 9), (2, 8), (3, 7)] >>> list(zip(d,c)) [(9, 1), (8, 2), (7, 3)] >>> m = {"name","lang"} >>> n = {"tajzhang","python"} >>> list(zip(m,n)) [(‘name‘, ‘tajzhang‘), (‘lang‘, ‘python‘)] >>> s = {"name":"tajzhang"} >>> t = {"lang":"python"} >>> list(zip(s,t)) [(‘name‘, ‘lang‘)] >>> a = ‘tajzhang‘ >>> c = [1,2,3] >>> list(zip(c)) [(1,), (2,), (3,)] >>> list(zip(a)) [(‘t‘,), (‘a‘,), (‘j‘,), (‘z‘,), (‘h‘,), (‘a‘,), (‘n‘,), (‘g‘,)]
>>> a = [1,2,3,4,5] >>> b = [9,8,7,6,5] >>> d = [] >>> for x,y in zip(a,b): #使用zip使列表相加 d.append(x+y) >>> d [10, 10, 10, 10, 10]
zip扩展用法
>>> for x,y in zip(a,b): d.append(str(x) + ":" +y) >>> d [‘1:python‘, ‘2:www.itdiffer.com‘, ‘3:tajzhang‘] >>> result = [(2,11),(4,13),(6,15),(8,17)] >>> list(zip(*result)) [(2, 4, 6, 8), (11, 13, 15, 17)]
使用zip解决字典key value调换
方法1:使用for循环
>>> myinfor = {"name":"tajzhang","stie":"www.bokey.io","lang":"python"} >>> infor = {} >>> for k,v in myinfor.items(): infor[v] =k >>> infor {‘tajzhang‘: ‘name‘, ‘www.bokey.io‘: ‘stie‘, ‘python‘: ‘lang‘}
方法2:使用zip()
>>> dict(zip(myinfor.values(),myinfor.keys())) {‘tajzhang‘: ‘name‘, ‘www.bokey.io‘: ‘stie‘, ‘python‘: ‘lang‘}
解析
>>> myinfor.values() dict_values([‘tajzhang‘, ‘www.bokey.io‘, ‘python‘]) >>> myinfor.keys() dict_keys([‘name‘, ‘stie‘, ‘lang‘]) >>> temp = zip(myinfor.values(),myinfor.keys()) #压缩成一个列表,每个元素是一个元祖,元祖中第一个是值,第二个是键 >>> temp <zip object at 0x10239ee08> >>> dict(temp) #这是函数dict()的功能 {‘tajzhang‘: ‘name‘, ‘www.bokey.io‘: ‘stie‘, ‘python‘: ‘lang‘}
2.6 enumerate()
功能:类似同事得到元素索引和元素
>>> for i in range(len(week)): print(week[i] + ‘is‘ + str(i) ) mondayis0 sundayis1 fridayis2 >>> for (i,day) in enumerate(week): print(day + ‘is‘ + str(i)) mondayis0 sundayis1 fridayis2
使用举例:
>>> seasons = [‘Spring‘,‘Summer‘,‘Fall‘,‘Winter‘] >>> list(enumerate(seasons)) [(0, ‘Spring‘), (1, ‘Summer‘), (2, ‘Fall‘), (3, ‘Winter‘)] >>> list(enumerate(seasons,start=1)) [(1, ‘Spring‘), (2, ‘Summer‘), (3, ‘Fall‘), (4, ‘Winter‘)] >>> mylist = ["tajzhang",703,"python"] >>> enumerate(mylist) <enumerate object at 0x1023b6288> >>> list(enumerate(mylist)) [(0, ‘tajzhang‘), (1, 703), (2, ‘python‘)]
使用练习:
2.7列表解析
先得到1-9每个整数的平方
>>> power2 = [] >>> for i in range(1,10): power2.append(i*i) >>> power2 [1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = [x**2 for x in range(1,10)] #更pythonic的用法 >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81] >>> mybag = [‘ glass‘,‘ apple‘,‘ green leaf‘] >>> [one.strip() for one in mybag] [‘glass‘, ‘apple‘, ‘green leaf‘]
3、while循环
原理图
以上是关于老齐python-基础6(循环 if while for)的主要内容,如果未能解决你的问题,请参考以下文章
python入门基础2 if语句 while循环 for循环