-4

I'm trying to write a simple program that tells you how many digits of e (from mathematics) are equal to your approximation...it works if there are one or more digits incorrect, but if not this pops up:

Traceback (most recent call last):
  File "&^%%@%#", line 5, in <module>
    while e[c] == ue[c]:
IndexError: string index out of range

I have tried if statements, more while statements and more functions, but it won't work. Here's the code:

e = str(2.7182818284590452353602874713526624977572470936999595)
ue = str(input("Copy in your version of e and this will check it ! "))

c = 0
while e[c] == ue[c]:
    if c < len(ue):
        c = c + 1
else:
    break

print(c - 1)

If I input 2.79 it shows up with 3. Though if I input, say 2.718 and all digits are correct it says this:

IndexError: string index out of range (Coming from line 5)

(Also this is my first time on Stack Overflow; so cut me some slack.)

  • explain what are you trying to do here –  Aug 02 '19 at 01:36
  • Your indentation of the `else` line is incorrect. It should be aligned with `if`. Currently it is a [`while..else`](https://stackoverflow.com/questions/3295938/else-clause-on-python-while-statement) block. – Selcuk Aug 02 '19 at 01:37
  • 1
    Note how you're checking `len(ue)` *after* doing `ue[c]` If `c` is out of bounds, it will cause an error there. You need to do the check before trying to index. – Carcigenicate Aug 02 '19 at 01:37
  • Selcuk so true, thanks! – Caden Stone Aug 02 '19 at 14:08
  • Ok, to clarify I'm writing a program that sees how many digits are correct in your e (may be found in another program) compared to the actual e (found elsewhere). – Caden Stone Aug 02 '19 at 14:25
  • Problem is this program only works when a digit is INCORRECT like: 2.711 – Caden Stone Aug 02 '19 at 14:26
  • If it's like 2.718 (*all digits are CORRECT*) it crashes, so I want to make it NOT crash and just give me c – Caden Stone Aug 02 '19 at 15:05

1 Answers1

0

Your problem is that your variables e and ue doens't have the same length.

When you are converting float into string you are losing precision.

e = str(2.7182818284590452353602874713526624977572470936999595)
ue = input("Copy in your version of e and this will check it ! ")

print (e) # 2.718281828459045
print (ue) # 2.7182818284590452353602874713526624977572470936999595

Define a string with double or single quotes:

e = '2.7182818284590452353602874713526624977572470936999595'
ue = input("Copy in your version of e and this will check it ! ")

c = 0
while e[c] == ue[c]:
    if c < len(ue)-1:
        c = c + 1
    else:
        break
print(c - 1)

output:

Copy in your version of e and this will check it ! 2.7182818284590452353602874713526624977572470936999595
52
ncica
  • 7,015
  • 1
  • 15
  • 37