[英]Python print each iteration of a while loop
I've created a summation function that takes in a start number and an end number and returns a summed answer between those two points我创建了一个总和 function ,它接受一个起始编号和一个结束编号,并返回这两点之间的总和答案
def print_sum_equations(start_number,end_number):
mySum = 0
num = start_number
while num <= end_number:
mySum += num
num += 1
print (mySum)
print_sum_equations(3,5)
It returns 12 which is correct, however, I want my output to look like the following它返回 12 这是正确的,但是,我希望我的 output 看起来像下面
3 + 4 + 5 = 12
rather than just returning the answer.而不仅仅是返回答案。 Im still new to python and learning how to iterate while loops so any help is appreciated我对 python 仍然很陌生,并且正在学习如何迭代 while 循环,因此不胜感激
def print_sum_equations(start_number,end_number):
vals = [i for i in range(start_number,end_number+1)]
s = sum(vals)
for ind,i in enumerate(vals):
print(f'{i}',end='')
if ind != end_number-start_number:
print(' + ',end='')
else:
print(f' = {s}')
print_sum_equations(3,5)
Use the join
method to get the series from a list of values.使用join
方法从值列表中获取系列。
val_list = list(range(start_number, end_number+1))
lhs = ' + '.join(val_list)
print ( lhs + ' = ' + str(sum(val_list)) )
You could also use a list comprehension to get val_list:您还可以使用列表推导来获取 val_list:
val_list = [ n for n in range(start_number, end_number+1) ]
... but list(range(...
is more direct. ...但是list(range(...
更直接。
Pretty new to programming in python, my solution, is pretty simple and easy to read.我的解决方案 python 中的编程非常新,非常简单易读。
def print_sum_equations(start_number,end_number):
mySum = 0
num = start_number
num_list = []
num_list.append(num)
while num <= end_number:
mySum += num
num += 1
num_list.append(num)
print (mySum)
num_list.pop()
print(*num_list, sep="+",end="")
print("="+str(mySum))
print_sum_equations(2,5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.