printing output values together with some multiplication parameter

Question:

I tried write a code that the given numbers multiply by ten for each input, and then sum all of those values. If their summation is bigger than 100 it will stop. Furthermore I want to print the output as "Program ends because 10*3+10*1+10*8 = 120, which is not less than 100" while the input parameters are 3,1,8 accordingly.

The code is works fine but the i couldnt figure out how to print as i mentioned before.
Thanks

`

l=[]
k=[]

while True:
    n = int(input("Enter Number to calculate: "))
    p=n*10
    l.append(p)
    k.append(n)
    s= sum(l)
    h = "10*"
    if s>=100:
        for i in range(len(k)) :
             print("Program ends because"+"{}".format(h)+k[i])
        break

`

Asked By: Doğa Selçuk

||

Answers:

You can construct the end message, then print it, like this:

l=[]
k=[]

while True:
    n = int(input("Enter Number to calculate: "))
    p=n*10
    l.append(p)
    k.append(n)
    s= sum(l)
    h = "10*"
    if s>=100:
        message = "Program ends because "
        for i in range(len(k)) :
            message += h + str(k[i]) + '+'*(i != len(k)-1)
        message += ' = ' + str(s) + " , which is not less than 100."
        print(message)
        break

# Program ends because 10*4+10*5+10*8 = 170 , which is not less than 100.

A more efficient way to deal with the ending (the message is built in one instruction, and the join method removes the need to deal with the final "+"):

if s>=100:
    print("Program ends because " + '+'.join([ h + str(i) for i in k]) + ' = ' + str(s) + " , which is not less than 100.")
    break
Answered By: Swifty
l=[]
k=[]
txt = "Program ends because "

while True:
    n = int(input("Enter Number to calculate: "))
    p=n*10
    l.append(p)
    k.append(n)
    s= sum(l)
    h = "10*"
    if s>=100:
        for i in range(len(k)) :
            if i == 0 :

                txt += h+str(k[i])

            else :

                txt += "+"+h+str(k[i])
        break

print(txt)

If you want try this codes. I made a new variable and I added entered number and sentence in it. In for loop if index == 0 I didn’t add plus but if index != 0 I added plus to beginning.

Answered By: Blacknight
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.