I still new in python and have a question here: how could I store the variables outside and to use it later?
I have already created a class and in that class can store variables, for example, the temp_username, how do I get the temp_username and use it outside of the class?
def read_username(self):
temp_username = self.username_entry.get()
temp_username1 = self.username_entry1.get()
if temp_username == '':
print("No valid name")
return
else:
self.name_valid = True
self.username = temp_username
self.username1 = temp_username1
You are dealing with local variables inside a function. What you would need is to transform that local variable into a global one.
A way to do that is using parameters and return:
def read_username(name):
temp_username = name
if temp_username == '':
print("No valid name")
return
else:
return temp_username
temp_username = read_username("ww")
print(temp_username)
Related
I'm new to python and trying to do an f-string as follows:
next_patient = East_Room.get_highest_priority()
print(f"The next patient is {next_patient.display_symptoms()} please")
Where East_Room is an instance of a Class and get_highest_priority is a method within the class to display a patient with the highest integer for the 'severity' attribute as follows:
def get_highest_priority(self):
tmp_priority_patient = None
current_size = self.SLL_waiting_list.size()
counter = 1
while counter <= current_size:
tmp_node = self.SLL_waiting_list.get_node(counter)
tmp_patient = tmp_node.get_obj()
if tmp_priority_patient == None:
tmp_priority_patient = tmp_patient
else:
if tmp_patient.severity > tmp_priority_patient.severity:
tmp_priority_patient = tmp_patient
counter = counter + 1
return tmp_priority_patient
def display_symptoms(self):
print(f"{self.firstname} {self.lastname}:{self.symptoms}")
This is the output:
Conor : Naseau
The next patient is None please
I know that this method works as it works perfectly if I call it without the f-string. thanks for you help!
display_symptoms only prints information but doesn't return anything.
In Python, function that don't return anything return None, hence the output you got: "The next patient is None please"
If you also want the function to return this string, you have to explicitly return it:
def display_symptoms(self):
print(f"{self.firstname} {self.lastname}: {self.symptoms}")
return f"{self.firstname} {self.lastname}: {self.symptoms}"
An even better way to do it would be to make it a property:
#property
def display_symptoms(self):
return f"{self.firstname} {self.lastname}: {self.symptoms}"
I am trying to add new objects to a class(emne) but the new instances of the class needs to be created using user input. So i need a way to be able to chose the name for the object and set some of the values of the objects with user input.
I have already tried to create a function that passes the value of the user input into a x = emner(x) to create it but it only returns:
AttributeError: 'str' object has no attribute 'fagKode'
so i think my issue is that the value of the input is created as a string so that it is not understood as a way to create the function
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne():
nyttEmne = input("test:")
nyttEmne=Emne(nyttEmne)
expected result is that the code creates a new instance of the class.
If by choosing a name you mean your fagKode attribute, what you need is:
fagKode = input('Enter code: ')
Emne(fagKode)
You're adding the instances of Enme to the list in the constructor, so you don't need to save them to a variable.
Alternatively, you can handle that in the function:
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
def leggTilEmne():
nyttEmne = input("test:")
enme.append(Emne(nyttEmne))
I'm not sure what exactly you are asking, since you haven't responded to the comments. So,
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne(self, value): # <--- is this what you want
self.nyttEmne= Emne(value)
This is an example of when to use a class method. __init__ should not be appending to a global variable, though. Either 1) have the class method append to a class attribute, or 2) have it return the object and let the caller maintain a global list.
emne = []
class Emne:
emne = []
def __init__(self, fag_kode):
self.fag_kode = fag_kode
self.karakter = ""
#classmethod
def legg_til_emne_1(cls):
nytt_emne = input("test:")
cls.emne.append(cls(nytt_emne))
#classmethod
def legg_til_emne_2(cls):
nyttEmne = input("test:")
return cls(nyttEmne)
Emne.legg_til_emne_1() # Add to Emne.emne
e = Emne.legg_til_emne_2()
emne.append(e)
I have been working on this little bit of code for a school project extension and I cant seem to find a solution to this. I have so far been attempting to get the new user sign up system working and have stopped working on the login part of the program due to this issue. here is my code:
def newUser():
usernameTemp = entryNew.get()
passwordTemp = entryNewPass.get()
database = {}
addFile = open("database.txt", "a")
addFile.write(usernameTemp + "," + passwordTemp + "\n")
addFile.close()
def userValidation():
global entryNew
global entryNewPass
global valid
fileCheck = open("database.txt", "r")
fileCheckData = fileCheck.read()
fileCheck.close()
entryNew = entryNew.get()
entryNewPass = entryNewPass.get()
database = {}
for line in fileCheckData.splitlines():
if line != '': # ignore empty lines
(username,password) = line.split(",", 1)
database[username] = password
if entryNew == username:
Error(101)
valid = False
if valid == True:
newUser()
break
here is the database.txt file:
######################,#############
testUser,password
admin,administratorPass
You changed the entryNew and entryNewPass variables here:
global entryNew
global entryNewPass
entryNew = entryNew.get()
entryNewPass = entryNewPass.get()
You declared these global, so you replaced the object that has a .get() method (a TkInter entry box?) with a string.
Use different names for these variables:
entry = entryNew.get()
and use those new names in your function:
if entry == username:
You were not actually using entryNewPass anywhere in your code.
I am accessing data from different accounts from an online platform over their API. I have created a class called Account that holds all the information necessary to access this API. I want to be able to set the account (and the necessary info to gain access) each time before I make an API request. I tried to make a function that will set a global variable Acct to the proper account class instance but after I call choose_account(), Acct continues to return '', is there a better way to handle this type of procedure?
Acct = ''
def choose_account():
global Acct
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == 'Adap1':
Acct = Adap1
elif get == 'Adap2':
Acct = Adap2
elif get == 'Adap3':
Acct = Adap3
elif get == 'Adap4':
Acct = Adap4
else:
print ("Please type Adap1, Adap2, Adap3, or Adap4 ")
Edit: show Account and Adap1 etc
class Account():
def __init__(self, name, username, password, org_id):
self.name = name
self.username = username
self.password = password
self.org_id = org_id
def update_pw(self, pw):
self.password = pw
Adap1 = Account('Adap1', 'username', 'password', 'org_id')
Sorry, but use of global variables in that way is not usually a good way to go. You are probably new to programming, so I don't want you to feel you are being "told off", but it would be much more sensible to have the function return a value, and then set the global variable with a statement like
Acct = choose_account()
In which case your function ought to look more like this (untested code):
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == "Adap1":
return Adap1
elif get == "Adap2":
return Adap2
elif get == "Adap3":
return Adap3
elif get == "Adap4":
return Adap4
Better still, you could consider a data-driven approach to the problem, and define a dictionary like
adict = {"Adap1": Adap1, "Adap2": Adap2, "Adap3": Adap3, "Adap4": Adap4}
Then your function could read (again, untested)
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
result = adict.get(get, None)
if result:
return result
As your experience level grows you will start to recognise the difference between good and bad code, but you made a pretty good attempt.
Hi I'm a beginner programmer. I don't know how can I call a variable from function.
I have two def calcular() and guardar(). I get some variables from calcular() that I will call later, but when I call variables in guardar(), it tells me that variable is not defined. I tried making global var, but it doesn't work. Hope you can help me
This is a little of my code...
def calcular():
if nClient == "":
texto = ("Inserta Numero de cliente")
ventanaMensaje(texto)
else:
if cl1=="":
texto = ("Inserta Clave")
ventanaMensaje(texto)
else:
if aB1 == "":
texto = ("Inserta Cantidad")
ventanaMensaje(texto)
else:
try:
clt = open("preciosEsp.txt","r+")
lClt = clt.readlines()
rClt = lClt[0]
sClt = rClt.split("'")
nRClt = sClt[0]
if nClient == nRClt:
cReg=sClt[1]
if cl1== cReg:
prc=sClt[2]
else:
k=1
while cl1 != cReg:
cReg=sClt[k]
k=k+2
if cl1== cReg:
ñ=k-1
prc=sClt[ñ]
else:
x = 0
while nClient != nRClt:
rClt = lClt[x]
sClt = rClt.split("'")
nRClt = sClt[0]
x=x+1
if nClient == nRClt:
cReg=sClt[1]
if cl1==cReg:
prc=sClt[2]
else:
k=1
while cl1 != cReg:
cReg=sClt[k]
k=k+2
if cl1== cReg:
ñ=k-1
prc=sClt[ñ]
indice=int(prc)+3
pdcts = open("productos.txt","r+")
lPdcts = pdcts.readlines()
rPdcts = lPdcts[0]
sPdcts= rPdcts.split("'")
nPdcts = sPdcts[0]
t = 0
if cl1 == nPdcts:
precio1=sPdcts[indice]
global txtD1################## MAKE A GLOBAL VAR
txtD1=sPdcts[1] #### THIS IS THE VARIABLE ########
def guardar():
guardarDatos = (n+txtD1) ################# I CALL HERE, BUT TELL ME THAT VARIABLE IS NOT DEFINED
If you really want a global variable, you'd define it outside of any function
txtD1 = None
def calcular():
...
it will then exist at module level. However, globals are rarely (read: never) the solution you should be using, instead you should be returning information from functions rather than modifying global state. You'd then pass that information into another function to use.
The global keyword in python says that you are referencing a global variable, not creating a new one. However, in your code no such name exists, so you're not actually referencing anything.
first create your "database" somewhere global
clt = dict(map(lambda x:x.split(" ",1),open("preciosEsp.txt","r+"))
now you can acess it anywhere with
clt.get(nClient)
next calcular should return the values you want
def calcular():
...
precio = clt.get(nClient)
return [precio,nClient,...]
then you would store the returned values (or do something with them as soon as they are returned )