Python 同线打印指定步长整数序列并以换行结尾的问题求解
问题原因
- 当第二个整数大于等于第一个时,你在循环中使用
print(i, end=' ')输出每个数字,将print默认的结尾换行符替换成了空格,所有数字输出完成后没有额外输出换行符,导致最终输出末尾缺少换行。 - 不符合输入条件的分支使用的是默认参数的print,本身自带换行,符合要求不需要修改。
修改方案
方案1:最小改动,循环结束后补换行
只需要在for循环结束后新增一行空print输出换行即可,不需要改动原有逻辑:
x = int(input()) y = int(input()) if y >= x: for i in range(x, y+1, 5): print(i, end=' ') print() # 新增行,输出末尾换行 else: print('Second integer can\'t be less than the first.')
方案2:优化写法,避免末尾多余空格
如果需要同时解决当前代码输出末尾多一个空格的潜在问题,可以将所有待输出数字转为字符串拼接后一次性打印,print默认会在结尾加换行:
x = int(input()) y = int(input()) if y >= x: output_list = [str(num) for num in range(x, y+1, 5)] print(' '.join(output_list)) else: print('Second integer can\'t be less than the first.')
内容的提问来源于stack exchange,提问作者shanooonooo
相关产品推荐
相关产品推荐

