Go inside another For

Asked

Viewed 136 times

-4

Guys I’m needing to run a for inside another for but I’m not getting it. I need to store the result value within a variable. I’m not familiar with python, I believe this is the biggest problem. Follow what I’ve been trying to store the result.

import math

perimeter = [18, 24, 14]

area = [24, 36, 10]

lista2 = []

for i in perimeter:
    for x in area:
        d = {}   
        d = print(((i/2)+math.sqrt((i/2))**2-4*x))/2))
        lista2.append = (d)
print(lista2)

Can anyone propose me a solution to the problem? Because I can’t reach the result.

1 answer

1

  1. I do not know if it was a mistake in the formulation of the question, but the code is undefined. In the Python language, what defines what is inside a code structure, such as for, is its internal indentation.

  2. The function append, for lists, you receive a value that will be added to the list. The way it’s being used, it’s like you’re passing its return value to the variable d, which makes no sense, since it returns nothing. The correct use would be as follows:

    Lista2.append(d)

  3. There is a syntax error in the variable calculation d. Correction, it is as follows:

    d = ((i/2)+math.sqrt((i/2))**2-4*x)/2

The whole code goes like this:

import math

perimeter = [18, 24, 14]

area = [24, 36, 10]

lista2 = []

for i in perimeter:
    for x in area:
    
        d = {}
    
        d = ((i/2)+math.sqrt((i/2))**2-4*x)/2
    
        lista2.append(d)

print(lista2)

See running on repl.it

  • There was an error in formatting the question yes, but the answer was great, I was able to solve the problem. I ended up realizing that I didn’t need one to go inside another, but only to use a zip for both lists. But I still have a problem with the variable calculation syntax. Using python I can write as follows: d = ((24/2)-Math.sqrt((24/2)**2-4*32))/2. print returns 4. But when I put it inside the for, it returns a Valueerror: Math Domain error. How to fix this error?

  • Thallys, in the variable there is the use of the function sqrt, that computes the square root. This error can happen when the parameter of this function is a negative number, which would return a domain error. Make a debug simple (can even print on the screen the value that is passed to the function sqrt) and make sure it happens. Take a look at this question: https://answall.com/questions/295455/math-domain-error-no-python

Browser other questions tagged

You are not signed in. Login or sign up in order to post.