0

I am trying to print a certain output if the user's input (greet) begins with a certain word "hello" else if the input begins with h using the if statement.

I have tried:

if greet == "hello":
    print("wrong") 
elif greet == "h_" #(but not hello)
    print(" okay")
else: 
    print("good")
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Christine
  • 9
  • 5
  • 3
    Does this answer your question? [Checking whether a string starts with XXXX](https://stackoverflow.com/questions/8802860/checking-whether-a-string-starts-with-xxxx) – mkrieger1 Jul 27 '22 at 17:05
  • @gimix `greet == "h_"` does not check if `greet` starts with `"h"`. – John Kugelman Jul 27 '22 at 17:06
  • That's for sure :D I only suggested to OP that they first of all polish their code, since in its initial form it was not even Python correct code – gimix Jul 27 '22 at 17:33

2 Answers2

1

You could also use .startswith():

if greet.startswith("hello"):
    print("wrong")
elif greet.startswith("h"):
    print("okay")
else:
    print("good")
ewz93
  • 2,444
  • 1
  • 4
  • 12
  • This is the best answer towards what OP asked. My answer had all kinds of checks for lower/upper, if nothing was entered, and if a space was the first entered character.....but OP didn't ask for any of that. – Michael S. Jul 27 '22 at 17:27
1

Try this. It ignores leading and trailing spaces by calling strip, it has a conditional for if nothing was placed in the input, and lastly it's case insensitive because it standardizes the input to lower:

greet = input().strip()

if len(greet) > 0:
    firstWord = greet.split(" ")[0].lower()
    if firstWord == 'hello':
        print("wrong")
    elif firstWord[0] == "h":
        print("ok")
    else:
        print("good")
else:
    print("You must enter something")
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Michael S.
  • 3,050
  • 4
  • 19
  • 34