0

I am trying to create a function that takes two words and returns them if conditions are met. Word 1 has to be a certain number of characters, word 2 has to begin with a certain letter. I can get it to work with one condition but am confused when I have to meet two. This is what I have so far. Example below

Enter a 4 letter word: two
Enter a 4 letter word: wall
Enter a word starting with B: apple
Enter a word starting with B: boxes
['wall', 'boxes']

    def twoWords(lenLet, strtLet):
    input1 = str(input("Enter a word that is 4 letters long: "))
    while len(input1) != 4:
        input1 = str(input("Enter a word that is 4 letters long: "))
        if len(input1) == 4:
            break
    input2 = str(input("Enter a word that begins with b: "))
    while firstletter(input2) != 'b' or 'B':
        input2 = str(input("Enter a word that begins with b: "))
        if firstletter(input2) == 'b' or 'B':
            break
    return input1 and input2

print(twoWords()
uzziclip
  • 9
  • 2

1 Answers1

0

You were on the right track, but you can't do firstletters(input) == 'b' or 'B'. What you could to is transform to lower case and then check against 'b' using input2[0].lower() != 'b' or you could use input2[0] not in ('b', 'B') to check for both.

A side note: You don't need to cast the result of input() to str as it already is a str. And I am not sure what you want to return but input1 and input2 does not make much sense. If you want to return both words (in a tuple) use return (input1, input2). If you just want to say that the input was correct you could use return True. The return statement will only be reached if both words meet your conditions otherwise your program will be in an infinite loop.

Please note, that I have replaced your firstletters() function with input[0] which works for the first character. If you want to check for a couple of characters you could also use str.startswith().

def twoWords(lenLet, strtLet):
    # no need to cast to str, input always returns a str
    input1 = input(f"Enter a word that is {lenLet} letters long: ")
    while len(input1) != 4:
        input1 = input(f"Try again. Enter a word that is {lenLet} letters long: ")
        if len(input1) == 4:
            break
    input2 = input(f"Enter a word that begins with {strtLet}: ")
    while input2[0].lower() != 'b':
        input2 = input(f"Try again. Enter a word that begins with {strtLet}: ")
        if input2[0].lower() == 'b':
            break
    # you will be stuck in an infinite loop as long as the conditions are not met
    # only when the conditions are met you will arrive here so you can just return true
    return True

print(twoWords(4, "b"))
Mushroomator
  • 6,516
  • 1
  • 10
  • 27