简体   繁体   中英

When I print my code I don't want “..” to print yet

Is there a way that I still get the ".." further in the code, but don't have ".." till after "1+"

eg. n = 2 *my code at the moment will output

..1+..1+2+..

*i want my code to output

1+..1+2+..

def nested_increasing_additions(n):
    ans = ""
    n = n + 1
    for i in range(1,(n+1)):
        for k in range(1,i):
            ans = ans + str(k) + "+"

        ans = ans + ".."

    return ans 
print(nested_increasing_additions(1))

You can add the .. only if ans is not empty:

def nested_increasing_additions(n):
    ans = ""
    n = n + 1
    for i in range(1,(n+1)):
        for k in range(1,i):
            ans = ans + str(k) + "+"

        if ans:
            ans = ans + ".."

    return ans 
print(nested_increasing_additions(1))

i think you want it as below, i tested your code from the post it print

..1+..

def nested_increasing_additions(n):
    ans = ""
    for i in range(1,(n+2)):
        for k in range(1,i+1):
            ans = ans + str(k) + "+"    
        ans = ans + ".."
    return ans 

print(nested_increasing_additions(1))
# 1+..1+2+..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM