This is the question:

Define a function backwards (..) which receives a string of any letter, number or digit and returns one float number containing the average calculated considering all the digits in the string starting from the last position in the string and considering all digits (going backwards) until one

This is the question:

Define a function backwards (..) which receives a string of any letter, number or digit and returns one float number containing the average calculated considering all the digits in the string starting from the last position in the string and considering all digits (going backwards) until one letter is found or until reaching the start of the string (and include the first character in the string for the calculation if it is a digit) . If there are no digits in the string or if a letter is found before the first digit is found then the function should return the value 0.0.

For example, backwards("-9—6–D–4–3–") should return 3.5 because the average of 4 and 3 is 3.5.

value = backwards("-1—2–A–3–4–")

print(value)

should produce the output:

3.5

——

My fail attempt at the question:

def backwards(st):

h= len(st)-1

sum=0

while (st[h].isdigit()):

sum=sum+int(st[h])

h=h-1

s= float(b/h)

d= str(s)

return d

else:

return 0.0

can someone please help me?

sorry

value= backwards("-9—6–D–4–3–")

print(value)

should produce the output

3.5

### Best Answer:

**francesho9:** Hi Frances. Your while loop will loop from last to first while a) there are more characters, and b) current character isn't a letter. The variable d counts the number of digits.

def backwards(st):

… h=len(st)-1

… sum, d = 0, 0

… while h>=0 and not st[h].isalpha():

… … if st[h].isdigit():

… … … sum += int(st[h])

… … … d += 1

… … h -= 1

… if d>0:

… … return float(sum/d)

… return 0.0

### Other answer:

**francesho9:**

You need to grab some paper and a pencil, write Value = "D–4–3–" at the top, then MANUALLY process "value" while keeping track of what every variable contains.

I think your first problem is that a dash is not a digit, so your While loop is never entered, and h is never decremented. And, can you really have an "Else" after a "While"? I've heard of "If/Else If/Else" clauses, but never a "While/Else".

As a rookie, you've got to learn to do things by hand before you start typing the program.

**Duncan:**

If you do not have paper and pencil load your code with print commands so you can see what the values are. Your while loop only works if the h character from st is a digit. The print tells you that it is not and so the while loop is ignored….

def backwards(st):

h= len(st)-1

sum=0

print(st[h])

**Greywolf:**

WHILE loops are the same in all languages.