我目前正在学习Python,并且正在创建具有保存功能的Python 3 Text RPG。文本保存在文本文件中,然后在关闭脚本并重新打开时将其导入回变量中。
我遇到的问题是我的“ If”调用无法识别chrClassNum实际上是某个数字,而实际上却是。例如,如果chrClassNum为1,则“ If”调用将无法识别为1,并且会跳过它。
我尝试修改脚本,在chrClassNum之前包含str()前缀。 我还尝试过修改脚本以删除语音标记,但无济于事。
def loadSave():
clear()
# Opening save file in read-only for transfer to the script
# Reading all the lines individually as each line is different data
f = open("save.txt","r")
lines = f.readlines()
chrName = (lines[1 - 1])
chrClassNum = (lines[2 - 1])
print (chrClassNum)
# Currently broken, does not recognize that chrClassNum is equal to any number
if (chrClassNum) == ("0"):
chrClass = ("Berserker")
elif (chrClassNum) == ("1"):
chrClass = ("Warrior")
elif (chrClassNum) == ("2"):
chrClass = ("Tank")
# Bug check, incase the user manages to break the program
else:
print("Somehow you got here. The script broke.")
time.sleep(100)
exit()
我希望输出的内容与打印出来的相同;
print (chrClassNum)
但是,输出结果是它直接下降到“ else”调用,他们应该无法访问。
答案 0 :(得分:0)
您的字符串中可能包含一些空格,请使用strip()
将其删除。而且无论如何,使用数字比较会更好,请尝试以下方法:
chrClassNum = int(lines[1].strip())
print(chrClassNum)
if chrClassNum == 0:
chrClass = "Berserker"
# etc.
我还删除了不必要的括号,并简化了索引计算。