PDA

View Full Version : I have a WHILE looping question for Python




larswik
Mar 1, 2009, 11:40 PM
Hello, I started to learn Python a few days ago in my attempt to learn programing. Before I move on with the book I want to understand something. I have learned enough to get in to trouble at this point. I created a number generator that you had to guess and a 'while' loop until the right answer is selected. I created this without the books help and it works but I don;t know why : )

here is the code...

# number game while in while loop

import random

num = int(raw_input("\nGuess: "))

cpu_guess = random.randrange(3) +1

while num != cpu_guess:
num = int(raw_input ("\n Wrong Guess Again: "))
cpu_guess = cpu_guess


print "Lucky Guess, it was", cpu_guess


..... Here is my question. Start of code I set up a variable called 'num' . but in order for it to work right I had to create another 'num' variable in the 'while' loop body. Does this 'num' variable over ride the first 'num' variable because it is in a loop? Or is it the same variable in both places that is being assigned the new number?

I hope I explained it OK. I only got the book last Wednesday but I want to understand what is happening before I move on. This example was not in the book but I used what I learned to create it. I just need to understand why it is working before I move on.

thanks!

-Lars



kpua
Mar 1, 2009, 11:50 PM
In Python, loop blocks don't have their own scope -- it is shared with the method's scope. So, you're not really "creating a new variable" inside the loop. The second 'num' is the same variable as the first. You're doing this correctly.

Except for the whole "cpu_guess = cpu_guess" expression... That's a completely superfluous line since like "num", the second "cpu_guess" is the same as the first.

larswik
Mar 2, 2009, 12:00 AM
I see. I created the 'cpu_guess = cpu_guess' when I created the second 'num' I thought that loop block could not see outside it's own loop. So when it reached the cpu_guess I wanted to make sure it new it was the same thing.

I tried to delete the 'cpu_guess = cpu_guess' and the code worked fine without it.

So to understand. The program runs and I enter the first number for 'num' variable. then it compares the 'num' variable and the 'cpu_guess' variable. If it is TRUE the next line 'num = int(raw_input ("\n Wrong Guess Again: "))' is going to replace the 'num' for the whole method because there can only be 1 variable that can have the same name, right?

Thanks!

-Lars

kpua
Mar 2, 2009, 09:07 AM
Right.