python代码结构(第四章)

第四章:代码结构
1.使用if、elif和else进行比较
disaster = True
if disaster:
print("woe!")
else:
print("whee!")
输出:
woe!

furry = True
small = True
if furry:
if small:
print("it's a cat")
else:
print("it's a beer")
else:
if small:
print("it;s a skink")
else:
print("it's a human.or a hairless bear")
输出:
it's a cat

color = "puce"
if color == "red":
print("it;s a tomato")
elif color == "green":
print("it's a green pepper")
elif color == "bee purple":
print("i don't know what it is,but only bees can see it")
else:
print("I;ve never heard of the color",color)
输出:
I;ve never heard of the color puce

some_list = []
if some_list:
print("There's something in here")
else:
print("Hey,it's empty")
输出:
Hey,it's empty



2.使用while进行循环
使用if、elif和else条件判断的列子是自顶向下执行的,但是有时候我们需要重复一些操作-循环,
python最简单的操作是while
count = 1        #首先将变量count赋值为1 
while count <= 5:            #while循环比较count的值和5的大小关系,如果count小于等于5的话继续执行
print(count)
count += 1
输出:
1
2
3
4
5


3.使用break跳出循环
如果想让循环在某一条件停止,但是不确定有哪次循环跳出,可以在无限循环中声明break语句
我们通过python的input()函数从键盘输入一行字符串,然后将字符串首字母转换成大写输出,当输入的一行仅含有字符q时,跳出循环
while True:
stuff = input("string to capitalize[type q to quit]:")
if stuff =="q":
break
print(stuff.capitaliz())
输出:
string to capitalize[type q to quit]:test
Test
string to capitalize[type q to quit]:hey,it work
Hey,it work
string to capitalize[type q to quit]:q
integer,please[q to quit]:



4.使用continue跳到循环开始
有时我们并不想结束整个循环,仅仅想跳到下一轮循环的开始。下面是编造的列子:
读入一个整数,如果它是奇数则读出它的平方数,如果是奇数则输出它的平方数,如果是偶数则跳过,同样使用q结束循环
while True:
value = input("integer,please[q to quit]:")
if value == "q":                   #如果是q则停止,跳出循环
break
    number = int(value)
    if number % 2== 0:                    #如果是偶数就跳到循环的最开始,如果是奇数就输出平方和
        continue
    print(number,"squared is",number*number)
输出:
integer,please[q to quit]:1
1 squared is 1
integer,please[q to quit]:2
integer,please[q to quit]:3
3 squared is 9
integer,please[q to quit]:q


Process finished with exit code 0


5.循环外使用else
如果while循环正常结束(没有使用break跳出),程序将进入到可选的else段,当你使用循环来遍历检查某一数据结构时,找到满足条件的解使用break跳出;
循环结束,即没有找打可行解时,将执行else部分代码
numbers = [1,3,5]     #将1,3,5赋值给numbers
position = 0          #起始的position是0
#print(numbers[position])
while position < len(numbers):     #当position小于numbers的长度时,执行循环语句
number = numbers[position]     #将numbers[0]=1最开始,赋值给number,
#print(numbers[position])
if number % 2== 0:              #number除以2余数为1,因此不输出,而是继续执行
print('found even number',number)
        break
position += 1                    #positon=position+1,此时position=0+1=1,然后又返回循环的最开始,执行while循环,直到执行到position < len(position)不成立为止
#print(position)
else:
print('no even number found')     #当position >= len(position)时,输出
输出:
no even number found


6.使用for迭代
rabbits = ['flopsy','mopsy','cottontail','peter']
current = 0
while current < len(rabbits):
print(rabbits[current])
current += 1
输出:
flopsy
mopsy
cottontail
peter

for rabbit in rabbits:
print(rabbit)
输出:
flopsy
mopsy
cottontail
peter

列表(列如rabbits)、字符串、元组、字典、集合等都是python可迭代的对象,元组或列表在一次迭代过程产生一项,而字符串迭代会产生一个字符,如下所示:
word = 'cat'
for letter in word:
print(letter)
输出:
c
a
t

对一个字典(或字典的keys()函数)进行迭代将返回字典的键,在下面的列子中,字典的键为图版游戏的牌的类型
accusation = {'room':'ballroom','weapon':'lead pipe',
              'person':'col.mustard'}
for card in accusation:  #或者是for card in accusation.key() ,将返回字典的键
print(card)
输出:
room
person
weapon

for value in accusation.values():
    print(value)    #对字典的值进行迭代。可以使用字典的value()函数,返回字典的值
输出:
ballroom
col.mustard
lead pipe

for item in accusation.items():
    print(item)      #以元组的形式返回键值对,可以使用字典的items()函数
输出:
('room', 'ballroom')
('person', 'col.mustard')
('weapon', 'lead pipe')

for card,contents in accusation.items():
    print('card', card, 'has the contents', contents)  
输出:            #元组只能被初始化一次,它的值是不能改变的,对于调用函数items()返回的每一个元组,将第一个返回值(键)赋给card,第二个返回值赋给contents
card room has the contents ballroom
card person has the contents col.mustard
card weapon has the contents lead pipe




7.循环外使用else
cheeses = []
for cheese in cheeses:  #如果cheese出现在cheeses打印出cheese
print('this shop has some lvely',cheese)
break      #并跳出循环
else:  #没有break表示没有找到奶酪,cheeses中不存在cheese则执行else
print('this is not much of a cheese shop,is it?')
输出:
this is not much of a cheese shop,is it?






















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值