Getting nameerror in python - python

I have the following function, I want to concat the 2 strings, What wrong am I doing here?
commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd
for key in commands:
conf_cmd += key + '\n'
print(conf_cmd)
Getting the following error:
conf_cmd += key + '\n'
After running it, I get this error:
NameError: name 'conf_cmd' is not defined

I added your code with your critical issue resolved.
commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd = '' // <-- ''
for key in commands:
conf_cmd+=key+'\n'
print(conf_cmd)

All you need to do is to add:
conf_cmd = ''
just after commands = ["abcd","123"]
Why?
global conf_cmd Does not create new string, it just means you can access the global variable.

Related

Problem using exec within class' function in Python

The following code works as expected
name = "Test"
myname = ""
exec('myname ="' + name + '"')
print(myname)
Which shows as result:
Test
Problem
However, if I define the same within a function in a class and execute it I get as result an empty string.
class new(object):
def __init__(self, name):
self.print(name)
def print(self, name):
myname = ""
exec('myname ="' + name + '"')
print(myname)
a = new("My name")
The above is a toy example code of a bigger code.
Question
How to define the function so as to get the same result? The exec function is actually needed in the bigger code.
You can pass a dictionary as the globals (or locals) for exec.
def print(self, name):
d = {"myname": ""}
exec('myname ="' + name + '"', d)
print(d["myname"])

why summ1 is not getting printed even it is defined in function?

class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def add(self,s1,s2):
summ1 = self.m1 + self.m2
summ2 = s1.m1 + s1.m2
summ3 = s2.m1 + s2.m2
std1=Student(89,99)
std2=Student(95,99)
std3=Student(95,99)
std1.add(std2,std3)
print(summ1)
print(summ2)
print(summ3)
why summ1 is not getting printed even it is defined in function?
Well summ1,summ2,summ3 are defined in add function when I try to print them this code is giving me error.
Error is
NameError: name 'summ1' is not defined
summ1,summ2,summ3 are local variables defined in the function add and they are not visible outside of this function. If you replace them by self.summ1, self.summ2, self.summ3, then print(std1.summ1) etc. will work.
As AnkurSaxena said, you can not access your variables the way you try it.
The following code should solve your problem:
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
self.summ1 = None
self.summ2 = None
self.summ3 = None
def add(self,s1,s2):
self.summ1 = self.m1 + self.m2
self.summ2 = s1.m1 + s1.m2
self.summ3 = s2.m1 + s2.m2
std1=Student(89,99)
std2=Student(95,99)
std3=Student(95,99)
std1.add(std2,std3)
print(std1.summ1)
print(std1.summ2)
print(std1.summ3)

Python NameError and I can not understand

I'm now practicing defining functions:
def get_seconds(hours, minutes, seconds):
return 3600*hours+60*minutes+seconds
Now, I want to exec the function:
amount_a = get_seconds(7200*minutes+30*seconds)
amount_b = get_seconds(__)
result = amount_a + amount_b
print(result)
Error:
NameError: name 'minutes' is not defined
First you define "get_seconds" function, you just need to do :
amount_a = get_seconds(hours=2, minutes=30, seconds=0)
amount_b = get_seconds(hours=0, minutes=45, seconds=15)

UnboundLocalError error: local variable 'i' referenced before assignment

I'm writing a program in selenium python. I pasted here part of the code from my program (I did not paste all the code because it has 800 lines) with the UnboundLocalError error: local variable 'i' referenced before assignment, the error occurs exactly at i += 1.
global i
i = 0
odpowiadanieobserwowaniestronfb0()
def odpowiadanieobserwowaniestronfb0():
if i > ileraz:
driver.quit
skonczono()
'''
try:
testt = driver.find_element_by_xpath('')
except Exception:
odpowiadanieobserwowaniestronfb1()
zleskonczono1()
'''
def odpowiadanieobserwowaniestronfb1():
i += 1
global keyword tells the function, not the whole module / file, what variables should be considered declared outside the scope of the said function. Try this:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
There are two options:
You can use your global variable:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
or you pass the i to the function:
def odpowiadanieobserwowaniestronfb1( i ):
return i += 1

Calling methods from other files in python results in executing the entire python file [duplicate]

This question already has answers here:
Why is Python running my module when I import it, and how do I stop it?
(12 answers)
Closed 3 years ago.
I am new to python programming. I have written sample code as flows.
temp.py
p = 'Tushar'
print(p)
class Basics:
def __init__(self, name, phNum):
self.name = name
self.phNum = phNum
def getString(self):
temp = self.name+' '+str(self.phNum)
print(type(temp))
return temp
bs = Basics("tushar", 9620207652)
x = bs.getString()
print(x)
def isBlue(isBlue):
if(isBlue):
print('Boolean true')
x = 'true'
else:
print('Boolean false')
x = 'false'
return x
tus = isBlue(True)
if(tus != None):
str = bs.getString().split(' ',1)
print(str[0])
print(str[1])
Hello.py
from temp import Basics
class Check:
def __init__(self):
print('Check obj')
def createName(self, firstName, lastName):
str = firstName + ' ' + lastName
return str
emp = Check()
completeName = emp.createName('Tushar', 'Banne')
print(completeName)
b = Basics('Tushar', 98765432)
val = b.getString
print("Val is {}".format(val))
I am running Hello.py file and getting the below output.
Tushar
class 'str'
tushar 9620207652
Boolean true
class 'str'
tushar 9620207652
Check obj
Tushar Banne
Val is (bound method Basics.getString of 0x0000024ECCCB5B70
The questions that I have are as follows
Why is the entire temp.py getting executed?
How to execute only getString method.
Why is it that when I use parenthesis after getString, it fails.
Why is the val printing object reference?
Am I following the correct standards of python coding?
Why is the entire temp.py getting executed?
That's how it works. Importing a module means essentially executing it.
How to execute only getString method.
In order to do so, the code in temp.py has to be changed in a way that it is only executed when the module is run at highest level ("as the __main__ module") instead of imported.
You do that this way:
if __name__ == '__main__':
p = 'Tushar'
print(p)
class Basics:
def __init__(self, name, phNum):
self.name = name
self.phNum = phNum
def getString(self):
temp = self.name+' '+str(self.phNum)
print(type(temp))
return temp
if __name__ == '__main__':
bs = Basics("tushar", 9620207652)
x = bs.getString()
print(x)
def isBlue(isBlue):
if(isBlue):
print('Boolean true')
x = 'true'
else:
print('Boolean false')
x = 'false'
return x
if __name__ == '__main__':
tus = isBlue(True)
if(tus != None):
str = bs.getString().split(' ',1)
print(str[0])
print(str[1])
Why is it that when I use parenthesis after getString, it fails.
I don't see it fail in your question.
Why is the val printing object reference?
Because you asked it to. Referring to a method or function means seeing it as an object and printing its string representation. If you call it (with the () behind), you perform a function call.
First, check this out What does if __name__ == "__main__": do?
When you are importing a python file, all of the code is executed.
What do you mean fails, what is the error?
val = b.getString means that now val references the method getString, that's why it is printed.
No, read the link above, also, python uses snake_case, not camelCase, so call the method get_string, not getString. (this obviously doesn't changes thte

Categories

Resources