我正在尝试学习python,我正在尝试一个刽子手游戏.但是,当我尝试将用户的猜测与单词进行比较时,它不起作用.我错过了什么?
import sys
import codecs
import random
if __name__ == '__main__':
try:
wordlist = codecs.open("words.txt", "r")
except Exception as ex:
print (ex)
print ("\n**Could not open file!**\n")
sys.exit(0)
rand = int(random.random()*5 + 1)
i = 0
for word in wordlist:
i+=1
if i == rand:
print (word, end = '')
break
wordlist.close()
guess = input("Guess a letter: ")
print (guess) #for testing purposes
for letters in word:
if guess == letters:
print ("Yessssh")
#guessing part and user interface here
Run Code Online (Sandbox Code Playgroud)
在" for word in wordlist"循环中,每个单词将以换行符结尾.尝试添加word = word.strip()下一行.
顺便说一句,你的最后一个循环可以替换为:
if guess in word:
print ("Yessssh")
Run Code Online (Sandbox Code Playgroud)
额外提示:添加"调试打印"时,使用repr通常是个好主意(特别是在处理字符串时).例如,你的行:
print (guess) #for testing purposes
Run Code Online (Sandbox Code Playgroud)
如果你写的话可能会更有用:
print (repr(guess)) #for testing purposes
Run Code Online (Sandbox Code Playgroud)
这样,如果有奇怪的字符guess,你会在调试输出中更容易看到它们.
| 归档时间: |
|
| 查看次数: |
722 次 |
| 最近记录: |