2

I need my outputs to be in 3 decimals

def main():

    n = eval(input("Enter the number of random steps: "))
    t = eval(input("Enter the number of trials: "))

    pos = 0
    totalPosition = 0
    totalSum = 0
    L = list()

    import random
    A = [-1, 1]

    for x in range(t):
        pos = 0
        for y in range(n):
            step = random.choice(A)
            pos += step


        totalPosition += abs(pos)
        totalSum += pos**2

    pos1 = totalPosition/t
    totalSum /= t
    totalSum = totalSum**0.5


    print("The average distance from the starting point is a %.3f", % pos1)
    print("The RMS distance from the starting point is %.3f", % totalSum)

main()

I keep getting syntax errors whether I try to use both the '%' character and the {0:.3f} .format(pos1) method. Anybody know where I'm going wrong?

Thanks!

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Yotam Kasznik
  • 55
  • 2
  • 2
  • 9

4 Answers4

2

You don't need , in print function just % is enough for example:

print("The RMS distance from the starting point is %.3f", % totalSum)
                                                        ^ remove this ,

like:

print("The RMS distance from the starting point is %.3f" % totalSum)
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • @YotamKasznik Your welcome Yotam, I believe you will like this to read this [**String formatting in Python**](http://stackoverflow.com/questions/517355/string-formatting-in-python) ... interesting – Grijesh Chauhan May 30 '13 at 19:28
1

For string interpolation, you need to put the % operator right behind the format string:

print ("The average distance from the starting point is a %.3f" % pos1)

it is a bit more obvious if you use the more modern format way:

print ("The average distance from the starting point is a {:.3f}".format(pos1))
Thomas Fenzl
  • 4,342
  • 1
  • 17
  • 25
0

You have commas between the string literal and the % sign. Remove those.

print("The average distance from the starting point is a %.3f" % pos1)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

You're getting the print and formatting confused:

print("The average distance from the starting point is a %.3f" % pos1)

You should really prefer the new style formatting though:

print("Whatever {:.3f}".format(pos1))

Or, if you really wanted:

print("Whatever", format(pos1, '.3f'))
Jon Clements
  • 138,671
  • 33
  • 247
  • 280