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

Python循环中为唯一ID添加校验位并存储的问题求助(含报错)

Fixing the 'int' object is not subscriptable Error & Implementing ID Check Digits

Hey there! Let's break down what's going wrong and fix your code step by step.

The Root Cause of the Error

Your Unique variable is an integer (like 101, 102), and you're trying to access its digits using subscript notation (Unique[0])—but integers don't support that! That's exactly why you're getting the 'int' object is not subscriptable error. To get individual digits, you first need to convert the integer to a string.

Corrected Code with Explanations

Here's the fixed version of your code, with comments explaining each key change:

Staff = []
ID = []
Unique = 100  # Starting base ID number

# Change range(0,3) to range(0,10) if you want 10 names instead of 3
for _ in range(0, 3):
    Name = input("Enter your name:\n")
    Staff.append(Name)
    Unique += 1  # Increment to get the next unique ID
    
    # Convert integer ID to string to access individual digits
    unique_str = str(Unique)
    
    # Extract each digit, convert back to int for calculation
    p1 = int(unique_str[0])
    p2 = int(unique_str[1])
    p3 = int(unique_str[2])
    
    # Calculate the check digit using your weighted sum + MOD 10 logic
    check_digit = ((p1 * 3) + (p2 * 2) + (p3 * 1)) % 10
    
    # Create a full ID (either as a concatenated string or keep as a tuple)
    # Option 1: Concatenated string (more user-friendly for display)
    full_id = f"{Unique}{check_digit}"
    # Option 2: Keep as tuple (matches your original code's structure)
    # full_id = (Unique, check_digit)
    
    ID.append(full_id)

# Print results neatly
for name, staff_id in zip(Staff, ID):
    print(f"Name: {name}, Full ID: {staff_id}")

Key Changes Made

  • Converted Unique to string: This lets us safely access each digit with subscripts (e.g., unique_str[0] gets the first digit of the ID).
  • Adjusted check digit calculation: We convert each extracted string digit back to an integer so we can do arithmetic operations on them.
  • Improved output formatting: Used zip() to loop through names and IDs together, making the code cleaner than using index-based loops.
  • Optional ID format: You can choose between a concatenated string (like 1013) or keep the tuple format ((101, 3)) based on your needs.

Testing the Code

When you run this, you'll be prompted to enter 3 names (change to 10 by updating the range value). For example, if you enter "Alice" as the first name:

  • Unique becomes 101
  • Digits are 1, 0, 1
  • Weighted sum: (13)+(02)+(1*1) = 4
  • Check digit: 4 % 10 = 4
  • Full ID becomes 1014

内容的提问来源于stack exchange,提问作者Mr mac

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:00:35