Python彩票系统开发遇TypeError:'int'对象不可迭代问题求助
问题解决:TypeError: 'int' object is not iterable
错误原因
ticket_sum_inquiry是用户输入的整数(比如输入3就直接是数值3),但zip()函数要求传入的参数必须是可迭代对象(比如列表、range序列等)。把整数直接传给zip时,Python会报错,因为整数无法被遍历拆分。
修复步骤
- 修正zip的迭代对象:把
ticket_sum_inquiry替换成range(1, ticket_sum_inquiry + 1),这样就能生成对应票数的序号(比如输入3就生成1、2、3),和ticket_num里的号码一一配对。 - 修复号码生成逻辑:
- 没必要自定义
randint函数,直接用内置的random.randint()即可,避免函数名重名混淆。 - 原代码只生成了一个空列表添加到
ticket_num,需要根据用户输入的票数,循环生成对应数量的彩票号码。
- 没必要自定义
- 完善分支逻辑:补充原代码中空缺的else分支提示。
修改后的完整代码
import random # 初始化核心变量 ticket_cost = 10 ticket_num = [] # 获取用户输入的票数 ticket_sum_inquiry = int(input("Enter number of tickets: ")) print(ticket_sum_inquiry) print(f"It will cost {ticket_sum_inquiry * ticket_cost} dollars for these tickets.") # 根据票数生成对应数量的随机号码 for _ in range(ticket_sum_inquiry): # 生成1-100范围内的随机数作为彩票号码 random_num = random.randint(1, 100) ticket_num.append(random_num) # 确认用户是否需要查看彩票 proceed = input('Would you like to continue? enter "y" for yes, enter "n" no: ').lower() if proceed == "y": print("Great, here are your tickets with their numbers:") # 遍历票序号和对应号码 for ticket_id, number in zip(range(1, ticket_sum_inquiry + 1), ticket_num): print(f"Ticket {ticket_id}: {number}") elif proceed == "n": print("Goodbye") else: print("Invalid input, please enter 'y' or 'n'")
额外优化说明
- 将
random模块导入放在代码开头,符合Python编码惯例。 - 使用f-string简化输出格式,让代码更易读。
- 变量名改用小写加下划线的规范命名(如
proceed代替Proceed),贴合Python风格。 - 移除了无用的冗余变量(
failed、passed等),精简代码结构。
内容的提问来源于stack exchange,提问作者Liv.K
相关产品推荐
相关产品推荐

