frivolousplasterer
frivolousplasterer

Reputation: 61

Why is this range variable declared before being used?

I have just started working through Invent Your Own Computer Games with Python. This is the sample code for Chapter 3:

1   # This is a Guess the Number game.      
2   import random       
3   
4   guessesTaken = 0        
5           
6   print('Hello! What is your name?')      
7   myName = input()        
8           
9   number = random.randint(1, 20)      
10  print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')      
11          
12  for guessesTaken in range(6):       
13      print('Take a guess.') # Four spaces in front of "print"        
14      guess = input()     
15      guess = int(guess)      
16          
17      if guess < number:      
18          print('Your guess is too low.') # Eight spaces in front of "print"      
19          
20      if guess > number:      
21          print('Your guess is too high.')        
22          
23      if guess == number:     
24          break       
25          
26  if guess == number:     
27      guessesTaken = str(guessesTaken + 1)        
28      print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')       
29          
30  if guess != number:     
31      number = str(number)        
32      print('Nope. The number I was thinking of was ' + number + '.') 

Why is guessesTaken declared at the start when variables can apparently be declared at any time in Python?

I have tried it both without that line entirely and also having changed guessesTaken to numbers other than 0. In both cases, it appears to work exactly the same, as the range function seems to manage guessesTaken.

The book states:

Line 4 creates a new variable named guessesTaken :

4. guessesTaken = 0

You’ll store the number of guesses the player has made in this variable. Since the player hasn’t made any guesses at this point in the program, store the integer 0 here.

This does not justify the line's existence to me.

Upvotes: 6

Views: 176

Answers (3)

Prune
Prune

Reputation: 77847

First of all, Python does not require declaring variables; they inherit their types from context, and can change on a whim. The line you refer to defines guessesTaken; there is no declaration as such. In contrast, global would declare a variable.

As Sam already said, the line that confuses you (good for you!) is useless: the for statement defines the variable adequately for its usage there; any value given to it in line 4 is destroyed; it could as easily be

guessesTaken = ["My list", 7, True, "of useless data"]

The value of guessesTaken is not used before the loop, and the name is redefined as a string (with a text value one higher) after the loop -- sloppy variable use. Also, note how there are independent, exclusive and exhaustive if statements -- these should be if - elif - else constructs for cleanliness and efficiency.

In short, this is not a good example from which to learn programming style.

Upvotes: 3

Adam Smith
Adam Smith

Reputation: 54203

There's no great reason for it, but regardless this is kind of a wonky structure for Python code. Phrasing the code this way requires that loop variables remain in scope after the loop exits, which (while accurate in both Py2 and Py3) is kind of mentally taxing on the programming. I can't be the only experienced Python programmer who thinks:

for x in some_iter:
    frobnicate(x)

# x is undefined here

For that reason I would avoid this structure completely, instead preferring:

for guess_number in range(MAX_GUESSES):
    guess = int(input("Guess: "))
    if guess == number:
        # it took guess_number+1 guesses. Let the player know and:
        break  # or return
    elif guess > number:
        # too high, tell the player
    elif guess < number:
        # too low, tell the player
else:
    # you trigger the for/else block when you don't break from a for loop
    # so getting here means you've failed to guess in MAX_GUESSES tries
    # tell the player and handle it

Upvotes: 2

Sam
Sam

Reputation: 1552

The declaration before the loop serves no purpose. It is only there for readability or understanding of the code.

Upvotes: 3

Related Questions