python - Why does my simple program never exit my while loop? -
it's simple number guessing game, , code follows:
from random import randint number = randint(0,20) playerguess = '0' def guess(): playerguess = input("guess number: ") if int(playerguess) == number: print("correct!") elif int(playerguess) > number: print("lower!") elif int(playerguess) < number: print("higher!") else: print("please input whole number.") while int(playerguess) != number: guess() print("------------------------------------") print("good job!")
i not understand why code not break out of while loop expected.
variables exist in 'namespace', part of code different variables recognized. new namespace made each function write. helpful because projects grow, may want reuse common variables names several different things.
in code, there 2 different variables named playerguess
. 1 in first namespace, , 1 in namespace made function guess()
. if make code this:
while int(playerguess) != number: print(playerguess, number) # added line guess()
it becomes more clear. game played added line:
0 14 guess number: >>> 10 0 14 # playerguess still 0, not 10 higher! guess number: >>> 14 0 14 # i've been told won because happens in guess() function correct! guess number: # while: loop doesn't know i've won . . .
the namespace in script outside of functions, number = randint(0,20)
is, 'global' namespace, means values can pulled here other namespace. why number
can used guess()
function- guess()
checks see if there variable number
defined in namespace, sees there not, , checks global namespace. possible change global namespace other parts of code, considered bad practice because can not obvious these changes come from. if wanted take approach though, alter code this:
from random import randint number = randint(0,20) playerguess = '0' def guess(): global playerguess # added line playerguess = input("guess number: ") . . .
and works because guess()
has been given explicit permission alter global namespace. alternative pass value care , forth between namespaces.
from random import randint number = randint(0,20) playerguess = '0' def guess(): playerguess = input("guess number: ") if int(playerguess) == number: print("correct!") elif int(playerguess) > number: print("lower!") elif int(playerguess) < number: print("higher!") else: print("please input whole number.") return playerguess # added line while int(playerguess) != number: print(playerguess, number) playerguess = guess() # added line, update playerguess in namespace
this considered better because obvious , alters variable playerguess.
Comments
Post a Comment