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

Python计算器异常问题咨询:输入第二个数后仍重复请求输入

解决Python计算器重复要求输入第二个数字的问题

你的计算器持续要求输入第二个数字,核心问题出在原代码的qwe()函数逻辑上:

def qwe():
    try:
        global y
        y = int(input("enter second number: "))
    except ValueError:
        print("you don't enter correct")
    qwe()  # 无论输入是否合法,都会再次调用自身,导致无限循环

这段代码中,不管输入是否成功转换为整数,最后都会无条件递归调用qwe(),因此即使输入了正确数字,程序也会陷入无限循环,持续要求输入第二个数字。

修复后的完整代码

print("Python Basic Calculator Version 1.12")

print('''
type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
** for power
% for modulo
''')

def main():
    def get_first_num():
        try:
            return int(input("enter first number: "))
        except ValueError:
            print("you don't enter correct")
            return get_first_num()
    
    x = get_first_num()        

    def get_operation():
        ops = ["+","-","*","/","**","%"]
        o = input("type the operation: ")  # 修正拼写错误 opreation -> operation
        if o in ops:
            return o
        else:
            print("you don't enter correct")
            return get_operation()
    
    o = get_operation()

    def get_second_num():
        try:
            return int(input("enter second number: "))
        except ValueError:
            print("you don't enter correct")
            return get_second_num()
    
    y = get_second_num()        

    # 用elif替代多个独立if,提升执行效率
    if o == "+": 
        z = x + y
        print(z)
    elif o == "-":  
        z = x - y
        print(z)
    elif o == "*":
        z = x * y
        print(z)
    elif o == "/":
        z = x / y
        print(z)
    elif o == "**":
        z = x ** y
        print(z)
    elif o == "%":
        z = x % y
        print(z)

main()

主要修改点

  • 修复输入数字函数的递归逻辑:仅当输入不合法时才递归调用,输入成功则返回数字并终止递归
  • 移除全局变量,改用函数返回值传递数据,代码逻辑更清晰
  • 修正拼写错误opreation为operation
  • 用elif替代多个独立if,减少不必要的条件判断
  • 给嵌套函数起更具语义的名称,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:45:33