Python 3.x 在Python中停止For循环

Python 3.x 在Python中停止For循环,python-3.x,for-loop,Python 3.x,For Loop,我想做的是去掉用户输入的结束值后面的+号 count = 0 total = 0 # Input start = int(float(input("1 of 2 - Enter Starting Loop Value: "))) ending = int(float(input("2 of 2 - Enter Ending Loop Value: "))) # for loop for n in range(start, ending+1, 1): total = total + n

我想做的是去掉用户输入的结束值后面的+号

count = 0
total = 0

# Input
start = int(float(input("1 of 2 - Enter Starting Loop Value: ")))
ending = int(float(input("2 of 2 - Enter Ending Loop Value: ")))

# for loop
for n in range(start, ending+1, 1):
  total = total + n
  count = count + 1
  print(n, "+ ", end="")
print("=", total)

print("\nLoop ran", count, "Times")

print("\n\n")
输出看起来像

1 of 2 - Enter Starting Loop Value: 5
2 of 2 - Enter Ending Loop Value: 11
5 + 6 + 7 + 8 + 9 + 10 + 11 + = 56

Loop ran 7 Times

因此,我想去掉11之后的+号。

您可以检查以确保只有在不是最后一个要打印的数字时才打印,如下所示

for n in range(start, ending+1, 1):
  total = total + n
  count = count + 1
  if n != ending:
      print(n, "+ ", end="")
  else:
      print(n + " ")
使用
加入

nums = list(range(start,ending+1))
total = sum(nums)
strsum = ' + '.join(str(i) for i in nums)
print('{} = {}'.format(strsum,total))