Search code examples
python-3.xstringif-statementinputalphabetical

alphabetically sorting multiple strings


The code I am trying to write must include a prompt from the user, and three separate strings. I am able to get the sorting function to work when I ask the user to input 3 words in the same prompt, but when I separate the inputs out, the sorting function is not working. I am very new to coding (first week), so I apologize if this is not clear.

I am supposed to be writing a series of Python statements that will prompt the user for three strings. Then, using an 'if' statement, print them in alphabetical order.

Here is the code I have so far: Might anyone have any suggestions?

Thank you!

word1 = input(str("Please enter a word of your choice:"))
word2 = input(str("please enter another word, but make sure the word does not start with the same letter:"))
word3 = input(str("Awesome! Ok, finally, enter one last word, again making sure not to use the same letter:"))
    
if (word1 == word2):
    print("The words are the same")
else:
    print("Nicely done, you read directions well!")
       
print("The words in alphabetical order are..")

What's next here? I can't find this info anywhere.


Solution

  • You need to compare the strings and given the comparisons, perform an action. Using the string comparison from this resource to compare strings and the algorithm from this post, you can order the three strings.

    word1 = input(str("Please enter a word of your choice:"))
    word2 = input(str("please enter another word, but make sure the word does not start with the same letter:"))
    word3 = input(str("Awesome! Ok, finally, enter one last word, again making sure not to use the same letter:"))
    
    if (word1 == word2):
        print("The words are the same")
    else:
        print("Nicely done, you read directions well!")
    
    print("The words in alphabetical order are..")
    
    if(word1>word3):
      tmp = word1
      word1 = word3
      word3 = tmp
    
    if(word1>word2):
      tmp = word1
      word1 = word2
      word2 = tmp
    
    if(word2>word3):
      tmp = word2
      word2 = word3
      word3 = tmp
    
    print(word1)
    print(word2)
    print(word3)