[SOLVED] Write a function named first_word that returns the first word in a string

Issue

My buddy sent me a screenshot a question he was stuck on for an assessment and asked if I was able to help. So I took a shot at it and it’s been two days now and this is haunting my dreams.

Question: "create a function named first_word that takes in a string and returns the first word.

Given Code:

assert first_word("Random string here") == "Random"
assert first_word("Another random string here") == "Another"
assert first_word("Again a random string... etc.") == "Again"
print("Excerscise is complete"

What I have Tried amongst other variations:

def first_word(x):
        print(first_word.split().pop(0))
        return first_word
assert first_word("Random string here") == "Random"
assert first_word("Another random string here") == "Another"
assert first_word("Again a random string... etc.") == "Again"
print("Excerscise is complete"



def first_word(x):
        print(first_word.split()
        return
assert first_word("Random string here") == "Random"
assert first_word("Another random string here") == "Another"
assert first_word("Again a random string... etc.") == "Again"
print("Excerscise is complete"

I have tried a lot of different combinations and can’t think to add them all, I have looked up online and I can’t seem to make the code work how it was for the assessment. I can return the first letter but I cannot wrap my brain around how to get the first word.

This assessment my friend is doing has no actual impact on me, and it’s already passed so he will gain nothing from this. I merely want to understand how to complete this task that will help me figure out why it is failing.

I currently work in eDiscovery and am working towards getting my security + and OSCP. I feel gaining any knowledge of python will be beneficial. Any help would be appreciated. Thank you very much

-Oerml

Solution

You have the right basic idea here:

def first_word(x):
    print(first_word.split().pop(0))
    return first_word

but are confused about the syntax:

  • first_word is the function, and x is the string parameter that you’re trying to get the first word of. first_word.split() doesn’t make sense, because you can’t split() a function. What you can split() is x.
  • You’re mixing up print and return. Your function is supposed to return the first word (not first_word, which is the function itself, but the string you get by splitting x), and not print it.

This should work:

def first_word(x):
    return x.split()[0]

Answered By – Samwise

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.