krankes kind
krankes kind

Reputation: 63

How do I calculate something inside a 'for' loop?

I'm doing an assignment in which I have to move a simulated robot across the screen in a loop - I've got that part down, however, between loops, I also have to print the percentage of area covered with each movement - that's my issue.

I googled a bit and even found someone with the same problem, however, I'm not sure if I'm doing it properly.

This code was offered:

percent_complete = 0

for i in range(5):
    percent_complete += 20
    print('{}% complete'.format(percent_complete))

However, after an error, further googling revealed that only worked with certain versions

so I used this code:

percent_complete = 0

for i in range(5):
        percent_complete += 20
        print '% complete' % (percent_complete)

And, at the very least, it now executes the code, however, the output when printing is the following:

Here we go!
hello
omplete
hello
(omplete
hello
<omplete
hello
Pomplete
hello
domplete

What is the cause of this? I assume because one of the codes had to be edited, the other parts do as well, but I'm not sure what needs to be done.

Upvotes: 1

Views: 200

Answers (3)

BrenBarn
BrenBarn

Reputation: 251373

To add to/correct above answers:

The reason your first example didn't work isn't because print isn't a function, but because you left out the argument specifier. Try print('{0}% complete'.format(percent_complete)). The 0 inside the brackets is the crucial factor there.

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122346

The first version only works in Python 3 because it uses print as a function. You're probably looking for the following:

percent_complete = 0
for i in xrange(5):
    percent_complete += 20
    print '{0} complete'.format(percent_complete)

Your other code doesn't do what you intend to do because it now display the number as a string. What you want is that the number is properly converted to a string first and then displayed in the string. The function format does that for you.

You can also use Ansari's approach which explicitly specifies that percent_complete is a number (with the d specifier).

Upvotes: 2

Ansari
Ansari

Reputation: 8218

for i in range(5):
    percent_complete += 20
    print '%d complete' % (percent_complete)

You were missing the d specifier.

Upvotes: 5

Related Questions