elif
Your code doesn't look like it will work the way you intend it to:
if "Mary" in name:
print(name)
if "Alan" in name:
print(name)
else:
print("no")
If name
contains "Mary"
, but does not contain "Alan"
, you will have two lines printed, due to the first print(name)
and the print("no")
statements. It would also print name
twice in the string contained both "Mary"
and "Alan"
, like "Mary is Alan's"`.
You probably wanted an if
/elif
/else
statement:
if "Mary" in name:
print(name)
elif "Alan" in name:
print(name)
else:
print("no")
This will print only once per row.
.startswith
Do you really want in? Should "Anne"
match "Mary-Anne is herself"
? Or are you looking for name.startswith("...")
tests?
Should "Mary"
match "Maryanne is herself"
or "Mary-Anne is herself"
? Maybe you want to add a space to the end of the search term:
if name.startswith("Mary "):
print(name)
elif name.startswith("Alan "):
print(name)
else
print(no)
Alternately, you may want to split name
into words, and check for equality. You'll have to clarify your question.
or
If you want to do the same thing with multiple conditions, you could link them with or
:
if name.startswith("Mary ") or name.startswith("Alan "):
print(name)
else
print(no)
any
If you want to test a long list of similar conditions, joined together with or
, you are really wanting to test if any
of the conditions match. Which is perfect for the any(...)
function, which returns True
if any of the conditions is True
.
Combined any()
with a generator expression, to generate a series of conditions to test:
prefixes = ["Mary ", "Alan "]
for i in range(6):
name = df["A"].iloc[i]
if any(name.startwith(prefix) for prefix in prefixes):
print(name)
else:
print("no")
Loop like a native
Why are you looping over indices, and then extracting the data by index? Why hard-code the length of the range?
prefixes = ["Mary ", "Alan "]
for name in df["A"]:
if any(name.startwith(prefix) for prefix in prefixes):
print(name)
else:
print("no")
if:…else:…
- can you make me see the issue withso many if else
? \$\endgroup\$