尝试执行代码后,Python中出现未知错误

问题描述

我正在尝试使用v3.8创建一个简单的Python脚本来执行以下操作:

  1. 创建2个单独的列表
  2. 列表是否根据用户输入而增长(不输入整数就退出
  3. 垂直并排显示列表

我个人都有所有的项目。当我添加for块之后的try循环时,脚本将关闭。如果将for循环放在我的try块之前,它可以正常工作,这表明它来自我的try块。但是,无论我尝试搜索答案多少次并尝试其他方法,我都无法弄清楚。

代码

nameList = []
countList = []

try:

    while True:
        nameList.append(str(input("Enter Name: ")))
        countList.append(int(input("Enter Count: ")))

except Exception:
    pass
        
print("Name" '\t' "Count")
for o in range(len(nameList)):
    print(nameList[o] + '\t ' + countList[o])

sleep(2)

解决方法

有两个问题:

  1. nameList[o] + '\t ' + countList[o]行无效,因为您试图在字符串后加上数字。请改用nameList[o] + '\t ' + str(countList[o])
  2. 当while循环中出现异常时,列表长度不一样

下面的方法会起作用,但是写这样的代码绝对不是最佳实践

nameList = []
countList = []

try:

    while True:
        nameList.append(str(input("Enter Name: ")))
        countList.append(int(input("Enter Count: ")))

except Exception:
    pass
        

print("Name" '\t' "Count")
for o in range(len(countList)):
    print(nameList[o] + '\t ' + str(countList[o]))
,

如果您不想打扰转换,请让格式使用字符串中的占位符为您处理

print('{}\t {}'.format(nameList[o],countList[o]))
,

您只能在最后一个打印语句中串联str(MaskFormatter mf = new MaskFormatter("(0###) ### - ## - ##"); // format JFormattedTextField formattedTextField = new JFormattedTextField(mf); 是int类型)。