ab=21sum=0for i in range121sum+=abprintt 2fformatsum
This code has a couple of syntax errors:
- There is no variable named
bdefined, soa/bwill raise aNameError. - The
range()function takes an integer argument, but1.21is a float, so this will raise aTypeError. - The
print()function is missing the value to be printed.
Here's a corrected version of the code:
a = 2.1
b = 1
sum = 0
for i in range(1, 21):
sum += a/b
print("sum: {:.2f}".format(sum))
This should output:
sum: 42.00
Explanation:
- We set
bto 1 so thata/bis equal toa. - We use
range(1, 21)to loop from 1 to 20 inclusive (i.e. 20 iterations). - We use
:.2finside theformat()method to format thesumvariable as a floating-point number with 2 decimal places.
原文地址: http://www.cveoy.top/t/topic/Lhr 著作权归作者所有。请勿转载和采集!