Thursday 15 March 2012

linux - Code not working how I expected (Python 3.x.x) -



linux - Code not working how I expected (Python 3.x.x) -

this question has reply here:

function not changing global variable 3 answers

i've beingness self teaching python , i'm making first effort @ game. thought user must guess reply (integer) code not yet finish first half won't work.

my code:

highest = 10 reply = 7 guess = int(input("what guess?")) def guessinggame(): print("try 1 time again please") guess = int(input("what guess?")) while (int(guess) != answer): if (int(guess) < answer): print ("answer higher!") guessinggame(); elif (int(guess) > answer): print ("answer lower!") guessinggame();

no matter whether come in value less answer(which 7) or higher, ;"the reply higher!" doing wrong? thanks!

edit: i'm aware code might incredibly buggy/poorly written , love criticism/improvements.

the guess variable edit in guessinggame not same 1 comparing in while loop.

adding global guess top of guessinggamefunction should solve it.

for future reference, if not behaving, it's useful print variables @ various stages see things are. (for larger programs debugger more useful on stuff this, printing fine).

edit: respect criticism/improvements comment:

functions should named after do. guessinggame should named updateuserguess. rather rely on globals think i'd create function homecoming guess , assign value guess variable outside function.

the elif status not needed. if guess isn't < answer , not equal must higher

you phone call guessinggame whether guess higher or lower can moved out of if/else statements

you casting guess int every time utilize (in guessinggame function , 1 time again in each of conditions). nil wrong it's not necessary. if it's stored int, utilize one.

python linux python-3.x python-3.4

No comments:

Post a Comment