Establish an empty variable for future use? - python

I want to be able to establish a variable with no value in order to fill it in at a later point in my code, based upon the output of another function.
Ex:
variable = ""
...20 lines later...
if function() is 10:
variable = "10"
else:
variable = "5"
print(variable + 20)
Here's my code so far:
yahoo = "smtp.mail.yahoo.com"
hotmail = "smtp.live.com"
def smtpServer():
if "#yahoo.com" in username:
server = smtplib.SMTP(yahoo,587)
if "#hotmail.com" in username:
server = smtplib.SMTP(hotmail,587)
else:
pass
def check():
try:
server.connect(server)
server.login(username,password)
server.quit()
line = f.readline()
cnt = 1
while line:
#UserAndPass = str.split(':') #check login
UserAndPass = line.split(':')
username = str(UserAndPass[0])
password = str(UserAndPass[1])
cnt += 1
server = ""
smtpServer()
check()
With what I have now, I keep getting errors saying that it's undefined, so I'm just not sure how to define it for this purpose. Thank you!

If you want to refer a global variable from within a function, you need to declare it using global yahoo or global hotmail in your function. You also need to declare global server in the functions setting and using the server.
You don't need to initialize the variable to an empty value for this to work.
However, your approach of hardcoding the mail servers for mail addresses is completely broken. Use the MX records provided by the domain name system, they're there for a reason.

Use this for making an empty variable:
variable = None
For your code, you can use server = None.

Related

what is wrong with this script? the function does not replace the old email with a new one

I tried to write a script that replaces Hotmail address with Gmail if found in the input, but there is something wrong with the function I think. There is no syntax error but the result just does not output the replaced Gmail domain but the same Hotmail one.
old_email = "hotmail.com"
new_email = "gmail.com"
email = input("Enter email: ")
def replace_domain(email, old_email, new_email):
if "#" + old_email in email.endswith:
index = len(old_email)
new = email[:-index]+ "#" + new_email
return new
return email
a = email
print(a)
Here's the fixed code and then I'll explain what I've changed:
old_email = "hotmail.com"
new_email = "gmail.com"
email = input("Enter email: ")
def replace_domain(email, old_email, new_email):
if email.endswith("#" + old_email):
index = len(old_email)
new = email[:-index] + new_email
return new
return email
a = replace_domain(email, old_email, new_email)
print(a)
First: There was no call to the function. I've added that to the penultimate line.
Second: endswith is a function. I've therefore changed that line so that the function is called with the old email domain.
Third: The # was being output twice, because it isn't removed in the :-index part and then a new one is added immediately afterwards.
I would also make some recommendations:
Fourth: a is not a descriptive variable name, which makes the code harder to read. Similarly, index and new are not ideal variable names. Words like new are best avoided as variable names, because they can easily clash with built-in names.
Fifth: I would consider changing the variable name old_email to old_domain instead. Same with new_email. This is a better match for the contents of that variable.
Example output:
Enter email: robson#hotmail.com
robson#gmail.com
Another example output:
Enter email: robson#aol.com
robson#aol.com

Accessible variables at the root of a python script

I've declared a number of variables at the start of my script, as I'm using them in a number of different methods ("Functions" in python?). When I try to access them, I can't seem to get their value = or set them to another value for that matter. For example:
baseFile = open('C:/Users/<redacted>/Documents/python dev/ATM/Data.ICSF', 'a+')
secFile = open('C:/Users/<redacted>/Documents/python dev/ATM/security.ICSF', 'a+')
def usrInput(raw_input):
if raw_input == "99999":
self.close(True)
else:
identity = raw_input
def splitValues(source, string):
if source == "ident":
usrTitle = string.split('>')[1]
usrFN = string.split('>')[2]
usrLN = string.split('>')[3]
x = string.split('>')[4]
usrBal = Decimal(x)
usrBalDisplay = str(locale.currency(usrBal))
elif source == "sec":
usrPIN = string.split('>')[1]
pinAttempts = string.split('>')[2]
def openAccount(identity):
#read all the file first. it's f***ing heavy but it'll do here.
plString = baseFile.read()
xList = plString.split('|')
parm = str(identity)
for i in xList:
substr = i[0:4]
if parm == substr:
print "success"
usrString = str(i)
else:
lNumFunds = lNumFunds + 1
splitValues("ident", usrString)
When I place baseFile and secFile in the openAccount method, I can access the respective files as normal. However, when I place them at the root of the script, as in the example above, I can no longer access the file - although I can still "see" the variable.
Is there a reason to this? For reference, I am using Python 2.7.
methods ("Functions" in python?)
"function" when they "stand free"; "methods" when they are members of a class. So, functions in your case.
What you describe does definitely work in python. Hence, my diagnosis is that you already read something from the file elsewhere before you call openAccount, so that the read pointer is not at the beginning of the file.

AttributeError: 'str' object has no attribute 'get' when trying to get string information from a tkinter Entry Widget

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.

How to change a global variable in python?

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.

how can I give a variable another value inside a function in python?

I'm creating a simple python script that checks for new comments on a WordPress blog using the xmlrpc API.
I'm stuck with a loop that should tell me if there are new comments or not. Here's the code:
def checkComm():
old_commCount = 0;
server = xmlrpclib.ServerProxy(server_uri); # connect to WP server
comments = server.wp.getComments(blog_id, server_admin, admin_pass, filters);
new_commCount = len(comments);
if new_commCount > old_commCount:
print "there are new comments"
old_commCount = new_commCount
else:
print "no new comments"
while True:
checkComm()
time.sleep(60)
I've skipped the variables like blog_id, server_admin etc.. since they add nothing to this question.
Can you tell what is wrong with my code?
Thanks a lot in advance.
You want to pass it as a parameter, because you are resetting it every time you call the function:
def checkComm(old_commCount): # passed as a parameter
server = xmlrpclib.ServerProxy(server_uri) # connect to WP server
comments = server.wp.getComments(blog_id, server_admin, admin_pass, filters)
new_commCount = len(comments)
if new_commCount > old_commCount:
print "there are new comments"
old_commCount = new_commCount
return old_commCount # return it so you can update it
else:
print "no new comments"
return old_commCount
comm_count = 0 # initialize it here
while True:
comm_count = checkComm(comm_count) # update it every time
time.sleep(60)

Categories

Resources