Search code examples
pythonfor-loopwhile-loopfractions

Python loop for :1/30 + 2/29 + 3/28


Hello everyone I have a noob question.

how do I set up the following code to print:

1/30 + 2/29 + 3/28..........30/1

The numerator is increasing \ denominator decreasing

I have the following:

for i in range(1,31):
    v = i
for j in range(30,0,-1):
    t = j
    print(v/t)

but prints

1.0
1.0344827586206897
1.0714285714285714
1.1111111111111112
1.15384615384.........

how do I get 1/30 + 2/29 + 3/28.....

Thank you for your help and guidance.


Solution

  • I presume you want the strings instead of the numerical values, correct?

    s = ''
    for j in range(30, 0, -1):
        s += "{}/{} + ".format(31-j, j)
    print s[:-2]
    

    Read this documentation to get a grasp of it. Essentially, it's formatting the string, using the two pairs of curly braces as placeholders, and passing in the value 31-j in the first slot, and j in the second.

    Surely there is a more elegant way to do it, but this is the quick and dirty method.