You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

while循环内嵌if语句异常:输入View时代码重复执行求助

问题分析与修复方案

核心问题

你的代码存在两个关键问题,导致View功能异常:

  1. View分支无法读取文件内容
    调用narrate.readlines()会一次性读取所有行并将文件指针移到末尾,后续的for row in narrate就没有内容可以遍历了,所以看不到任何输出。

  2. 条件判断逻辑彻底错误
    第三个if的条件action != 'add' or 'view'在Python中永远为True——因为非空字符串'view'会被视为布尔值True,or运算只要有一个为真结果就为真。这意味着不管你输入add还是view,都会触发break退出循环,和你描述的“输入Add时正常”矛盾,但这个逻辑确实是错误的。

修复后的代码

master_pass = input('Lost in Soul Sand be everything, but the KEY! ')

while master_pass == 'Soul':
    action = input('Add/View Soul?').lower()

    if action == 'add':
        U = input('Soulname: ')
        P = input('Soul Sand: ')
        with open('sandvalley.txt','a') as f:
            f.write(f"{U}|{P}\n")
            print('Souls saw the light')

    elif action == 'view':
        with open('sandvalley.txt','r') as narrate:
            # 直接遍历文件对象,自动逐行读取,无需提前调用readlines()
            for row in narrate:
                print(row.strip())  # 去除换行符,避免多余空行

    else:
        print('Soul has left the storm')
        break

print ('End')

修复说明

  • 移除了未使用的import string模块。
  • 改用if-elif-else结构,避免重复判断,逻辑更清晰。
  • 删除View分支中多余的readlines()调用,直接遍历文件对象即可逐行读取内容。
  • 用f-string格式化写入内容,比字符串拼接更简洁。
  • 打印时用strip()去掉换行符,优化输出格式。
  • 用else处理非add/view的输入,条件判断准确无误。

内容的提问来源于stack exchange,提问作者Mykl_007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:01:24