簡體   English   中英

使用循環時的回溯錯誤

[英]Traceback error when using loop

下面的代碼是用python編寫的。

import subprocess as sp

def user_input():
    sp.call('cls',shell=True)
    print('[1]: ASCII to Binary')
    print('[2]: Binary to ASCII')
    valid_answer()

def valid_answer():
    while True:
        try:
            user_input = int(input('Please type 1 or 2: '))
            sp.call('cls',shell=True)
            break
        except ValueError:
            print('Please enter a valid input...')
            sp.call('pause',shell=True)
            user_input()

    while True:
        if user_input < 0:
            print('Input must be 1 or 2.')
            sp.call('pause',shell=True)
            user_input()
        elif user_input > 2:
            print('Input must be 1 or 2.')
            sp.call('pause',shell=True)
            user_input()
        else:
            break
    if user_input == (1):
        print('Good.')
        exit
    elif user_input == (2):
        print('Good.')
        exit

user_input()

每當我在CMD Shell中運行該文件時,它都可以正常工作,直到獲得代碼的這一部分:

while True:
    if user_input < 0:
        print('Input must be 1 or 2.')
        sp.call('pause',shell=True)
        user_input()
    elif user_input > 2:
        print('Input must be 1 or 2.')
        sp.call('pause',shell=True)
        user_input()
    else:
        break

如果user_input不返回1或2,則會出現此錯誤:

錯誤圖片

我無法確切地弄清楚我的代碼出了什么問題,而且我也不了解CMD Shell拋出的任何錯誤。 有人知道我在做什么錯嗎?

問題在這里:

user_input = int(input('Please type 1 or 2: '))

此時,您將user_input設置為一個數字,然后稍后嘗試使用user_input()調用該數字,其方法與此相同:

>>> user_input = 1
>>> user_input()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM