前言
本次主要讲解循环语句,其中包括if语句及其嵌套语句的使用、for语句和while语句。
一、IF语句
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are dogs.")
附加练习
1、你认为 if 对它下面的代码起什么作用?
if 语句在代码中创建了一个“分支”(branch),有点类似于在一本冒险书中,你选择了哪个答案,就翻到对应的那一页,如果你选择了不同的答案,就会去到不同的地方。if 语句就是告诉脚本,如果这个布尔表达式是 True,那就运行它下面的代码,否则的话就跳过。
2、为什么 if 下面的代码要缩进 4 个空格?
通过一行代码结尾的冒号告诉 Python 你在创建一个新的代码块,然后缩进四个空格告诉 Python 这个代码块中都有些什么。这就跟本书前半部分中你学的函数是一样的。
3、如果没有缩进会发生什么?
如果没有缩进,你很可能收到一个错误提示。Python 一般会让你在一个带 : 的代码行下面缩进一些内容。
4、你能把一些布尔表达式放进 if 语句吗?试试看。
if True:
print("这是True")
if False:
print("这是False")
if True and False:
print("false")
if True or False:
print("false")
5、如果你改变 people,cats 和 dogs 的初始值会发生什么?
people = 15
cats = 30
dogs = 20
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are dogs.")
people = 30
cars = 40
trucks = 15
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print("Maybe we could take the trucks.")
else:
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.")
附加练习
1、试着猜猜 elif 和 else 的作用是什么?
else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子句则是需要检查更多条件时会被使用,与if和else一同使用,elif是else if 的简写。
2、改变 cars,people,和 trucks 的数值,然后追溯每一个 if 语句,看看什么会被打印出来。
people = 25
cars = 18
trucks = 30
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print("Maybe we could take the trucks.")
else:
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.")
3、试试一些更复杂的布尔表达式,比如cars > people 或者 trucks < cars。
people = 25
cars = 18
trucks = 30
if cars > people or trucks < cars :
print("We should take the cars.")
print("Maybe we could take the trucks.")
elif cars < people and trucks > cars:
print("We should not take the cars.")
print("That's too many trucks.")
else:
print("We can't decide.")
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.")
常见问题
如果多个 elif 块都是 True 会发生什么? Python 从顶部开始,然后运行第一个是 True 的代码块,也就是说,它只会运行第一个。
1.IF嵌套使用
print("""You enter a dark room with two doors.Do you go through door #1 or door #2?""")
door = input("> ")
if door == "1":
print("There's a giant bear here eating a cheese cake.")
print("What do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
bear = input("> ")
if bear == "1":
print("The bear eats your face off. Good job!")
elif bear == "2":
print("The bear eats your legs off. Good job!")
else:
print(f"Well, doing {bear} is probably better.")
print("Bear runs away.")
elif door == "2":
print("You stare into the endless abyss at Cthulhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies.")
insanity = input("> ")
if insanity == "1" or insanity == "2":
print("Your body survives powered by a mind of jello.")
print("Good job!")
else:
print("The insanity rots your eyes into a pool of muck.")
print("Good job!")
else:
print("You stumble around and fall on a knife and die. Good job!")
附加练习
给这个游戏加一些新内容,同时改变用户可以做的决定。尽可能地扩展这个游戏,直到它变得很搞笑。
print("""You enter a dark room with two doors.Do you go through door #1 or door #2 or door #3?""")
door = input("> ")
if door == "1":
print("There's a giant bear here eating a cheese cake.")
print("What do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
bear = input("> ")
if bear == "1":
print("The bear eats your face off. Good job!")
elif bear == "2":
print("The bear eats your legs off. Good job!")
else:
print(f"Well, doing {bear} is probably better.")
print("Bear runs away.")
elif door == "2":
print("You stare into the endless abyss at Cthulhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies.")
insanity = input("> ")
if insanity == "1" or insanity == "2":
print("Your body survives powered by a mind of jello.")
print("Good job!")
else:
print("The insanity rots your eyes into a pool of muck.")
print("Good job!")
elif door == "3":
print("What do you want to do?")
print("1. Watching TV.")
print("2. eating fruits.")
print("3. Sleeping.")
insanity = input("> ")
if insanity == "1" :
print("It is a good choice.")
print("Good job!")
elif insanity == "2":
print("It is good for you.")
print("Good job!")
else:
print("You are a good boy.")
else:
print("You stumble around and fall on a knife and die. Good job!")
常见问题
1、我能用一系列的 if 语句来代替 elif 吗?
在某些情况下可以,但是取决于每个 if/else 是怎么写的。如果这样的话还意味着 Python 将会检查每一个 if-else 组合,而不是像 if-elif-else 组合那样只会检查第一个是 false 的。
2、如何表示一个数字的区间?
有两种方式:一种是 0 < x < 10 或者 1 <= x < 10 这种传统表示方法,另一种是 x 的区间是 (1, 10)。
3、如果想在 if-elif-else 代码块中放更多的选择怎么办?
为每种可能的选择增加更多的 elif 块。
二、FOR语句
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# also we can go through mixed lists too
# notice we have to use {} since we don't know what's in it
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print(f"Element was: {i}")
常见问题
1、如何创建一个二维列表?
可以用这种列表中的列表:[[1,2,3],[4,5,6]]
2、列表(lists)和数组(arrays)难道不是一个东西吗?
这取决于语言以及实现方法。在传统术语中,列表和数组的实现方式不同。在 Ruby 中都叫做 arrays,在 python 中都叫做 lists。所以我们就把这些叫做列表。
3、为什么 for-loop 可以用一个没有被定义的变量?
变量在 for-loop 开始的时候就被定义了,它被初始化到了每一次 loop 迭代时的当前元素中。
4、为什么 range(1, 3) 中的 i 只循环了两次而不是三次?
range() 函数只处理从第一个到最后一个数,但不包括最后一个数,所以它在 2 就结束了。这是这类循环的通用做法。
5、element.append() 的作用是什么?
它只是把东西追加到列表的末尾。打开 Python shell 然后创建一个新列表。
三、while语句
现在我们来看一个新的循环: while-loop。只要一个布尔表达式是 True,while-loop 就会一直执行它下面的代码块。
while-loop,它所做的只是像 if 语句一样的测试,但是它不是只运行一次代码块,而是在 while 是对的地方回到顶部再重复,直到表达式为 False。
但是 while-loop 有个问题:有时候它们停不下来。如果你的目的是让程序一直运行直到宇宙的终结,那这样的确很屌。但大多数情况下,你肯定是需要你的循环最终能停下来的。
为了避免这些问题,你得遵守一些规则:
1、保守使用 while-loop,通常用 for-loop 更好一些。
2、检查一下你的 while 语句,确保布尔测试最终会在某个点结果为 False。
3、当遇到问题的时候,把你的 while-loop 开头和结尾的测试变量打印出来,看看它们在做什么。
i = 0
numbers = []
while i < 6:
print(f"At the top i is {i}")
numbers.append(i)
i = i + 1
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
常见问题
1、for-loop 和 while-loop 的区别是什么?
for-loop 只能迭代(循环)一些东西的集合,而 while-loop 能够迭代(循环)任何类型的东西。不过,while-loop 很难用对,而你通常能够用 for-loop 完成很多事情。
2、循环好难,应该如何理解它们?
人们不理解循环的主要原因是他们跟不上代码的运行。当一个循环运行的时候,它会过一遍代码块,到结尾之后再跳到顶部。为了直观表现这个过程,你可以用 print 打印出循环的整个过程,把 print 行写在循环的前面、顶部、中间、结尾。研究一下输出的内容,试着理解它是如何运行的。
分支和函数
from sys import exit
def gold_room():
print("This room is full of gold. How much do you take?")
choice = input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print("Nice, you're not greedy, you win!")
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
print("There is a bear here.")
print("The bear has a bunch of honey.")
print("The fat bear is in front of another door.")
print("How are you going to move the bear?")
bear_moved = False
while True:
choice = input("> ")
if choice == "take honey":
dead("The bear looks at you then slaps your face")
elif choice == "taunt bear" and not bear_moved:
print("The bear has moved from the door.")
print("You can go through it now.")
bear_moved = True
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg.")
elif choice == "open door" and bear_moved:
gold_room()
else:
print("I got no idea what that means.")
def cthulhu_room():
print("Here you see the great evil Cthulhu.")
print("He, it, whatever stares at you and you go insane.")
print("Do you flee for your life or eat your head?")
choice = input("> ")
if "flee" in choice:
start()
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
print(why, "Good job!")
exit(0)
def start():
print("You are in a dark room.")
print("There is a door to your right and left.")
print("Which one do you take?")
choice = input("> ")
if choice == "left":
bear_room()
elif choice == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
常见问题
1、为什么你要用 while True?
这样可以构建一个无限循环。
2、exit(0) 是干什么用的?
在很多操作系统中,一个程序可以用 exit(0) 来结束,其中传入的数字代表是否有错误。如果你用 exit(1) 代表有 1 个错误, exit(0) 则代表程序正常退出。它不同于通常的布尔逻辑(0==False),因为你可以用不同的数字来表示不同的错误结果。你可以用 exit(100) 来表示与 exit(2) 或者 exit(1) 不同的错误结果。
3、为什么 input() 有时会被写成 input(’> ')?
input 的参数是一个字符串,所以要在获取用户输入的内容前面加一个提示符。这里 > 也可以换成想要提示用户的文字。
总结
本篇文章主要讲解了for、if、 while这三种常用的循环,并举例来理解其工作原理。