跳转至内容

Python 入门教程/for循环

来自维基教科书,开放的书籍,开放的世界

好吧,在第一节关于循环的课中,我说我会等到我们学到列表后才教你for循环。现在,它来了!

'for' 循环

[编辑 | 编辑源代码]

基本上,for 循环对列表中的每个值执行操作。它的写法有点令人困惑,但除此之外非常简单。以下是在代码中的示例

代码示例 1 - for 循环
# Example 'for' loop
# First, create a list to loop through:
newList = [45, 'eat me', 90210, "The day has come, the walrus said, to speak of many things", -67]

# create the loop:
# Goes through newList, and sequentially puts each bit of information
# into the variable value, and runs the loop
for value in newList:
    print(value)

如您所见,当循环执行时,它会遍历 'in' 后面提到的列表中的所有值。然后它将它们放入 value 中,并执行循环,每次 value 的值都不同。让我们再看一个例子,一个我们都知道的经典啦啦队口号

代码示例 2 - for 循环示例
# cheerleading program
word = input("Who do you go for? ")

for letter in word:
    call = "Gimme a", letter + "!"
    print(call)
    print(letter + "!")
print("What does that spell?")
print(word + "!")

您刚刚学习了几件事

如您所见,字符串(记住 - 字符串是文本行)只是包含大量字符的列表。程序遍历了 word 中的每个字母(或值),并在屏幕上打印了它们。

代码示例 3 - 循环遍历范围

有时,您可能只需要循环特定次数(例如 10 次)。如果您来自其他编程语言,您可能正在寻找类似于此格式的普通 for 循环

for (var i = 1 ; i < 10 ; i++ ) {
}

Python 没有这种类型的循环。如果您想循环特定次数,只需使用 range()。

# The below code will print numbers from 0 through 9
for integer in range(0,10):
  print(integer)

# The above code can further be simplified to:
# for integer in range(10):
#   print(integer)

您必须注意几件事

  • 范围从起始数字开始,一直到(但不包括)结束数字。如果您想从 0 循环到 100,您的范围函数将是 range(0,101),因为该函数不包含结束数字。
  • range 函数的参数是起始值(默认值为 0)、结束值和步长(默认值为 1)。步长只是 range() 的递增量。如果您想从 100 循环到 0,只需使用 -1 的步长。换句话说:range(100,0,-1)。

制作菜单函数

[编辑 | 编辑源代码]

现在进入这节课的重点。让我们开始编写程序。到目前为止,我们已经学习了变量、列表、循环和函数。这几乎是我们进行大量编程所需的一切。因此,让我们给自己设定一个任务。

代码示例 4 - 菜单函数
# THE MENU FUNCTION
# The program asks for a string with all the menu options in it,
# and a text string asking a question.
# make sure every menu entry is unique.

def menu(list, question):
    for entry in list:
        print(1 + list.index(entry),)
        print(") " + entry)

    return input(question) - 1

# def menu(list, question): is telling the function to
# ask for two bits of information:
# A list of all the menu entries,
# and the question it will ask when all the options have been printed

# for entry in list: is pretty much saying;
#'for every entry in the list, do the following:'

# print list.index(entry) + 1 uses the .index() function to find
# where in the list the entry is in. print function then prints it
# it adds 1 to make the numbers more intelligible.

# print ") " + entry prints a bracket, and then the entry name

# after the for loop is finished, input(question) - 1 asks the question,
# and returns the value to the main program (minus 1, to turn it back to
# the number the computer will understand).

这并不难,是吗?实际的程序只占用了五行——这就是我们到目前为止所学内容的奇妙之处!我所有的注释占用了十六行——超过了程序长度的三倍。对程序进行大量注释是一个好主意。请记住,如果您要公开发布您的代码,将会有很多人查看您编写的代码。我们将在第一个示例程序中看到我们刚刚编写的函数。

我们的第一个“游戏”

[编辑 | 编辑源代码]

我们的第一个示例程序是什么?如何做一个(非常)简单的文字冒险游戏?听起来很有趣!它只包含一个房间,并且非常简单。将有五样东西和一扇门。在五样东西中,有一把通往门的钥匙。您需要找到钥匙,然后打开门。我将先给出普通英语的版本,然后再用 Python 编写

代码示例 5 - 代码的普通英语版本
#Plain-english version of our 'game'

Tell the computer about our menu function

Print a welcoming message, showing a description of the room.
We will give the player six things to look at: plant, painting,\
 vase, lampshade, shoe, and the door

Tell the computer that the door is locked
Tell the computer where the key is

present a menu, telling you what things you can 'operate':
    It will give you the six options
    It will ask the question "what will you look at?"

if the user wanted to look at:
    plant:
        If the key is here, give the player the key
        otherwise, tell them it isn't here
    painting:
        same as above
    etc.
    door:
        If the player has the key, let them open the door
        Otherwise, tell them to look harder

Give the player a well done message, for completing the game.

从这里,我们可以编写一个真正的程序。准备好了吗?它来了(跳过键入注释)

代码示例 6 - 文字冒险游戏
#TEXT ADVENTURE GAME

#the menu function:
def menu(list, question):
    for entry in list:
        print(1 + list.index(entry),)
        print(") " + entry)

    return int(input(question)) - 1

#Give the computer some basic information about the room:
items = ["plant","painting","vase","lampshade","shoe","door"]

#The key is in the vase (or entry number 2 in the list above):
keylocation = 2

#You haven't found the key:
keyfound = 0

loop = 1

#Give some introductory text:
print("Last night you went to sleep in the comfort of your own home.")

print("Now, you find yourself locked in a room. You don't know how")
print("you got there, or what time it is. In the room you can see")
print(len(items), "things:")
for x in items:
    print(x)
print("")
print("The door is locked. Could there be a key somewhere?")
#Get your menu working, and the program running until you find the key:
while loop == 1:
    choice = menu(items,"What do you want to inspect? ")
    if choice == 0:
        if choice == keylocation:
            print("You found a small key in the plant.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the plant.")
            print("")
    elif choice == 1:
        if choice == keylocation:
            print("You found a small key behind the painting.")
            print("")
            keyfound = 1
        else:
            print("You found nothing behind the painting.")
            print("")
    elif choice == 2:
        if choice == keylocation:
            print("You found a small key in the vase.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the vase.")
            print("")
    elif choice == 3:
        if choice == keylocation:
            print("You found a small key in the lampshade.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the lampshade.")
            print("")
    elif choice == 4:
        if choice == keylocation:
            print("You found a small key in the shoe.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the shoe.")
            print("")
    elif choice == 5:
        if keyfound == 1:
            loop = 0
            print("You put in the key, turn it, and hear a click")
            print("")
        else:
            print("The door is locked, you need to find a key.")
            print("")

print("Light floods into the room as you open the door to your freedom.")

嗯,一个非常简单但有趣的遊戲。不要被代码量吓到,53 行只是 'if' 语句,这是最容易阅读的部分。(一旦您理解了所有缩进,您就可以制作自己的游戏,并且可以根据自己的喜好制作它,既可以简单,也可以复杂。)

改进游戏

[编辑 | 编辑源代码]

您应该问的第一个问题是“这个程序能运行吗?”答案是肯定的。然后您应该问“这个程序运行得很好吗?”——不完全是。menu() 函数很棒——它减少了很多键入工作。然而,我们使用的 'while' 循环有点乱——对于一个简单的程序来说,有四级缩进。我们可以做得更好!

现在,当我们介绍类时,这将变得非常非常简单。但那必须等待。在此之前,让我们创建一个函数来减少我们的混乱。我们将传递两件事:我们选择的菜单和钥匙的位置。它将返回一件事——是否找到了钥匙。让我们看看

代码示例 7 - 创建检查函数
def inspect(choice,location):
    if choice == location:
        print("")
        print("You found a key!")
        print("")
        return 1
    else:
        print("")
        print("Nothing of interest here.")
        print("")
        return 0

现在主程序可以简化一点。让我们从 while 循环中提取它,并更改一下

代码示例 8 - 新游戏
while loop == 1:
    keyfound = inspect(menu(items,"What do you want to inspect? "), keylocation)
    if keyfound == 1:
        print("You put the key in the lock of the door, and turn it. It opens!")
        loop = 0

print("Light floods into the room, as you open the door to your freedom.")

现在程序变得非常短——从繁琐的 83 行缩减到非常紧凑的 50 行!当然,您会失去很多通用性——房间中的所有物品都做同样的事情。当您找到钥匙时,您会自动打开门。游戏变得不那么有趣了。它也变得更难改变。

华夏公益教科书