Reputation: 9
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")
Upvotes: 0
Views: 3133
Reputation: 3128
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")
Upvotes: 1
Reputation: 3174
You could also use .startswith()
:
if greet.startswith("hello"):
print("wrong")
elif greet.startswith("h"):
print("okay")
else:
print("good")
Upvotes: 1