簡體   English   中英

if語句在函數內部的行為不同

[英]if statement behaving differently inside function

好吧,所以我需要為python創建一個簡單的子手游戲。 而且我的函數和變量有問題。 當我嘗試一個簡單的if循環時,猜測並替換“空白”是可行的,但是一旦我將所有內容放入適當的函數中,它就會給我帶來問題。

例如,當一個單詞有一個以上的字母實例時,嘗試在函數外執行if循環時會同時顯示兩個字母,但是使用該函數時它只會顯示1。我刪除了舊程序並重新啟動,但是我仍然有此功能的麻煩(這很令人發瘋)。 在我遇到問題之前,還更新了starCopy和嘗試。 這么簡單的程序有這么多麻煩,真讓我不寒而栗。 :\\

這是在函數外部起作用的循環:

import random
#declare variables
guess="a"
choice="barnyard"
starredUp=len(choice) * "*"
starCopy=starredUp
attemptedLetters=[]
running=True
attempts=0

if guess in choice:
    starCopy=list(starCopy)
    for i, x in enumerate(choice):
        if x == guess:
            starCopy[i]=guess
            print(" ".join(starCopy));
            print("Letter in word! " + "Wrong Attempts: " + str(attempts))

返回* * r * * * r * Letter in word! Wrong Attempts: 0 * * r * * * r * Letter in word! Wrong Attempts: 0

現在,當我嘗試調用該函數時:

def guessMan(guess, choice, attempts, starCopy):
    if guess in choice:
        starCopy=list(starCopy)
        for i, x in enumerate(choice):
            if x == guess:
                starCopy[i]=guess
                print(" ".join(starCopy))
                print("Letter in word! " + "Wrong Attempts: " + str(attempts))
                return(starCopy)
    elif guess not in choice:
          attempts+=1
          print("yo fix it")
    elif guess in attemptedLetters:
          print("already guessed")
guessMan("r", choice, attempts, starCopy)

它返回:

* * r * * * * *
Letter in word! Wrong Attempts: 0

老實說,我不確定為什么要用這種方式撞到這樣的磚牆。 感覺就像我缺少了一些超級簡單的東西。

輸出更改,因為在基於函數的示例中,您返回了變量starCopy。 它在碰到與“ guess”匹配的第一個字母后立即返回,因此只有第一個字母被替換。 將return命令移到末尾應該可以工作:

def guessMan(guess, choice, attempts, starCopy):
    if guess in choice:
        starCopy=list(starCopy)
        for i, x in enumerate(choice):
            if x == guess:
                starCopy[i]=guess
                print(" ".join(starCopy))
                print("Letter in word! " + "Wrong Attempts: " + str(attempts))

    elif guess not in choice:
          attempts+=1
          print("yo fix it")
    elif guess in attemptedLetters:
          print("already guessed")

    return(starCopy)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM