Python: Functions in while loops -


i told functions useful when want execute same piece of code numerous times... when dealing while loops, functions necessary. i'm not sure whether call functions in while loop text - based adventure game have make school. after why need functions in loop when repeated until exit loop. teacher mark me down having unnecessary functions?

on side not well: how change variables in main routine within function... want subtract 1 num_water variable (global num_water -= 1) says invalid syntax highlighting equal symbol –

william-

consider simple c-based state machine, 1 function runs state machine, , based on current state dispatch out number of functions. state machine runs forever, in

bool done=0; while(done == no) {   switch(state)   {     case some_state: do_thing_for_this_state(); break;     case other_state: ...   } } 

a while loop conceptually no different:

while (done == no) {    things } 

if "do things" block simple, , code can read , understood, leaving in while block fine.

if "do things" block complex, ask yourself: code readable? make more sense if broken chunks, each descriptively named function? if so, have candidate calling functions in while loop.

also, if makes sense "do things" block re-used elsewhere, makes sense separate function well.

the last consideration on mind should performance. if writing mission critical code embedded processor, dsp, doing low level telecommunications or launching space vehicles, then, yes. takes small amount of cpu cycles function call. small amount of code written, there performance considerations.

i hope helps.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -