I am trying to write a program that accepts two strings from the user:
s1 = input("Please enter a word:")
s2 = input("Please enter another word:")
How can I output True
if the two are anagrams and False
otherwise?
If you found this question from a search engine and want to look for possibly multiple anagrams within a list: it is possible, but not optimal to compare each pair of elements. Please see Using Python, find anagrams for a list of words for more specific advice.
You need to think through your conditional logic a bit more. The loop is on the right track, but if there is a letter in s1 that is NOT in s2, you should break
out of this loop and print the "False" statement. Consider using a variable like all_s1_in_s2 = True
and then setting that to false if you find a letter that doesn't match.
Some other tips:
for l in s1
will loop through string s1 giving you access to each letter in sequence as l
- you don't need range
or len
at all
The if .. in
statement can help test whether a letter exists in a string, e.g. if letter in mystring:
is a valid statement and this could help you a lot, again not needing range
or len
You should avoid using numbers in variable names where possible - better would be word_one
and word_two
, as an example