Python Forum

Full Version: Help with "For loop"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello. I'm a programming beginner and I am having trouble with something that would be considered really basic.

The following example code won't run:
import csv
global de, ep
DN = 0.200
SCH = 40
with open("Di_Tub.csv", "r") as f3:
    reader2 = csv.reader(f3, delimiter=';')
    for row3 in reader2:
        if row3[0] == DN:
            if row3[1] == SCH:
                de = float(row3[2])
                ep = float(row3[3])
print(de, ep)
I am getting this error:
print(de)
NameError: name 'de' is not defined
Can anyone help me?
As the error says de is not defined

print(de)

de = 'text'
print(de)
Output:
NameError: name 'de' is not defined text
de has not been defined outside of if row3[1] == SCH:
and if if row3[1] == SCH: is never True it never will be defined
(Jun-23-2020, 07:09 PM)Yoriz Wrote: [ -> ]de has not been defined outside of if row3[1] == SCH:
and if if row3[1] == SCH: is never True it never will be defined

But wouldn't "global" define it outside the "if" statement?
About it begin True or not, it's will always be True given my input and the f3 file conditions. The script I posted is just a modified part of a bigger code.

Sorry if my questions are stupid, I'm really new to this.
if I'm not mistaken global does not define a variable. On a 2nd note you probably do not need to declare it a global variable unless there is a reason.
Examples:
#! /usr/bin/env python3

myvar = 'some text'
print(f'Outside -> {myvar}')

def myfunc():
    print(f'Inside function - > {myvar}')
myfunc()

class MyClass:
    def __init__(self):
        print(f'Inside class - > {myvar}')
MyClass()
Output:
Outside -> some text Inside function - > some text Inside class - > some text
define it to be a blank variable outside the if
de = ''
DN is a number. You compare it to a string. They will never be equal.
(Jun-23-2020, 07:23 PM)menator01 Wrote: [ -> ]define it to be a blank variable outside the if
de = ''

It didn't help :/

(Jun-23-2020, 08:25 PM)jefsummers Wrote: [ -> ]DN is a number. You compare it to a string. They will never be equal.

That was it, so simple!

Thank you a lot!