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

大学编程入门课ATM代码运行异常求助:无语法错误但执行中断

ATM程序问题分析与修正

你的代码存在多个关键逻辑错误,导致程序无法正常执行,以下是具体问题和修复方案:

核心问题点

  • 变量误用+类型不匹配:判断PIN时错误使用内置函数名input而非你定义的pin_attempt变量,且input()返回字符串类型,而truepin是整数,两者直接比较永远不相等,会直接进入错误分支。
  • return语句滥用:函数执行return后会立即终止,你在输出选项列表前就写了return,导致后续的选项提示、功能分支代码完全不会执行。
  • 字符串与整数比较:用户输入的option是字符串类型,你直接和整数1、2、3比较,永远无法匹配,会进入错误分支。
  • 提前return导致代码不可达:比如option == 2分支里,先执行了return,后面的取款金额输入代码永远无法运行。
  • 未打印函数返回值:调用cashpoint(1234, 2350.25)但未用print()输出结果,即使函数有返回,控制台也看不到内容。

修正后的代码示例

def cashpoint(truepin, balance):
    pin_attempt = input('Please enter your PIN: ')
    # 转换输入为整数,处理非数字输入的异常
    try:
        pin_attempt = int(pin_attempt)
    except ValueError:
        return 'PIN must be a number, please try again'
    
    if pin_attempt == truepin:
        # 用print输出选项,而非return终止函数
        print("Pin correct, please choose one of the following options")
        print('1: Check balance')
        print('2: Withdraw cash and check balance')
        print('3: Mobile top up')
        
        option = input('Option selected: ')
        # 转换选项为整数
        try:
            option = int(option)
        except ValueError:
            return 'Incorrect input, please enter a number between 1-3'
        
        if option == 1:
            return f'Balance: {balance}'
        elif option == 2:
            withdrawal = float(input('Please enter the amount you wish to withdraw: '))
            # 增加余额校验逻辑
            if withdrawal <= balance:
                balance -= withdrawal
                return f'Withdrawal successful. New balance: {balance}'
            else:
                return 'Insufficient balance'
        elif option == 3:
            top_up_amount = float(input('Please input the amount you wish to top up: '))
            balance += top_up_amount
            return f'Top up successful. New balance: {balance}'
        else:
            return 'Incorrect option, please select one of the available options (1-3)'
    else:
        return 'PIN incorrect, please try again'

# 打印函数返回结果
print(cashpoint(1234, 2350.25))

额外优化说明

  • 增加try-except处理非数字输入,避免程序崩溃
  • 完善取款、充值的余额更新逻辑
  • 调整提示语清晰度,明确操作指引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:12:46