Search code examples
pythonstring.format

Having trouble formatting code to desired output


I'm trying to get the code to print in the below format, however nothing seems to work out. Can someone point out the mistake in the code or logic?

Desired format: We have got only 3 oranges and only 1 apple

Code:

excess = {"apple": 5, "orange": 6}
s = ""
for k, v in excess.items():
    n = 1
    if n == 0:
        s = "We have got only {} {} ".format(v, k)
    elif n > 1:
        s += "and {} {}".format(v, k)  
    n += 1
print(bill, s)

Output

We have only 6 orange

Solution

  • You need to define n outside of the loop, and replace n>1 condition with n>0 (or else)

    excess={"apple":5,"orange":6}
    s=""
    n=0
    
    for k,v in excess.items():
        if n==0:
            s="We have got only {} {}".format(v,k)
        else:
            s+=" and {} {}".format(v,k)  
        n+=1
        
    print(s)
    # We have got only 5 apple and 6 orange