Traversing a string - Answers
Q1. Get the code working.
Q2. How this program works:
-
- A function is defined called 'forwards', that needs one argument.
- An index is set to zero.
- While the index is less than the length of the string, you set a variable to be the character in the string pointed to by the value contained in index.
- Print the variable.
- Each time you print a character in the string, you increment the index.
- To start the program, you have to enter in a string. This is stored in myWord.
- You then call the function and pass whatever is in myWord to the variable anyWord in the function.
- After the function has been called, you press any key to exit.
Q3. To modify the code to print out the length of the string entered with a message, add this line just before the WHILE loop:
print("The length of the string you entered is",len(anyWord),"\n")
Q4. To modify the code so that the letters are all on the same line but separated by a tab, change
print(letter) to this:
print(letter,end="\t")
Q5. To define an extra function to print out your string letter by letter in reverse order add this function.
def backwards(anyWord):
index = len(anyWord)
while index > 0:
letter = anyWord[index-1]
print(letter)
index = index-1
Call it using:
backwards(myWord)
Q6. To use a FOR loop to print out the letters of the string "Telephone" one by one, each on a new line, add this code to the end of your program:
print("\n\n")
for letter in "Telephone":
print (letter)