簡體   English   中英

'for char in word:' 在 Python 中不起作用

[英]'for char in word:' not working in Python

我正在制作一個簡單的劊子手游戲,我的電腦上有一個大約 5,000 個單詞的單詞列表,我用這些單詞列出了一個列表,然后使用隨機 function 隨機選擇一個游戲,但它打印了一個其中太多:'-',當我試圖猜測這個詞時,我使用了命令'for char in word:'來計算字符數並打印出正確數量的'-'。

import time
import random

List = open("nouns.txt").readlines()

name = input("What is your name? ")

print ("Hello, ", name, "Time to play hangman!")

time.sleep(1)

print ("Start guessing...")
time.sleep(0.5)

Word = random.choice(List)

guesses = ''
turns = 20

while turns > 0:         

    failed = 0

    for char in Word:      

        if char in guesses:    

            print (char)

        else:

            print ("_")     

            failed += 1    

    if failed == 0:        
        print ("\nYou won" ) 

        break              

    guess = input("guess a character:") 

    guesses += guess                    

    if guess not in Word:  

        turns -= 1        

        print ("Wrong")    

        print ("You have", + turns, "more guesses")

        print ("The word was ", Word)

        if turns == 0:           

            print ("You Loose" )

此處的原因是您從文件中讀取行,並且每行末尾都有一個“換行符”(“\n”)字符。 當你遍歷字符時,你會得到這個作為最后一個字符。

您可以使用 strip() 方法來擺脫它:Word = random.choice(List).strip()

而且我認為你應該在這里使用 raw_input() 而不是 input() 方法,或者你可能使用 python 3.x 那么它就可以了。

暫無
暫無

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

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