Exercise 1: Write a while loop that starts at the last
character in the string and works its way backwards to
the first character in the string, printing each letter
on a separate line, except backwards.
fruit = "banana"
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
Another way to write a traversal is with a for loop:
for char in fruit:
print(char)
str_fruit = "orange"
index = -1
len_str_fruit = -len(str_fruit)
while index >= len_str_fruit:
print(str_fruit[index])
index = index - 1
#OR
str_fruit = "orange"
for fruit in range(len(str_fruit)): print(str_fruit[-(fruit+1)])
Exercise 3: Encapsulate this code in a function named
count, and generalize it so that it accepts the string
and the letter as arguments.
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
def count(string, letter):
counter = 0
for character in string:
if character == letter:
counter = counter + 1
print("\n>>> No. of times", letter, "appears = ", counter)
inp_str = input("Enter your string: ")
inp_char = input("Enter the characters you want to be counted: ")
count(inp_str, inp_char)
# OR
def count(string, letter):
start_pos = 0
len_letter = len(letter)
letter_pos_list = list()
while True:
letter_pos = string.find(letter, start_pos)
if letter_pos == -1:
break
start_pos = letter_pos + len_letter
letter_pos_list.append(letter_pos)
print(len(letter_pos_list))
inp_str = input("Enter your string: ")
inp_char = input("Enter the characters you want to be counted: ")
count(inp_str, inp_char)
Exercise 5: Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.
str = "X-DSPAM-Confidence:0.8475"
start_pos = str.find(":")
desired_output = str[(start_pos + 1):]
fl_output = float(desired_output)
print("\n>>>Desired output: ", desired_output, "\n>>>",type(fl_output))