Python Arena
Step 4 of 6

Counting from the end

word[len(word) - 1] gets the last character, but Python has a shorter way: negative indexes, which count from the end. The index -1 is the last character, -2 the one before it, and so on:

 p   y   t   h   o   n
-6  -5  -4  -3  -2  -1
word = "python"
print(word[-1])
print(word[-2])
print(word[-6])
Output
n
o
p

word[-1] is always the same character as word[len(word) - 1], whatever the length of the word. Negative indexes run out too: "python" has nothing at the index -7, so word[-7] is an IndexError, just as word[6] is.

Empty input

When the user just presses Enter, input gives the empty string. It has no characters, so it has no first or last character, and every index is out of range:

This program makes an English noun plural in a simple way: a word that ends in s, such as bus, gets es, and any other word gets s. Pressing Enter without a word stops it:

word = input("Word: ")
if word[-1] == "s":
    print(word + "es")
else:
    print(word + "s")
Input
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    if word[-1] == "s":
       ~~~~^^^^
IndexError: string index out of range

When a program can get an empty string, check the length before you use an index. Here the check comes first, so by the time Python gets to word[-1], the word has at least one character:

word = input("Word: ")
if len(word) == 0:
    print("No word, no plural")
elif word[-1] == "s":
    print(word + "es")
else:
    print(word + "s")
Input
Output
Word:
No word, no plural

Backwards through a string

A loop can go through a string from its end. Here the index starts at -1 and goes down by one in every round, until it has passed the first character, which is at -len(word):

word = "stressed"
backwards = ""
index = -1
while index >= -len(word):
    backwards += word[index]
    index -= 1
print(backwards)
Output
desserts

stressed has 8 characters, so -len(word) is -8. The loop runs with the indexes -1, -2 and so on down to -8, adding one character in every round, and ends when index is -9. The same works with ordinary indexes: start from len(word) - 1, the last index, and go down while the index is at least 0.

Your task

Challenge 1 of 3

Fill in the blanks so the program prints the first and the last character of the word typed in. Use a negative index for the last one.

Word: banana
First: b
Last: a

Challenge 2

A palindrome is a word that reads the same backwards, like level or racecar. Write a program that asks for a word and says whether it's a palindrome.

Word: level
level is a palindrome

For a word that isn't, it prints, for example, python is not a palindrome.

Challenge 3

Write a program that asks for a sentence and looks at its last character. If it's ?, the program prints A question; if it's !, it prints An exclamation; otherwise it prints A statement. If the user types nothing at all, it prints Nothing to read.

Sentence: Is it raining?
A question