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

Python选择输入循环与文件读取功能调试求助

Python计算器程序问题修复

需求

  • 通过输入选择,使用计算器功能或打开存储计算记录的文件
  • 针对文件不存在的情况做防御性处理,提示用户重新输入文件名

遇到的问题

  • 首次输入的process_choice无法进入对应选项
  • 执行文件读取操作时触发FileNotFoundError

原问题代码

from pathlib import Path

file = open('calculatortextfile.txt' , 'a')

process_choice = str(input("Enter 'C' to use calculator or 'F' to open file: ")).upper

#CALCULATOR OPTION
while True:
        
    if process_choice == "C": 

       
            try:
                num1 = float(input("Please enter a number:"))
                num2 = float(input("Please enter another number: "))

                operator = input("Please enter the operator (+, -, *, /): ")   


                if operator == "+":
                    calculation = num1 + num2
                    entry = ("{} + {} = {}".format(num1,num2,calculation))  
                    print(entry) 

                elif operator == "-":
                    calculation = num1 - num2
                    entry = ("{} - {} = {}".format(num1,num2,calculation)) 
                    print(entry)

                elif operator == "*":
                    calculation = num1 * num2
                    entry = ("{} * {} = {}".format(num1,num2, calculation)) 
                    print(entry)   

                elif operator == "/":
                    calculation = num1 / num2
                    entry = ("{} / {} = {}".format(num1, num2, calculation))
                    print(entry)

                else:   
                    print("You have not entered a valid operator, please try again.")
                    continue

                file.write(str(num1) + " " + operator + " " + str(num2) + " = " + str(calculation)+"\n") 

                choice = input("To continue enter - yes or no: ") 
                if choice == "no":
                    print("See you next time!")
                    break

            except ValueError:
                print("Wrong key entered. Please key in a number")

            except ZeroDivisionError:
                print("You cannot divide by zero. Please try again!") 

        # OPEN FILE TO READ OPTION 
    elif process_choice == "F":

        file_name = input("Please enter the name of the file: ").lower
        path = Path("calculatortextfile.txt")
        contents = path.read_text()   
        print(contents)

        if file_name == "calculatorfiletext.txt":
            print("The file exists")
            with open(file_name, 'r') as f:
                    
                    lines = f.readlines()
                    print(lines)

        else:
            raise FileNotFoundError('No such file or directory')
        print("This file does not exist")

    file.close()

问题分析与修复要点

  1. 方法调用缺失括号:

    • process_choice = ... .upper 改为 process_choice = ... .upper(),否则变量存储的是方法对象而非字符串,无法匹配"C"/"F"
    • file_name = ... .lower 改为 file_name = ... .lower(),同理
  2. 文件操作逻辑错误:

    • 移除一开始直接打开文件的代码,改用with语句管理文件读写,避免文件未正确关闭的问题
    • 文件读取部分添加try-except捕获FileNotFoundError,循环提示用户输入正确的文件名,直到找到存在的文件
    • 修正文件名判断的拼写错误:原文件名为calculatortextfile.txt,原代码误写为calculatorfiletext.txt
    • 移除主动抛出FileNotFoundError的代码,改为友好提示并重新输入
  3. 循环逻辑调整:将选择操作的逻辑放在循环内,确保用户输入无效选项时可以重新选择,同时拆分计算器和文件读取为独立函数,提升代码可读性

修正后代码

from pathlib import Path

def calculator():
    # 使用with语句管理文件写入,自动关闭文件
    with open('calculatortextfile.txt', 'a') as file:
        while True:
            try:
                num1 = float(input("请输入第一个数字: "))
                num2 = float(input("请输入第二个数字: "))
                operator = input("请输入运算符(+, -, *, /): ")

                if operator == "+":
                    calculation = num1 + num2
                elif operator == "-":
                    calculation = num1 - num2
                elif operator == "*":
                    calculation = num1 * num2
                elif operator == "/":
                    if num2 == 0:
                        print("不能除以0,请重新输入!")
                        continue
                    calculation = num1 / num2
                else:
                    print("无效的运算符,请重新输入!")
                    continue

                entry = f"{num1} {operator} {num2} = {calculation}"
                print(entry)
                file.write(f"{entry}\n")

                choice = input("继续计算请输入yes,退出请输入no: ").lower()
                if choice == "no":
                    print("下次再见!")
                    break
            except ValueError:
                print("输入错误,请输入数字!")

def open_calculation_file():
    while True:
        file_name = input("请输入要打开的文件名: ").strip()
        path = Path(file_name)
        try:
            contents = path.read_text()
            print("计算记录:\n")
            print(contents)
            break
        except FileNotFoundError:
            print(f"文件 {file_name} 不存在,请重新输入!")

# 主逻辑
while True:
    process_choice = input("输入'C'使用计算器,输入'F'打开计算记录文件: ").strip().upper()
    if process_choice == "C":
        calculator()
        break
    elif process_choice == "F":
        open_calculation_file()
        break
    else:
        print("无效选择,请输入'C'或'F'!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:54:58