我正在学习Python,我正在努力让这个游戏发挥作用。基本上我指定了一个要猜测的单词然后将单词切成小块并将其分配给其他几个变量。基本上,分配为“letterx”的每个变量都是一个字母,它构成字符串变量字的一部分。问题是使用嵌套的if语句获取while语句。出于某种原因,我无法将猜测输入设置为等于letterx。我运行代码时得到的只是“不”。然后剩下的转弯量。但是,我无法让elif声明工作。几乎所有其他工作。我习惯用Java编程,我对Python很新,所以任何提示或帮助都会非常感激。感谢您的时间和帮助!这是代码:
#Guess The Word
word = "action"
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
print("Welcome to Guess the Word!\n")
count = 6
while(count != 0):
guess = input("Take a guess: \n")
if(guess != letter1 or guess != letter2 or guess != letter3 or guess !=
letter4 or guess != letter5 or guess != letter6):
count -= 1
print("No.\n")
print("Turns left: \n", count)
elif(guess == letter1 or guess == letter2 or guess == letter3
or guess == letter4 or guess == letter5 or guess == letter6):
count -= 1
print("Yes.\n")
if(count == 0):
print("Your turns are up, what do you think the word is?")
guess = input("The word is...: \n")
if(guess == word):
print("You win! That's the word")
elif(guess != word):
print("Sorry, you lose.")
这是在Python shell中运行的程序:
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Welcome to Guess the Word!
Take a guess:
a
No.
Turns left:
5
Take a guess:
c
No.
Turns left:
4
Take a guess:
t
No.
Turns left:
3
Take a guess:
i
No.
Turns left:
2
Take a guess:
o
No.
Turns left:
1
Take a guess:
n
No.
Turns left:
0
Your turns are up, what do you think the word is?
The word is...:
action
You win! That's the word
答案 0 :(得分:0)
我们说guess
等于letter1
。然后即使
guess == letter1
,自guess != letter2
以来,第一个条件仍为True。同样地,无论guess
是什么,都有一些字母(letter1
,letter2
等),它不相等。
因此第一个if
条件始终为True。
相反,您可以使用
while(count != 0):
guess = input("Take a guess: \n")
if not guess in word:
count -= 1
print("No.\nTurns left: \n", count)
else:
count -= 1
print("Yes.\n")
顺便说一下,完全可以在不定义letter1
,letter2
等的情况下对游戏进行编码。所有这些代码都应该删除:
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
只需使用word[0]
代替letter1
,word[1]
代替letter2
等。
请注意,您甚至可能不需要word[0]
,word[1]
。例如,
使用Python,您可以使用
guess in word
而不是
guess in (word[0], word[1], word[2], word[3], word[4], word[5])
不仅打字少得多,而且更为通用,因为guess in word
使用任意长度的单词做正确的事。