Python 使用循环时出现回溯错误
下面的代码是用python编写的Python 使用循环时出现回溯错误,python,cmd,Python,Cmd,下面的代码是用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
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()
将子流程作为sp导入
def user_input():
sp.call('cls',shell=True)
打印('[1]:ASCII到二进制')
打印('[2]:二进制到ASCII')
有效答案()
def valid_answer():
尽管如此:
尝试:
用户输入=int(输入('请键入1或2:'))
sp.call('cls',shell=True)
打破
除值错误外:
打印('请输入有效的输入…')
sp.call('pause',shell=True)
用户输入()
尽管如此:
如果用户输入<0:
打印('输入必须为1或2')
sp.call('pause',shell=True)
用户输入()
elif用户输入>2:
打印('输入必须为1或2')
sp.call('pause',shell=True)
用户输入()
其他:
打破
如果用户输入==(1):
打印(“好”)
出口
elif用户输入==(2):
打印(“好”)
出口
用户输入()
每当我在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
为True时:
如果用户输入<0:
打印('输入必须为1或2')
sp.call('pause',shell=True)
用户输入()
elif用户输入>2:
打印('输入必须为1或2')
sp.call('pause',shell=True)
用户输入()
其他:
打破
如果用户_输入未返回为1或2,则会出现以下错误:
我不能确切地找出我的代码有什么问题,我也不理解cmdshell抛出的任何错误。有人知道我做错了什么吗?问题在于:
user_input = int(input('Please type 1 or 2: '))
此时,您将user\u input
设置为一个数字,然后您尝试使用user\u input()
调用该数字,这与执行此操作相同:
>>> user_input = 1
>>> user_input()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>用户输入=1
>>>用户输入()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“int”对象不可调用
所以,我需要做的是将def user\u input():
更改为user\u input
以外的内容,或者更改变量?是的,我的建议是更改变量;当你使用它时,如果user\u input==(1):
你不需要()
围绕1
@jornsharpe值错误将解决这个问题。现在我解决了这个问题,现在发生的是我只需返回user\u input()
而不是关闭shell。