简体   繁体   中英

Program to add the squares of numbers in list which have been entered by while-loop

I'm writing a program which should produce an output of something like this:

`Enter an integer (or Q to quit): 1
Enter an integer (or Q to quit): 2
Enter an integer (or Q to quit): 3
Enter an integer (or Q to quit): Q
(1 x 1) + (2 x 2) + (3 x 3) = 14`

So far, I've gotten the display of the equation right, but I can't seem to figure out how to actually get the total of the equation. Currently, the total displays 18 instead of the expected 14 .

Here's my code so far:

`int_list = [] # initiate list 

while True:
  user_input = input("Enter an integer (or Q to quit): ") # get user input
  if user_input == "Q": # break loop if user enters Q
    break
  integer = int(user_input) # convert user_input to an integer to add to list
  int_list.append(integer) # add the integers entered to the list

for i in range(0, len(int_list)):
  template = ("({0} x {1})".format(int_list[i], int_list[i]))
  if i == len(int_list)-1:
    trailing = " = "
  else:
    trailing = " + "
  print(template, end="")
  print(trailing, end="")

for i in range(0, len(int_list)):
  x = (int_list[i]*int_list[i])

add = (x+x)
print(add)`

Any help would be greatly appreciated:))

You duplicate only the last product (2 x 3 x 3 = 18).
Because you reassign x in your loop ( x = (int_list[i]*int_list[i]) ) and than duplicate x with add = (x+x) .

But you have to build the sum.

int_list = []  # initiate list

while True:
    user_input = input("Enter an integer (or Q to quit): ")  # get user input
    if user_input == "Q":  # break loop if user enters Q
        break
    integer = int(user_input)  # convert user_input to an integer to add to list
    int_list.append(integer)  # add the integers entered to the list

for i in range(0, len(int_list)):
    template = ("({0} x {1})".format(int_list[i], int_list[i]))
    if i == len(int_list) - 1:
        trailing = " = "
    else:
        trailing = " + "
    print(template, end="")
    print(trailing, end="")

x = 0
for i in range(0, len(int_list)):
    x += (int_list[i] * int_list[i])

print(x)

Your problem exists in the here:

for i in range(0, len(int_list)):
  x = (int_list[i]*int_list[i])

add = (x+x)
print(add)

Let us walk through what the code does to get a better understanding of what is going wrong.

With a list of [1, 2, 3] The for loop will iterate three times

On the first iteration, x will be assigned the value 1 because 1 * 1 is 1 .

On the second iteration, x will be assigned the value 4 because 2 * 2 is 4 . Notice that rather than the two values being added x's value being overwritten

On the third iteration, x will be assigned the value 9 because 3 * 3 is 9 . Again the value is being overwritten.

After the loop, the variable add is created with the value x + x, or in our case 9 + 9 which is 18

This is why with the list [1, 2, 3] the value displayed is 18

Now that we have walked through the problem. We can see that the problem is overriding the value in the for loop then doubling the value before displaying it.

To fix these problems we can first remove the doubling giving the following code

for i in range(0, len(int_list)):
  x = (int_list[i]*int_list[i])

print(x)

But the program still has the overriding problem so the value of a list [1, 2, 3] would be 9.

To fix this rather than overriding the value of x, let's create a new variable total that will have the result of the loop added to it every iteration rather than being overwritten.

total = 0 
for i in range(0, len(int_list)):
    total = total + (int_list[i]*int_list[i])
    
print(total)

Now let's walk through what the code does now.

With a list of [1, 2, 3] the for loop will iterate three times

On the first iteration, total will be assigned the value 1 because 0 + 1 * 1 is 1 .

On the second iteration, total will be assigned the value 5 because 1 + 2 * 2 is 5 . Notice how the previous value of the loop iteration is being added to the loop

On the third iteration, total will be assigned the value 14 because 5 + 3 * 3 is 14 . Notice again how the previous value of the loop iteration is being added to the loop.

This gives us the correct result of 14 .

One nice feature of python is the addition assignment which condentes A = A + B to A += B so it is possible to simply the following code to:

total = 0 
for i in range(0, len(int_list)):
    total += (int_list[i]*int_list[i])
    
print(total)

A reason this problem may have been so difficult is that the for loop is more complicated than it needs to be. It is possible that rather than iterating through a list of indices generated by a list of numbers then assessing the numbers from the list by their index. It is possible to iterate through the numbers directly.

With the that simplification your loop would look like this:

total = 0 
for number in int_list:
    total += number * number
    
print(total)

These changes would make your whole programme look like this:

int_list = [] # initiate list

while True:
  user_input = input("Enter an integer (or Q to quit): ") # get user input
  if user_input == "Q": # break loop if user enters Q
    break
  integer = int(user_input) # convert user_input to an integer to add to list
  int_list.append(integer) # add the integers entered to the list

for i in range(0, len(int_list)):
  template = ("({0} x {1})".format(int_list[i], int_list[i]))
  if i == len(int_list)-1:
    trailing = " = "
  else:
    trailing = " + "
  print(template, end="")
  print(trailing, end="")

total = 0 # start the total at zero as no values have been calculated yet
for number in int_list: # iterate through all values in the list
  total += number * number # add to the total the number squared

print(total)

You can try this

state= True
combi= []
while state:
    user_input = input("Enter an integer (or Q to quit): ").lower() 
    if "q" in user_input: 
        state= False
    else:
        combi.append(int(user_input))
else:
    final= sum([x+x for x in combi])
    print(final)

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