Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with "For loop"
#1
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?
Reply
#2
As the error says de is not defined

print(de)

de = 'text'
print(de)
Output:
NameError: name 'de' is not defined text
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
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
Reply
#4
(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.
Reply
#5
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 = ''
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#6
DN is a number. You compare it to a string. They will never be equal.
Reply
#7
(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!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020