Lioninn22
Lioninn22

Reputation: 39

Finding differences between words

I am trying to make my code have differentiate between eight words that start with different letters and all I can get is an if-else statement to work and I can't get an if-elif statement to work without having eight inputs popping up. I know this is a simle problem but I am new to python.

My code:

if input().lower().startswith('z'):
    print('yes')
elif input().lower().startswith('x'):
    print('no')

Upvotes: 1

Views: 107

Answers (3)

N1B4
N1B4

Reputation: 3453

Expanding on @Padraic_Cunningham's comment:

Rather than write out multiple if elif statements, you can create a dictionary storing the starting letter (the key) and the desire output (the value) for that letter.

letter_dict = {"a": "starts with an a",
               "h": "starts with an h",
                ...
               }

>>> word = input()
>>> Hello
>>> letter_dict[word[0].lower()]
>>> 'starts with an h'

Upvotes: 1

TheSoundDefense
TheSoundDefense

Reputation: 6935

You shouldn't call input() every time like that. Each call to input() will request more text from the user. Do it just once at the start and save it to some variable, and then compare that.

input_str = input().lower()
if input_str.startswith("z"):
  print "yes"
elif input_str.startswith("x"):
  print "no"

Upvotes: 3

kindall
kindall

Reputation: 184091

Store the input in a variable, then test that variable

text = input().lower()

if text.startswith("z"):
     # etc

Upvotes: 4

Related Questions