Using 'is not' in Python - python

I am trying to cursor search through some records in an access table from a field called DEV_TYPE. I want to compare each record against a list of know values I have built earlier in my script:
(devcatList)
I want to print out any values that do not occur in the list. Some of the values in the records are Null as well. I want to set my if statement to only print out values that do not occur in the list, but I also do not want to print out 'None' for the Null values. My script is as follows:
if field.name == "DEV_TYPE":
for iRow in arcpy.SearchCursor(fc):
if not iRow.DEV_TYPE is None or iRow.DEV_TYPE not in devcatList:
print str(iRow.OBJECTID) + " - " + str(iRow.DEV_TYPE)
I've played around with the 'if not x is None' to 'if x is not None'. Changed the 'or' to and 'and' (even though it was counter intuitive), but my printouts either return all values or no values or only 'None'....basically everything I don't want. I'm sure I'm doing something silly. Can someone point out what my silliness is?
Thanks,
Mike

I think you want if iRow.DEV_TYPE is not None and iRow.DEV_TYPE not in devcatList:

Maybe something like this:
if field.name == "DEV_TYPE":
for iRow in arcpy.SearchCursor(fc):
dev_type = iRow.DEV_TYPE
if dev_type is not None and dev_type not in devcatList:
print "{} - {}".format(iRow.OBJECTID, iRow.DEV_TYPE)
The if dev_type is not none can be more conveniently (but less precisely) stated if dev_type since None is equivalent to False in a conditional context. I also took the liberty of rewriting the print statement in a more idiomatic fashion.

Related

I have to use "IN Operator" but can't use"True" in the codes to get "True" as an answer

I had to modify the code in such a way that I use "In operator" and the result should display "True" if a given word is found in string
mystery_string = "Hello, world!"
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#The 'in' operator can be used to see if a string of characters
#is found within another string of characters, just like it can
#be used to find if an item is in a list.
#Above we've created a string with the variable name
#mystery_string. Write some code below that will print True
#if the string "world" appears within mystery_string, and
#False if it does not.
#Write your code here!
if "world" in mystery_string:
print("True")
else:
print("False")
#dropdown in the top left:
#We found the str "True" declared in your code. You shouldn't be creating this value
#manually.`
"world" in mystery_string returns a boolean value. You should not have to print True or false manually. Instead, you can do print("world" in mystery_string). This should print true if world is in string else print false.
print("world" in mystery_string)
Finally, it worked!

How to compare two strings with the != operator and store the result in a variable called my_boolean?

I'm not sure I understand what they're asking me to do here, so this is my attempt at doing it.
a='Swim'
b='Run'
if a!=b:
my_boolean = a!=b
print (my_boolean)
the excercise is only asking you to save the value of 'a!=b' in a variable.
However this should help you to understand the code better; you should save 'a != b' only once and then use 'my_boolean' every time you need it, but your code only prints true, because if 'my_boolean' is false, try this:
a = 'Swim'
b = 'Run'
my_boolean = a != b
print(my_boolean)
if my_boolean:
print('printing result: ' + str(my_boolean))
Let's get through it one-by-one. You are trying to compare two strings. If they are exactly the same you should get True otherwise you get False. Doing so would result in a Boolean or bool value.
So, your solution is inverted. It is expected to be:
a='Swim'
b='Run'
my_boolean = (a==b) # This value is boolean already. You can remove the brackets too. I put them for clarity
print (str(my_boolean)) # It works without saying str(), but I did that to show you that the value is converted from the type `bool` into the type String `str`.

converting tuple to set for use in if-in statement in python?

i have a tuple which looks like this b (u'3.7', 9023). i want to use it in the following statement :
if list(self.ballot_number) == msg.ballot_number and b in waitfor:
print "hello"
i have checked and the ballotnumber section of the if condition is worrking fine. it's the second part that's not returning true. the waitfor set looks like this : set([((u'3.0', 9002), (u'3.1', 9005), (u'3.2', 9008), (u'3.3', 9011), (u'3.4', 9014), (u'3.5', 9017), (u'3.6', 9020), (u'3.7', 9023))]).
The value of tuple are there in the set but they are not able to match it probably because of different data types. i don't want to split the tuple into individual elements as i have to use it collectively later in the code. How can i run my if statement?
building of set
waitfor = set()
print "in scout"
for a in self.acceptors:
print "acceptor",a
a = tuple(tuple(p) for p in self.acceptors)
waitfor.add(a)
print "waitfor",waitfor
The problem is that you’re not building the set that it seems you think you’re building, and as a result it can’t be used the way you want to use it.
Your code does this:
waitfor = set()
print "in scout"
for a in self.acceptors:
print "acceptor",a
a = tuple(tuple(p) for p in self.acceptors)
waitfor.add(a)
print "waitfor",waitfor
So, for each acceptor, you’re not adding that acceptor to the set, you’re adding the tuple of all acceptors to the set. You do this over and over, but because it’s a set, and you’re adding the same tuple over and over, you end up with just one element, that big tuple of all of the acceptors. Which is exactly what you see—notice the extra parentheses in your output, and the fact that if you print out len(waitfor) it’s just 1.
And this means that none of the p values you later check with p in waitfor are going to be in waitfor, because the only thing that’s actually in it is the giant tuple that contains all those pairs, not any of the pairs itself.
It’s like adding “The State of California” to a phonebook millions of times, instead of adding the millions of Californians, and then asking “Is Jerry Brown in the phonebook?” No, he’s not. There’s no bug in how you’re searching the phonebook; the bug was in creating the phonebook. So that’s the part you need to fix.
So, what you want is:
waitfor = set()
print "in scout"
for a in self.acceptors:
print "acceptor",a
waitfor.add(tuple(a))
print "waitfor",waitfor
Or, more simply, this one-liner:
print “in scout”
waitfor = set(tuple(p) for p in self.acceptors)
print “waitfor”, waitfor
Or, if your version of Python is new enough for set comprehensions (I think that means 2.7, but don’t quote me on that), it’s slightly more readable:
print “in scout”
waitfor = {tuple(p) for p in self.acceptors}
print “waitfor”, waitfor
You've got too many brackets in your set, so it's only looking for a single element.
len(waitfor)
# 1
If you try:
waitfor = set([(u'3.0', 9002), (u'3.1', 9005), (u'3.2', 9008), (u'3.3', 9011), (u'3.4', 9014), (u'3.5', 9017), (u'3.6', 9020), (u'3.7', 9023)])
Then your test:
(u'3.7', 9023) in waitfor
# True
Will work!

Is it possible to find out which condition is being met in a multi condition if then statement?

I'm working on a python/beautifulsoup web scraper. I'm searching for certain keywords, my statement looks like this:
if 'tribe' in entry or 'ai1ec' in entry or 'tfly' in entry:
print('Plugin Found!')
rating = easy
sheet.cell(row=i, column=12).value = rating
What I would like to do is find out which one of those keywords is making the statement true. My first instinct would be to write a nested loop to check but I wasn't sure if there was a way to capture the value that makes the statement true that would involve less code?
I would use a generator comprehension that I would pass to next with a default value. If the comprehension doesn't find anything, next returns the default value, else it returns the first found and stops there (kind of any, but which stores the result)
cases = ['tribe','allec','tfly']
entry = 'iiii allec rrrr'
p = next((x for x in cases if x in entry),None)
if p is not None:
print('Plugin Found!',p)
[EDIT: changed to only find first name]
for name in ('tribe', 'ailec', 'tfly'):
if name in entry:
print ('Name =', name)
print('Plugin Found!')
rating = easy
sheet.cell(row=i, column=12).value = rating
break

Python dictionary failsafe [duplicate]

This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
Closed 9 years ago.
I have created a dictionary in python as my first 'major' project. I'm using it to keep track of key words as I go along. The entered are just examples so feel free to improve my definitions (:
I'm new to python so feel free to criticise my technique so I can learn before it gets any worse!
What I'm wondering is, would there be a way to deal with searches that are not included in the dictionary.
As in 'Sorry, the word you were looking for could not be found, would you like to try another search?'
Anyway, here's my code:
Running = True
Guide = {
'PRINT': 'The function of the keyword print is to: Display the text / value of an object',
'MODULO': 'The function of Modulo is to divide by the given number and present the remainder.'
'\n The Modulo function uses the % symbol',
'DICTIONARY': 'The function of a Dictionary is to store a Key and its value'
'\n separated by a colon, within the {} brackets.'
'\n each item must be separated with a comma',
'FOR LOOP': 'The For Loop uses the format: \n '
'For (variable) in (list_name): (Do this)',
'LINE BREAKS': ' \ n ',
'LOWERCASE': 'To put a string in lower case, use the keyword lower()',
'UPPERCASE': 'To put a string in upper case use the keyword upper()',
'ADD TO A LIST': 'To add items to a list, use the keyword: .append'
'\n in the format: list_name.append(item)',
'LENGTH': 'To get the length of a STRING, or list use the keyword len() in the format: len(string name)', }
while Running:
Lookup = raw_input('What would you like to look up? Enter here: ')
Lookup = Lookup.upper()
print Guide[str(Lookup)]
again = raw_input('Would you like to make another search? ')
again = again.upper()
if again != ('YES' or 'Y'):
Running = False
else:
Running = True
You can use a try/except block:
try:
# Notice that I got rid of str(Lookup)
# raw_input always returns a string
print Guide[Lookup]
# KeyErrors are generated when you try to access a key in a dict that doesn't exist
except KeyError:
print 'Key not found.'
Also, in order for your code to work, you need to make this line of code:
if again != ('YES' or 'Y'):
like this:
if again not in ('YES', 'Y'):
This is because, as it currently stands, your code is being evaluated by Python like so:
if (again != 'YES') or 'Y':
Furthermore, since non-empty strings evaluate to True in Python, having the code like this will make the if-statement always return True because 'Y' is a non-empty string.
Finally, you can completely get rid of this part:
else:
Running = True
since it does nothing but assign a variable to what it already equals.
Two options.
Use the in operator:
d = {}
d['foo'] = 'bar'
'foo' in d
Out[66]: True
'baz' in d
Out[67]: False
Or use the get method of your dictionary and supply the optional default-to argument.
d.get('foo','OMG AN ERROR')
Out[68]: 'bar'
d.get('baz','OMG AN ERROR')
Out[69]: 'OMG AN ERROR'
You can get what you want if you replace
print Guide[str(Lookup)]
with
badword = 'Sorry, the word you were looking for could not be found, would you like to try another search?'
print Guide.get(lookup,badword)
One thing that jumped out is naming your dict with a capital letter. Generally capital letters are saved for classes. Another kind of funny thing is that this is the first time I've seen a dict actually used as a dictionary. :)

Categories

Resources