0

I started learning python few weeks ago (no prior programming knowledge) and got stuck with following issue I do not understand. Here is the code:

def run():
    count = 1
    while count<11:
        return count
        count=count+1

print run()

What confuses me is why does printing this function result in: 1? Shouldn't it print: 10?

I do not want to make a list of values from 1 to 10 (just to make myself clear), so I do not want to append the values. I just want to increase the value of my count until it reaches 10.

What am I doing wrong?

Thank you.

4

3 回答 3

5

The first thing that you do in the while loop is return the current value of count, which happens to be 1. The loop never actually runs past the first iteration. Python is indentation sensitive (and all languages that I know of are order-sensitive).

Move your return after the while loop.

def run():
    count = 1
    while count<11:
        count=count+1
    return count
于 2013-05-22T23:44:32.227 回答
1

Change to:

def run():
    count = 1
    while count<11:
        count=count+1
    return count

print run()

so you're returning the value after your loop.

于 2013-05-22T23:46:25.500 回答
0

Return ends the function early, prohibiting it from going on to the adding part.

于 2013-05-22T23:46:04.293 回答