python随机猜词程序
我正在用python编写一个猜字游戏,但在计算guess()函数中的算法时遇到了困难 当用户猜到一个正确的字母并被该字符替换时,空白(u0)将相应地消失。然而,即使用户猜到了正确的单词,仍有一些单词仍然存在。如何调整格式,使其被猜测的字符替换 另一个问题是,无论我的单词是对是错,程序都会给我10次尝试。我猜测在尝试时使用if语句或for循环进行迭代,但我不确定。在我说出正确的词后,如何让它停止 多谢各位python随机猜词程序,python,Python,我正在用python编写一个猜字游戏,但在计算guess()函数中的算法时遇到了困难 当用户猜到一个正确的字母并被该字符替换时,空白(u0)将相应地消失。然而,即使用户猜到了正确的单词,仍有一些单词仍然存在。如何调整格式,使其被猜测的字符替换 另一个问题是,无论我的单词是对是错,程序都会给我10次尝试。我猜测在尝试时使用if语句或for循环进行迭代,但我不确定。在我说出正确的词后,如何让它停止 多谢各位 def pick(): print() f = op
def pick():
print()
f = open('words.txt', 'r')
wlist = f.readlines()
f.close()
chosenword = random.choice(wlist)
return(chosenword)
def guess():
#Determine length of chosen word and display number of blanks
chosenword = pick()
pH = '_ ' * (len(chosenword)-1)
print()
print (pH)
print()
#Number of failed attempts
attempt = 0
count = 10
#Receive guess
for i in range (0, 10):
attempt += 1
guess = input("Enter a letter for a guess : ")
guess = guess.upper()
#Check if guess is found in random word
if guess in chosenword:
for i in range (0,len(chosenword)):
if guess == chosenword[i]:
pH = pH[:i] + guess + pH[i+1:]
print(pH)
if guess not in chosenword:
print(pH)
if pH == chosenword:
print ("You guessed the word - congrats!")
else:
print ("The word was ",chosenword)
print ("Sorry - bettter luck next time.")
guess()
pick()
下面是一个使用指定列表的版本。您可以将其更改为从文件读取。我在代码中添加了注释以显示对代码的更正
import random
def pick():
# You want to change this to load from file
wlist = ['hello', 'today', 'monday', 'every', 'neighbor']
chosenword = random.choice(wlist)
return chosenword
def guess():
#Determine length of chosen word and display number of blanks
chosenword = pick().upper() # Use upper case throughout
pH = '_' * len(chosenword) # don't subtract one from length and remove space
print (pH)
#Number of failed attempts
attempt = 0
count = 10
#Receive guess
for i in range (0, 10):
attempt += 1
guess = input("Enter a letter for a guess : ")
guess = guess.upper()
#Check if guess is found in random word
if guess in chosenword:
for i in range (0,len(chosenword)):
if guess == chosenword[i]:
pH = pH[:i] + guess + pH[i+1:]
if pH == chosenword:
break # need to break from guessing when they have guess the right word
if guess not in chosenword:
print(pH)
if pH == chosenword:
print ("You guessed the word - congrats!")
return # need to break from funtion when they guess the right word
else:
print ("The word was ",chosenword)
print ("Sorry - bettter luck next time.")
guess()
一个问题是,我认为当用户猜到正确的单词时,您需要一个“中断”来摆脱for循环。如果pH==chosenword:print(“您猜到了单词-恭喜!”),则需要在后面加一个分隔符。每个未知字符似乎是两个字符(下划线和空格),您要用字符pH='.'*(len(chosenword)-1)替换它们。还有,为什么要减去一呢?最后两行调用guess()和pick()。但是guess函数调用pick。你不应该叫guess吗?