所以我一直在学习python,我正在尝试制作我的第一款游戏,只是自己尝试使用该语言并掌握它。在制作这个猜词游戏时,我遇到了一个输入问题,发现很难克服。
import sys
import os
import random
import time
word_list = ["salt","excess","product","rib","slot","battle"]
#random word from list
random_word = random.choice(word_list)
#defining word_len and making it a string so it can be used in print()
word_len = len(random_word)
word_len = str(word_len)
print("Welcome to the guessing game")
print("I will give you the length of a random word and you need to guess
what it is!")
print("The word is " + word_len + " characters long.")
print("The choices are " + "salt " + "excess " + "product" + " rib" + "
slot" + " and battle" )
print("Good luck!")
#reads the input and defines it
word_guess = sys.stdin.readline()
if word_guess is random_word :
print("Congratulations! You guessed correctly!")
#else which is running despite if being met
else :
print("You lost! :( The word was " + random_word)
#sleep for 5 seconds so the terminal doesnt close
time.sleep(5)
问题是运行代码时会产生以下情况: https://i.imgur.com/Kx2dCiU.png 如果有人可以分享我需要更改的内容,我将不胜感激
答案 0 :(得分:0)
更改的代码(仅if else部分)。 readline将换行符保留在字符串中。因此,我们应该在比较之前将其删除。
word_guess = sys.stdin.readline()
word_guess = word_guess[:-1]
if random_word == word_guess :
print("Congratulations! You guessed correctly!")
#else which is running despite if being met
else :
print("You lost! :( The word was " + random_word)
答案 1 :(得分:0)
is和equals(==)之间的Python区别is运算符可能看起来与equals运算符相同,但是它们并不相同。 is检查两个变量是否指向同一对象,而==符号检查两个变量的值是否相同。
我想在您的代码中再指出一个缺陷。
word_list = ["salt","excess","product","rib","slot","battle"]
#Battle and excess is of same length
#slot and salt is of same length
#random word from list
random_word = random.choice(word_list)
word_len = len(random_word)
word_len = str(word_len)
#As you pick this random, chances of picking length 4 and word 'salt' is good. Whereas you could predict is as 'slot' and get an unexpected error even though you are correct.
因此,请修改列表,例如:
word_list = ["salt","excess","product","rib"]
即使在代码中将'is'更改为'=='后,仍对错误输出进行采样:
Welcome to the guessing game
I will give you the length of a random word and you need to guess what it is!
The word is 4 characters long.
The choices are salt excess product rib slot and battle
Enter the word : salt
Good luck!
You said salt
You lost! :( The word was slot
SLOT和SALT均为4个字母:) 随时在这里实现其他逻辑。
答案 2 :(得分:0)
word_guess = sys.stdin.readline() work_guess在末尾附加了\ n值,以便说明为什么不匹配。
替换 如果word_guess是random_word:
作者 如果word_guess [0:-1] == random_word:
它将起作用。
也请点击here来查看==并且位于python中。
答案 3 :(得分:0)
如果要使用sys.stdin.readlines(),则必须指定EOF,否则可以通过输入提示简单地读取输入,两者都很好。EOF is Needed `