Reputation: 23
if file is not None:
content = file.readlines()
if 'I' and 'J' in content:
display_oval()
else:
display_polygon()
in this case,suppose i opened a file containing I&J . i expect to call display_oval()
but it calls display_polygon()
. when i opened file not containing I&J,display_polygon()
calls as expected.
when i replaced 'I' and 'J'
with 'I' or 'J'
,when i opened a file containing I&J,display_oval()
works fine. But when i opened file not containing I&J, nothing works.
I want to call display_oval()
if file contains I&J and display_polygon()
otherwise. how it can be done?
Upvotes: 0
Views: 41
Reputation: 104712
You have a couple of intersecting issues with your code.
Thie first issue is that 'I' and 'J' in content
gets grouped as ('I') and ('J' in content)
, which is surely not what you intend. A string like 'I' is always truthy, so testing in that way is not useful. You probably mean
'I' in content and 'J' in content`.
But that's not enough to fix your code (it makes fewer inputs match, not more). The condition will still not work right because your content
is a list of strings, all but the last of which will be newline terminated. When done on a list, the in
operator expects exact matches, not substring matches as in
does when both arguments are strings.
I'm not exactly sure what fix would be best for that second issue. It depends on the logic of your program, and the contents of your file. If you want to test if I
and J
show up as individual lines in the file (each separately, on a line with no other characters), you might want to test for 'I\n' in content and 'J\n' in content
using the same content
you're using now. On the other hand, if you want to check for a capital I
and J
characters anywhere in the text of the file, without regard to lines, then you probably need to change content
instead of changing the matching logic. Use content = file.read()
to read the whole file into a single string, rather than a list of strings. Then 'I' in content
will do a substring search.
Upvotes: 1