首页 > 解决方案 > Python:尽管输入相同,但输入未被识别为变量

问题描述

所以我一直在学习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 如果有人可以分享我需要更改的内容,我将不胜感激

标签: python

解决方案


更改后的代码(仅 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)

推荐阅读