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

Python编程:如何移除程序输出行末尾多余的最后一个字符

问题修复方案

问题根因

代码中内层输出前进F的循环触发counter >= S的break条件后,只会跳出当前的F输出循环,程序仍会继续执行后续输出后退B的内层循环,因此会在末尾多输出一个多余的B字符。

修复方案

在每段内层动作循环结束后,新增总步数是否达标的判断,达标就直接跳出外层的总步数循环,避免执行多余的输出逻辑。

修改后完整代码

# 输入Nick、Bill的前进后退步数,以及游戏结束所需总步数
A = int(input("How many steps did Nick take forwards: "))
B = int(input("How many steps did Nick take backwards: "))
C = int(input("How many steps did Bill take forwards: "))
D = int(input("How many steps did Bill take backwards: "))
S = int(input("How many steps were needed to finish the game: "))

# 计数器,记录两人的移动距离、总步数
counter = 0
counter2 = 0
paces = 0
paces2 = 0

# 计算Nick的步数字符串和最终距离
print("\nNick")
while(counter < S):
    F = 0
    while(F < A):
        print("F", end="")
        F = F + 1
        paces = paces + 1
        counter = counter + 1
        if counter >= S:
            break
    # 新增判断:总步数达标直接跳出外层循环,不执行后续后退逻辑
    if counter >= S:
        break
    b = 0
    while(b < B):
        print("B", end="")
        b = b + 1
        paces = paces - 1
        counter = counter + 1
        if counter >= S:
            break
    # 新增判断:后退时达标也直接跳出外层循环
    if counter >= S:
        break
print(" =",paces + 1 ,"paces from the start")     

# 计算Bill的步数字符串和最终距离
print("\nBill")
while(counter2 < S):
    F2 = 0
    while(F2 < C):
        print("F", end="")
        F2 = F2 + 1
        paces2 = paces2 + 1
        counter2 = counter2 + 1
        if counter2 >= S:
            break
    # 新增判断
    if counter2 >= S:
        break
    b2 = 0
    while(b2 < D):
        print("B", end="")
        b2 = b2 + 1
        paces2 = paces2 - 1
        counter2 = counter2 + 1
        if counter2 >= S:
            break
    # 新增判断
    if counter2 >= S:
        break
print(" =",paces2 + 1 ,"paces from the start") 

# 输出最终结果
if paces > paces2:
    print("\nNick is Ahead after",S,"steps")
elif paces < paces2:
    print("\nBill is Ahead after",S,"steps")
else:
    print("\nBill and Nick are Tied after",S,"steps")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:45:03