python if condition not working properly as anticipated - python

In a onClick_button event I've a if condition to show a messagedialog if condition fails or else execute the rest of the statements.
Basically if condition is checking whether a textctrl has value or not. If there is value execute the else statement.
this works for the first time with out any value in tc(textctrls) with a msgdlg, but when click ok on the dlg and add some value in the tc, still the msgdlg pops out when it should execute the else.
Your help is very appreciated.
I've checked all the indentation.
def onClick_button_new(self, event):
self.list_box.Clear()
varstr = "csv"
if [(self.tc1.GetValue() == "") or (self.tc2.GetValue() == "")]:
dial = wx.MessageDialog(None, 'No file specified. Please specify relevant file', 'Error', wx.OK)
dial.ShowModal()
else:
file1 = subprocess.check_output("cut -d '.' -f2 <<< %s" %self.var1, shell = True, executable="bash")
file1type = file1.strip()
print file1type
file2 = subprocess.check_output("cut -d '.' -f2 <<< %s" %self.var2, shell = True, executable="bash")
file2type = file2.strip()
if varstr in (file1type, file2type):
print "yes"
else:
dial = wx.MessageDialog(None, ' Invalid file format. Please specify relevant file', 'Error', wx.OK)
dial.ShowModal()

depending on your input
[(self.tc1.GetValue() == "") or (self.tc2.GetValue() == "")]
is either [True] or [False]. in any case a non-empty list. this will be interpreted as True;
if [False]:
do_something()
in this example do_something() will always be executed.
to fix this you need to remove the brackets []:
if (self.tc1.GetValue() == "") or (self.tc2.GetValue() == ""):
...

You have your boolean logic mixed up and created a list object (which is always non-empty and always true). You want to use and and not use a list:
if self.tc1.GetValue() == "" and self.tc2.GetValue() == "":
You should never use a [...] list for a boolean test, because that just creates a list object that is not empty, and thus always considered true in a boolean context, regardless of the contained comparison results:
>>> [0 == 1 or 0 == 1]
[False]
>>> bool([0 == 1 or 0 == 1])
True

Don't need to compare your method result to empty string :
if not self.tc1.GetValue() and not self.tc2.GetValue():
See that post : Most elegant way to check if the string is empty in Python?

Related

Get TypeError when call the function from second time

My problem is the error message only happen after I call the function second time
numLen, phoneMask = numberLen(3)
TypeError: 'NoneType' object is not iterable
Here is my code.
If I type in correct extension, for example 71023 at first time I run the script, there is no problem.
If I typed wrong extension at first time and typed in correct one the second time, it return the typeerror message and I can see numberlen(i) returned none.
Thank you in advance.
import sys
def numAssign(t):
maskList = ['02694406XX', '02693710XX']
extList = ['706XX', '710XX']
i = 0
while i < len(extList) :
if t != extList[i] :
i = i + 1
else :
return True, maskList[i]
print('''The extension you entered is not in the indial range.''')
return False, ' '
def numberLen(i):
t = input('Please enter the extnsion : ')
T = len(t)
isNum = t.isdecimal()
patternConvert = t[0:3] + 'XX'
if T == 5 and isNum == True :
valid, mask = numAssign(patternConvert)
print(mask)
print(i)
if valid == True:
print(numAssign(patternConvert))
return True, mask
else :
if i == 0 :
print('''The number you entered was not valid.
It has to be 5 digits.''')
else :
print('Please try again')
print(i)
numberLen(i-1)
else :
if i == 0 :
print('Your entering is invalid, we will terminiate the programe')
exit()
else :
numberLen(i-1)
if __name__ == '__main__':
numLen, phoneMask = numberLen(3)
print(phoneMask)enter code here
Your numberLen() function only returns the tuple the caller is expecting when the user makes a valid input the first time; otherwise it calls itself recursively and does not return its returning value, which makes the function to return None by default, causing the exception when the caller tries to unpack it as a sequence.
You should change both occurrences of:
numberLen(i-1)
to:
return numberLen(i-1)

read a file line by line and print only after its done

So I am working on doing a "simple" task since like 2h and still can't find the solution, so where is my question :
I want to search in a file, line by line, and if no result is found, at the end print something, else call a function.
def DeletItemCheckUp():
import re
find = True
itemNumber = input("\n what is the item you want to delet : ")
fileItem = open('Data_Item', 'r', encoding='Utf-8')
for line in fileItem:
sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
if (sr == None):
pass
print("This item don't exist.")
fileItem.close()
if (find == True):
return itemNumber
DeletItem()
so here is the problem I have got with different try :
1. Print "This item don't exist." for every line that didn't had my itemNumber.
2. When there was actually no match found, its would not call DeletItem().
objectif of the code :
Ask for a item to delet, check in a file if the unique item number exist, if so, call DeletItem() to delet it, else, tell the user that this unique item number don't exist.
Few overlooks in there to achieve what you ask. We are going to use a flag (true/false) to know when we found something, and based on that we will decide whether to call the function or print/return the number.
def DeletItemCheckUp():
import re
find = False # initialize to False
itemNumber = input("\n what is the item you want to delet : ")
fileItem = open('Data_Item', 'r', encoding='Utf-8')
for line in fileItem:
sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
if (sr == None):
continue # do nothing and continue
else:
# we found the number, set the flag and break
find = True
break # no need to continue searching
fileItem.close()
if (find):
DeletItem() # call the function
else:
print("This item don't exist.")
1) replace the pass with your print('This item doesn't exist'). "Pass" means "do nothing."
2) Your DeleteItem() is after the return. Nothing executes after the return because you have returned to the place the function was called from. You want
else:
DeleteItem()

python won't execute second condition if elif

i have this on my script
for x in test:
extra_data_list = ast.literal_eval(x['extra_data'][3])
if extra_data_list.has_key('first_name') == True:
if extra_data_list['email_address'] == current_user['email']:
linked.append('Linkedin')
elif is_google == current_user['email']:
linked.append('Google Plus')
but when i pass linked to my template, i got one result, just 'Linkedin',
even second condition is also true, can you tell me to solve this ?
You are missing a tab before the elif. It referers to the external if
Because the first if condition is true your code cannot execute the elif!
You can just use a normal if statement:
for x in test:
extra_data_list = ast.literal_eval(x['extra_data'][3])
if extra_data_list.has_key('first_name') == True:
if extra_data_list['email_address'] == current_user['email']:
linked.append('Linkedin')
if is_google == current_user['email']:
linked.append('Google Plus')

How to pass when variable = null in python 3

so far I have this:
import datetime
f = open("log.txt", "a", encoding='UTF-8')
print ("Log file created")
print ("Enter /close to leave.")
spc = " "
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if msg == None:
pass
if msg == " ":
pass
else:
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
However, this line is not functioning as I want it, it still returns a blank line on the log file:
if msg == None:
pass
I want it to not return anything and simply continue the while loop, How would I fix this?
You should be using
if msg is None:
pass
Edit
You're missing what the pass function is all about. I would re-write your look like so. This way we're only processing this if the msg is not one of the bad input. Once we're done we break out of the loop.
...
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if not msg in [None, " "]
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
break
Evaluation of the rest of the loop will still continue after pass, and as None does not equal " ", this means the block beginning with msg2 = now1+spc+msg+"\n" will be executed. You need to either unite the if ... if ... else into a single if block by changing if msg == " ": to elif msg == " ": or else change if msg == None: pass to if msg == None: continue.
try:
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
except:
pass #example for a function: return None or raise
Your condition doesn't make any sense. The input function will never return None, only strings.
If you want to skip empty strings, a better test would be if not msg (empty strings are "falsy"). Or, if you want to reject any all-whitespace strings, try if not msg.strip() (which removes leading and trailing whitespace before checking if the rest of the string is empty or not).
Further, it's rarely a good idea to write an if statement that just contains pass. Instead, invert the test so that the condition is true for cases where you want to run some code (in this case, when msg is not empty or all whitespace) and simply omit the cases where you'd do nothing:
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if msg.strip(): # msg is not empty or all whitespace
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
One final issue (unrelated to the main question). Python's exit function is primarily intended for use in the interactive interpreter. It is added to the builtins by the site module, and so it won't exist if Python was run with the -S flag. If you want to close the interpreter, you should instead call sys.exit, raise a SystemExit exception, or just run off the end of the main module (a break statement would probably do that for the loop you've shown here, or perhaps a return if you're in a function somewhere).

Python: How to continue overwrite the code after "Return True"

The following is the basic function:
In the CheckReady.txt file, there can be 1 or 0
After it reads 1, it should return True, and then replace 1 to 0 to complete reset
If it reads 0, then it will return false.
Below is my code:
def CheckReady():
s = open("CheckReady.txt").read()
print "Ready= ",s
if s == "1":
print "ready"
return True
s = s.replace("1", "0");
f = open ("TrakStarReady.txt",'w')
f.write(s)
print "Ready= ",s, "Reset Complete"
elif s == "0":
print "not ready"
return False
f.close()
Here is my question:
I know that after return True, the code will stop to do replace 1 to 0... i'm really new in programming...tried many times,but have no idea how to fix that.
Could someone help me to fix this problem and complete the basic function?
Do everything you want to do, and then return:
def CheckReady():
with open("CheckReady.txt") as check:
s = check.read()
print "Ready= ",s
if s == "1":
print "ready"
s = "0"
with open("TrakStarReady.txt",'w') as trak:
trak.write(s)
print "Ready= ",s, "Reset Complete"
return True
else:
print "not ready"
return False
You don't need to open the CheckReady file. Instead, use the file as a "marker". If you're not ready, have the file moved to a temp location. When it is ready, rename it.
Here's how I would improve it:
import os
def CheckReady():
if os.path.isfile('/my/path/ready.txt'):
# the file exists. Reset the marker
os.rename('/my/path/ready.txt', '/my/path/notready.txt')
with open ("TrakStarReady.txt",'w'):
f.write(1)
return True
else:
print "not ready"
return False

Categories

Resources