NameError: name 'qtd' is not defined appears when i try to make an if

52 views Asked by At

I'm trying to figure out the position of a value in a worksheet, and I have that value stored in a variable.

list = df['Quantidade de Cotas'].tolist()
qtd = 2136252.54442995
print(qtd)

The value of the variable is 2136252.54442995, so it is defined

> 2136252.54442995

But if I try to execute an if

res = [i for i,j in enumerate(list) if j == qtd]

print(res)

this error appears saying that the variable is not defined

> NameError: name 'qtd' is not defined

If I run the exact same code, but instead of the variable, put her value, the if works and returns the correct position within the list

list = df['Quantidade de Cotas'].tolist()
qtd = 2136252.54442995
print(qtd)

> 2136252.54442995

res = [i for i,j in enumerate(list) if j == 2136252.54442995]

print(res)

> [0]

Could someone help me to make this code work this way?

list = df['Quantidade de Cotas'].tolist()
qtd = 2136252.54442995
res = [i for i,j in enumerate(list) if j == qtd]

print(res)

> [0]
1

There are 1 answers

0
Yousef khaled On
import pandas as pd

df = pd.DataFrame({'Quantidade de Cotas': [10, 20, 10, 40, 50]})

list = df['Quantidade de Cotas'].tolist()
# qtd = 2136252.54442995
qtd = 10

res = [i for i,j in enumerate(list) if j == qtd]
print(res)

Outout: [0, 2]

your code is correct but ensure you define 'qtd' before using it in the list comprehension.