Python If statement "or" doesn't work as expected

   2013   2   0
User Avatar
Member
20 posts
Joined: March 2019
Offline
When I'm looping over an object's primitives, if I use an 'or' in my if statement, it will start working on all primitives, disregarding the if statement's rules.

#this will return all the name attributes, even though 'asdasfsdf' is not in the name attribute
import hou

kk = hou.node('/obj/geo1/Character')
geo = kk.geometry()

for prim in enumerategeo.prims():
nameAttr = prim.stringAttribValue('name')
if 'shorts' or 'asdasfsdf' in nameAttr:
print(nameAttr)

#this works as expected, only working on the name attributes with 'shorts' in the string, however I don't want to have to write this block of code for every keyword I'm looking for
import hou

kk = hou.node('/obj/geo1/Character')
geo = kk.geometry()

for prim in enumerategeo.prims():
nameAttr = prim.stringAttribValue('name')
if 'shorts' in nameAttr:
print(nameAttr)
User Avatar
Member
1904 posts
Joined: Nov. 2006
Offline
The issue is with how Python interprets your conditional statement. It will evaluate it as: if 'shorts' or ('asdasfsdf' in nameAttr). So "shorts" is always True so it always prints. Without using operators which support intersection if you want to check for multiple values in the attribute vlaue you'll need to do something like: if 'shorts' in nameAttr or 'asdfasdf' in nameAttr: ...
Graham Thompson, Technical Artist @ Rockstar Games
User Avatar
Member
20 posts
Joined: March 2019
Offline
Ah that makes sense, thank you graham!
  • Quick Links