[英]How to add a string within a "for loop" that is specific to each iteration?
want to add the minutes that correlate with calories burned at the end of the string想要添加与字符串末尾燃烧的卡路里相关的分钟数
want it to say "You burned x calories on the treadmill in y minutes."希望它说“你在 y 分钟内在跑步机上燃烧了 x 卡路里。”
calories burned per minute = 4.2
for numbers in [10,15,20,25,30]: # in minutes
print('You burned', numbers * 4.2, 'calories on the treadmill. ')
if I understand your question correctly, you want to do something like this:如果我正确理解你的问题,你想做这样的事情:
numbers = [10,15,20,25,30] # This list could as well be a parameter in some function
for number in numbers:
print('You burned ' + str(number*4.2) + ' calories in ' + str(number) + ' minutes')
Anyway, there are various ways to format Strings in Python and that is not, in my opinion, the best.无论如何,在 Python 中有多种格式化字符串的方法,在我看来,这不是最好的。 So you could replace that line with:所以你可以用以下内容替换该行:
print(f'You burned {number*4.2} calories in {number} minutes')
or或者
print('You burned {} calories in {} minutes'.format(number*4.2, number))
or或者
print('You burned %.2f calories in %.2f minutes' % (number*4.2, number))
The f-format is only valid for Python 3.6+. f 格式仅对 Python 3.6+ 有效。 Check this for more information :).检查这个以获取更多信息:)。
You can loop through the range of 10 to 30 with the step of 5. Then using the new string format insert the necessary calculation and output.您可以使用步骤 5 循环遍历 10 到 30 的范围。然后使用新的字符串格式插入必要的计算和输出。
for i in range(10,31,5):
print(f'You burned {4.2*i} calories on the treadmill in {i} minutes.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.