跳轉至內容

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 行!當然,您會失去很多通用性——房間中的所有物品都做同樣的事情。當您找到鑰匙時,您會自動開啟門。遊戲變得不那麼有趣了。它也變得更難改變。

華夏公益教科書