python - How to go back to a specific line -
print "1) add" print "2) substract" print "3) multiply" print "4) divide" print "5) exit" x=input("choose operation: ") y=input("how many numbers need operate: ") op=1 lista=[] while y>0: a=input("value"+" "+str(op)+": ") litlist=[a] lista=lista+litlist y=y-1 op=op+1 while x!=5: if x==1: b=0 n in lista: b=b+n print b elif x==2: b=0 n in lista: if lista[0]==n: b=b+n else: b=b-n print b elif x==3: b=1 n in lista: b=b*n print b elif x==4: b=1 n in lista: if lista[0]==n: b=b*n else: b=b/float(n) print b
this program designed to:
- first ask operation user wants do
- then ask how many numbers need operated
- input numbers
- and print result
i want ask operation needs done, how many numbers need operated again after printing result. input numbers , on.
i know can use input in while make ask numbers again , stop loop there 2 whiles , doesnt allow me ask y again, x. cool able go line 6 , start over
answers :)
you're looking goto
statement. in 1968, dijkstra wrote famous paper called go statement considered harmful explained why should not looking goto
.
the right thing structure code.
the simplest change this:
print "1) add" print "2) substract" print "3) multiply" print "4) divide" print "5) exit" while true: x=input("choose operation: ") # ...
however, can better. take isolated pieces of code , separate them functions can call. if 2 (or, in case, four) pieces of code identical, abstract them single function takes parameter, instead of repeating same code 4 times. , on.
but really, without functions, can rid of of repetition:
import operator print "1) add" print "2) substract" print "3) multiply" print "4) divide" print "5) exit" while true: x=input("choose operation: ") if x==5: break y=input("how many numbers need operate: ") operands=[input('value {}'.format(i+1)) in range(count)] if x==1: op, value = operator.add, 0 elif x==2: op, value = operator.sub, 0 elif x==3: op, value = operator.mul, 1 elif x==4: op, value = operator.truediv, 1 operand in operands: value = op(value, operand) print value
the reason had import operator
above add
, sub
, etc. functions. these trivial, write them yourself:
def add(x, y): return x+y # etc.
then, instead of this:
op, value = operator.add, 0
… this:
op, value = add, 0
… , same other three.
or can define them in-place lambda
:
op, value = (lambda x, y: x+y), 0
still, shouldn't either of these. simple defining add
, sub
, mul
, , truediv
is, it's simpler not define them. python comes "batteries included" reason, , if you're avoiding using them, you're making life (and lives of has read, maintain, etc. code) harder absolutely no reason.
Comments
Post a Comment