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

Time:12-04

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
'''

CodePudding user response:

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

CodePudding user response:

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))

CodePudding user response:

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)) 

CodePudding user response:

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
  • Related