HotOnion24
HotOnion24

Reputation: 21

How to extract values from a while loop to print in python?

So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.

I couldn't figure out how to extract the values from the while loop as with my method it only gives the latest odd number which is 7 while 1,3 and 5 could not be taken out

num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
    odd = (str(oddNum))
    print (odd)
    total = total + oddNum
    oddNum = oddNum + 2
    count += 1

print (odd + "=" + str(total)) 
#output will be:
'''
1
3
5
7
7=16
but it should look like 1+3+5+7=16
'''

Upvotes: 1

Views: 473

Answers (4)

Arifa Chan
Arifa Chan

Reputation: 1017

Alternatively using walrus (:=), range,print, sep, and end:

print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))

# Insert a postive integer:4
# 1+3+5+7=16

Upvotes: 1

ScottC
ScottC

Reputation: 4105

An alternative method would be the use of:

  • range() method to generate the list of odd numbers
  • .join() method to stitch the odd numbers together (eg. 1+3+5+7)
  • f-strings to print odds together with the total = sum(odd_nums)

Code:

num = int(input("Insert a postive integer:")) #4
odd_nums = range(1, num * 2, 2)
sum_nums = "+".join(map(str, odd_nums))
print(f"{sum_nums}={sum(odd_nums)}")

Output:

1+3+5+7=16



Note:

Same but using two lines of code:

num = int(input("Insert a postive integer:")) #4
 
print(f"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}")
Output:
1+3+5+7=16

Upvotes: 2

phoenixinwater
phoenixinwater

Reputation: 340

There are a few options, you can either create a string during the loop and print that at the end, or create a list and transform that into a string at the end, or python3 has the ability to modify the default end of line with print(oddNum, end='').

Using a string:

num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
sequence = ''
while count <= num:
    sequence += ("+" if sequence != "" else "") + str(oddNum)
    total = total + oddNum
    oddNum = oddNum + 2
    count += 1

print (sequence + "=" + str(total))

Using print:

num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
    if count != 1:
        print('+', end='')
    print (oddNum, end='')
    total = total + oddNum
    oddNum = oddNum + 2
    count += 1

print ("=" + str(total)) 

Upvotes: 1

Soumendra
Soumendra

Reputation: 1624

You are not storing old oddNum values in odd. With minimal changes can be fixed like this:

num = int(input("Insert a positive integer:"))
oddNum = 1
total = 0
count = 1
odd = ""
while count <= num:
    total = total + oddNum
    odd += f"{oddNum}"
    oddNum = oddNum + 2
    count += 1
odd = "+".join(odd)
print(odd + "=" + str(total))

Upvotes: 1

Related Questions