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.

1
  • 5
    You return before the loop has a chance to fire off. Commented May 22, 2013 at 23:44

3 Answers 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
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you for the reply. But I still do not understand the principle. Is "return" the equivalent of a "break"?
@stgeorge No, return leaves the current function call. break can be used to exit a certain scope. You can read more about it in the Python grammar.
Sorry that's too much advanced for me (Python grammar explanation). Thank you though.
@stgeorge return exits the function and returns (sends) a value. In your case, you want to print something, and what is it that you will print? You will print the value that return sends.
Thank you for the reply ribot. Still the difference between "return" and "break" confuses me. So whenever the script gets to "return" it ends the function. And whenever the loop gets to the "break" it ends the loop (no matter if the loop is inside of function or not)?
|
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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.