美文网首页
Python | 控制流

Python | 控制流

作者: 一颗西蓝花_ | 来源:发表于2020-05-26 17:46 被阅读0次

一、什么是控制流

编程语言中的控制流语句用于控制各操作执行的顺序。
一段没有控制流的程序的操作顺序应当是这样的:

image.png

但是实际生活中,顺序操作并不总是能够满足我们的需求,我们可能需要对流程中的一些步骤加入控制。

举个例子,当我们在揉面团的时候,我们首先加入面粉,再倒入一点点水,之后我们还要 判断 目前的加入的水量是否合适,如果过干,需要再加入一点点水,循环 这个步骤,直到我们认为面粉和水的配比合适为止。


image.png

上面的这个流程中就包含了 判断 和 循环 两种控制流处理。

本章学习重点:

  1. conditional statements
  2. for and while loops
  3. break and continue
  4. useful built-in functions
  5. list comprehensions

二、条件语句

if phone_balance < 5:
    phone_balance += 10
    bank_balance -= 10

If、Elif、Else

  • Elif is short for else if

总结一下:Indentation非常重要,Indentation告诉了代码,哪些代码是在if条件内,哪些代码是不在if条件内
请编写一个 if 语句,使竞争者能够根据自己的得分知道获得了哪个奖品,得分存储在整型变量 points 中。
有的上下限都包含在内,points 只能是正整数,最大值为 200。

在你的 if 语句中,将一个根据 points 的值存储相应消息的字符串赋值给 result 变量。如果赢得了奖品,消息内容应该是 "Congratulations! You won a [prize name]!",“[prize name]”应替换成相应的奖品。如果没有赢得奖品,消息内容应该是 "Oh dear, no prize this time."

points = 174  # use this input to make your submission

# write your if statement here
if points >= 1 and points <= 50:
    result = 'Congratulations! You won a wooden rabbit!'
elif points >= 50 and points <= 150:
    result = 'Oh dear, no prize this time.'
elif points >= 151 and points <= 180:
    result = 'Congratulations! You won a wafer-thin mint!'
elif points >= 181 and points <= 200:
    result = 'Congratulations! You won a wooden penguin!'

print(result)

上述是我的代码,查看了一下答案,顺道将答案也贴上来

points = 174

if points <=0:
  result = " Invalid score."
elif points <= 50:
  result = "Congratulations! You won a wooden rabbit!"
elif points <= 150:
  result = "Oh dear, no prize this time."
elif points <= 180:
  result = "Congratulations! You won a wafer-thin mint!"
elif points <= 200:
  result = "Congratulations! You won a penguin!"
else:
  result = " Invalid score."

print(result)

三、条件布尔表达式

if语句有时候会使用更加复杂的条件布尔表达式,可能包括多个比较运算符、逻辑运算符、甚至包括算式。
⚠️不要使用以下代码表达

if True 或者 if False

原因:True是一个有效的布尔表达式,但是不是有用的条件。因为它始终为 True。因此缩进代码始终都要运行,False则相反,永远都不会运行

学习地址:https://classroom.udacity.com/courses/ud1110/lessons/e91dc8c3-aed0-4c0c-9a43-438c36df7b0f/concepts/69bfbde2-3f63-41ed-8793-aabf0f6a4bab


# establish the default prize value to None
prize = None

# use the points value to assign prizes to the correct prize names
if points <= 50:
    prize = 'wooden rabbit'
    if prize = None:
        Result = "Oh dear, no prize this time."
    else:
        result = 'Congratulations! You won a' + prize.

elif points <= 150:
    prize = None
    if  Prize = None:
        result = "Oh dear, no prize this time."
    else:
        
elif points <=180:
    prize = 'wafer-thin mint'
    if prize = None:
        result = "Oh dear, no prize this time."
    else:
        result = 'Congratulations! You won a' + prize.

else:
    prize = 'penguin'
    if prize = None:
        result = "Oh dear, no prize this time."
    else:
        result = 'Congratulations! You won a' + prize.
# use the truth value of prize to assign result to the correct prize


print(result)

上面是我写的,但是我去看了一下官方给的答案~不由地感叹一声,官方给的教程,写得真的太好了,贴出来

prize = None
if points <= 50:
    prize = "a wooden rabbit"
elif 151 <= points <= 180:
    prize = "a wafer-thin mint"
elif points >= 181:
    prize = "a penguin"

if prize:
    result = "Congratulations! You won " + prize + "!"
else:
    result = "Oh dear, no prize this time."

print(result)

四、For 循环

cities = ['new york city', 'moutain view', 'chicago', 'los angeles']

for index in range(len(cities)):
    cities[index] = cities[index].title()
  1. len(cities) 是 4
  2. range(len(cities))是0、1、2、3
  3. index 在range(len(cities))中循环,分别是0、1、2、3
  4. 最后,在cities这个list中来查找

在实际工作中,我们会经常使用到 range 这个函数,来做一些需要重复工作的工作。

练习:创建用户名

写一个遍历 names 列表以创建 usernames 列表的 for 循环。要为每个姓名创建用户名,使姓名全小写并用下划线代替空格。对以下列表运行 for 循环:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

应该会创建列表:

usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]

  • 先看一下我写的代码
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for i in names:
    i = usernames[i].lower().replace(" ", "_")

接着就有报错了,报错信息如下

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-2bff8f8274d5> in <module>
      1 for i in names:
----> 2     i = usernames[i].lower().replace(" ", "_")

TypeError: list indices must be integers or slices, not str

TyperError说明了什么呢,他在说 list,也就是列的索引,不能是字符串,必须是整数,或者切片。
那么我们如何在列里面进行for loop呢?我们可以使用整数索引法则,使用整数索引法则可以借助
range()
修改一下上述代码

usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

for i in range(len(usernames)):
    usernames[i] = usernames[i].lower().replace(" ", "_")

print(usernames)
练习:标记计数器

写一个 for 循环,用于遍历字符串列表 tokens 并数一下有多少个 XML 标记。XML 是一种类似于 HTML 的数据语言。如果某个字符串以左尖括号“<”开始并以右尖括号“>”结束,则是 XML 标记。使用 count 记录这种标记的数量。

你可以假设该字符串列表不包含空字符串。

看一下我写的代码

tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0

# write your for loop here
for i in range(len(tokens)):
    if (tokens[i][0] = '<') and (tokens[i][-1] = '>'):
        count = count + 1

print(count)

😢查看了一下答案,发现自己犯了一个很低级的错误,判断是否相等应该是 ==,这个小知识点,之前学的时候,觉得很简单,但是用起来,还是经常容易出问题。

五、While 循环

对list使用for 循环,会对list中的每个元素执行一次操作。for loop使用rangefunction
而使用while,是一直循环,直到某个条件被满足。
pop method 和append刚好相反,pop会移除list中的最后一个,并且返回被移除的值。

练习:最接近的平方数

写一个 while 循环,用于计算比整数 limit 小的最大平方数,并将其存储在变量 nearest_square 中。平方数是整数乘以自己后的积,例如 36 是一个平方数,因为它等于 6*6。

例如,如果 limit 是 40,你的代码应该将 nearest_square 设为 36。

看一下我写的代码

nearest_square = []

## 平方数 
while x * x < limit:
    nearest_square.append(x)

print(nearest_square[-1])

(诶,有时候,分享自己的代码,感到羞耻,自己太菜了,不过没关系,知耻而后勇

分析这段代码有什么问题

  1. x 没有被定义就使用了
  2. limit也没有被定义
    如何修改呢?
  3. 首先,将x定义一下 num = 0
  4. 定义limit,参考题中给的40
num = 0
nearest_square = []
while num **2 <40:
    num = num + 1
nearest_square.append(num**2)
print(nearest_square)

但是上述代码运行之后,是49,49好像比40 大了,我们再分析一下为什么出错。
注意看我们的while条件语句,这里是判断num的平方是否小于40,当num为6时候,while为true,就不会运行语句nearest_square.append(num**2),而是会num +,接着就是num = 7,这个时候,不满足while条件,因此会等于49。所以呢?这段代码有两个改法?
解法1

num = 0
nearest_square = []
while (num +1)**2 <40:
    num = num + 1
nearest_square.append(num**2)
print(nearest_square)

解法2

num = 0
nearest_square = []
while num **2 <40:
    num = num + 1
nearest_square.append((num-1)**2)
print(nearest_square)

六、Break & Continue

Break terminates a for or while loop / break 会结束while 或for 循环。

相关文章

  • 2020-04-27

    python从零开始学带你玩转python连载【三】--控制流与自定义函数 在Python编程中控制流和自定...

  • Python | 常用的控制流语句

    一、控制流语句介绍 了解什么是控制流语句以及Python常用的两种控制流语句。 1.控制流语句 控制流语句即用来实...

  • python 控制流

    迭代器,生成器,可迭代对象 原文来自foofish链接如下在了解Python的数据结构时,容器(container...

  • Python控制流

    最近几周学习了Python的数据类型,今天就来说说Python的控制流 回顾:Python数据类型 字符串 数字 ...

  • Python -- 控制流

    条件判断 比较操作符: > < = >= <= True False 数值:0 为假,非零为真 序列(字符串,列表...

  • python 控制流

    控制流 编程本质编程的本质是用代码模仿现实,在面向过程中,代码的类似是将静态的物体加工成最后的成品,输入的参数是待...

  • Python | 控制流

    一、什么是控制流 编程语言中的控制流语句用于控制各操作执行的顺序。一段没有控制流的程序的操作顺序应当是这样的: 但...

  • python -控制流

    程序设计的三种基本结构:顺序结构、选择结构、循环结构 1、顺序结构:是一种线性、有序的结构,依次执行各语句模块 2...

  • python 控制流

    if条件判断(注意缩进) 单个条件判断,只需要一个ifif 条件1: 条件1为真的情况下,执行的代码 多个条...

  • Python数据分析基础----第五天

    控制流 Python中提供了若干种控制流元素,包括 if - elif - else 语句、for 循环、ra...

网友评论

      本文标题:Python | 控制流

      本文链接:https://www.haomeiwen.com/subject/hbyvahtx.html