For loop behavior in python -
i have these 2 function calculate numbers of animals based upon input in function. want know behavior of function. if input 20 heads , 56 legs 8 pigs , 12 chickens ultimately. there questions.
def solve(numlegs, numheads): numchick in range(0, numheads + 1): #we have got 12 chickens here? numpigs = numheads - numchicks totlegs = 4 * numpigs + 2* numchicks if totlegs == numlegs: return [numpigs, numchicks] return[none, none] def barnyard(): heads = int(raw_input('enter number of heads:')) legs = int(raw_input('enter number of legs:')) pigs, chickens = solve(legs, heads) if pigs = none: print 'there no solution' else: print 'number of pigs:' , pigs pirnt 'number of chickes:', chickens
i stuck here for numchick in range(0, numheads + 1):
. if number chickens in loop line can proceed calculating number of pigs right? how 12 chickens line commented above? please consider number of inputs
for numchick in range(0, numheads + 1)://what doing?
is loop loop 0
until numheads + 1
. if numheads
10, loop 0 until 10, if numheads
100, loop 0 until 100
see python loop function: https://wiki.python.org/moin/forloop
and range function: https://docs.python.org/2/library/functions.html#range
e.g.
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
each time loops, numchick
takes respective value, i.e. numchick
take values starting 0: 0, 1, 2, ... , numheads
Comments
Post a Comment