Python嵌套循环实现剧院座位标签的代码调试求助
剧院座位标签生成问题解决方案
问题需求
给定num_rows(行数)和num_cols(列数),生成剧院座位标签,格式要求:
- 每个座位标签后加空格
- 每行座位输出结束后换行
- 需使用外层for循环、初始化
curr_col_let为起始字母并定义内层for循环
现有代码存在锁定行(第1、2、8、9、10行不可修改),当前输出不符合预期,需实现列循环完成后递增行号并重置列字母,仅允许在第2行到第一个print语句之间添加新代码。
锁定代码示例
num_rows = int(input()) #line locked and can not be altered. num_cols = int(input()) #line locked and can not be altered. curr_row = 1 curr_col_let = 'A' for row in range(num_rows): for col in range(num_cols): print (f'{curr_row}{curr_col_let}', end=' ') #line locked and can not be altered. curr_col_let = chr(ord(curr_col_let) + 1) #line locked and can not be altered. print() #line locked and can not be altered.
问题分析
当前代码的缺陷:
curr_row仅初始化一次,列循环结束后未递增,导致所有行都使用同一行号curr_col_let在列循环后未重置为'A',后续行的列字母会延续上一行的末尾字母继续递增,不符合座位标签的常规格式(每行列字母从A开始)
修改后的代码
num_rows = int(input()) #line locked and can not be altered. num_cols = int(input()) #line locked and can not be altered. curr_row = 1 curr_col_let = 'A' for row in range(num_rows): for col in range(num_cols): print (f'{curr_row}{curr_col_let}', end=' ') #line locked and can not be altered. curr_col_let = chr(ord(curr_col_let) + 1) #line locked and can not be altered. # 添加的核心代码 curr_row += 1 curr_col_let = 'A' print() #line locked and can not be altered.
说明
在外层循环的内层循环结束后、换行打印前,添加两行代码:
curr_row += 1:完成一行座位输出后,行号递增curr_col_let = 'A':重置列字母为起始字母,确保下一行的列标签从A开始
内容的提问来源于stack exchange,提问作者Whyte_Out
相关产品推荐
相关产品推荐

