python - 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 如果有人可以分享我需要更改的内容,我将不胜感激
解决方案
更改后的代码(仅 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)
推荐阅读
- javascript - 在顺序循环中修改多个 Highcharts
- swift - 导航控制器不释放内存,内存泄漏?
- tfs - 如何使用 Visual Studio 2017 在 ASPNET Core 中排除 wwwroot\lib
- reactjs - Codesandbox.io 中的 React-Testing-Library 问题
- selenium - 使用页面对象模式执行操作的多种方式
- javascript - Firestore如何添加到子集合
- azure-resource-manager - Azure 模板中的数组限制为 100 个条目?
- git - Windows 10 上的 git 存储库上的 pip 安装失败
- javascript - 使用 ReactDOM.render 并注入组件的反应不好的做法?
- ios - 推送导航控制器时视图控制器被遮挡