从文本fi导入后,“If”函数无法识别变量的值

2024-09-30 06:14:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在学习Python,我正在创建一个python3文本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”调用,他们应该无法访问该调用。你知道吗


Tags: theto文本脚本ifissavescript
1条回答
网友
1楼 · 发布于 2024-09-30 06:14:56

字符串中可能有一些空白,请用strip()将其删除。无论如何,最好使用数字比较,试试这个:

chrClassNum = int(lines[1].strip())
print(chrClassNum)
if chrClassNum == 0:
    chrClass = "Berserker"
# etc.

我还删除了不必要的括号,简化了索引计算。你知道吗

相关问题 更多 >

    热门问题