简体   繁体   中英

Traceback error when using loop

The below code is written in 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()

Whenever I run the file in the CMD Shell, it works fine, until I get to this part of the code:

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 doesn't return as 1 or 2, I get this error:

错误图片

I can't exactly figure out what is wrong with my code, and I don't understand any of the errors thrown by the CMD Shell. Does anyone know what I'm doing wrong?

The problem is here:

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

At this point, you set user_input to a number, and then later on you are trying to call that number with user_input() , its the same as doing this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM