2

I would like to pick the first letter of a user input and use it for decision making in a loop. A simple example:

play_again = input("Do you want to play again? (y/n)").lower()

The program should detect "Yes" as "Y" and "No" as "N".

jpp
  • 159,742
  • 34
  • 281
  • 339

5 Answers5

1

To pick the first letter, simply add a [0] after your input. The [0] is string slicing - here it extracts only the first character of the string.

Also note, all inputs beginning with 'Y' will be treated as the "yes" output, and all inputs beginning with 'N' will be treated as the "no" output.

play_again = input("Do you want to play again? (y/n)").lower()
# Simply add [0]. But that does not work for empty strings.
if len(play_again) > 0) 
    play_again = play_again[0]

Please note that will not work if you provide an empty input - else a traceback will result stating IndexError: string index out of range. That is why there is an if-statement.

Examples:

Do you want to play again? (y/n)YES
y

Do you want to play again? (y/n)no
n

Do you want to play again? (y/n)OMG
o

Do you want to play again? (y/n)yakety yak
y

Do you want to play again? (y/n)
#Empty String
0
play_again = input("Do you want to play again? (y/n)").lower()

if play_again in ['yes', 'no', 'y', 'n']:
    play_again = play_again[0]

    if play_again == 'y':
        # do something

    else:
        # do something else
Josewails
  • 570
  • 3
  • 16
0

String indexing is similar to list indexing in Python. So you can index the 0th element directly:

play_again = input('Do you want to play again? (y/n)')[0].lower()

For example:

Do you want to play again? (y/n)Yes

print(play_again)

'y'
jpp
  • 159,742
  • 34
  • 281
  • 339
0
play_again = input("Do you want to play again? (y/n)").lower()
first_letter=play_again[0]
#or
play_again = input("Do you want to play again? (y/n)").lower()[0]
Pyd
  • 6,017
  • 18
  • 52
  • 109
0

I think this is exactly what you are looking for:

play_again = input('Do you want to play again? (y/n)')[0].lower()

while(play_again=='y'):

    # Do something

    play_again = input('Do you want to play again? (y/n)')[0].lower()

Explanation:

[0] takes the first letter from the input string, .lower() will normalize the character to lower, Eg. Y or y to y and N or n to n.

The while loop trigger's for the first time if the user input's the string starting with Y or y and loops until repeated so. The break condition is input string not starting with Y or y.

Rakmo
  • 1,926
  • 3
  • 19
  • 37