samedi 2 octobre 2021

Python For , While loops: change if-else into loops

I am a new learner, my question is how can I convert these if-else statement into for while loops?

I try to use a stupid way and my logic is as following:

1.Enter a list of numbers

2.Use the operands in the given vector in order to do the mathematical operation

3.Output the result

Thanks.

int= [1, 6, 8, 4]  # input int
operands=['+', '-', '*'] # input operands

sum = '+'
sub = '-'
multi = '*'
divide = '/'
z = 1
temp =0
if operands[0] == sum:
    temp = int[0]+int[1]
elif operands[0] == sub:
    temp =int[0] -int[1]
elif operands[0] == multi:
    temp =int[0] *int[1]
elif operands[0] == divide:
    temp = int[0]/int[1]

if operands[1] == sum:
    temp += int[2]
elif operands[1] == sub:
    temp -= int[2]
elif operands[1] == multi:
    temp *= int[2]
elif operands[1] == divide:
    temp /= int[2]
if operands[2] == sum:
    temp += int[3]
elif operands[2] == sub:
    temp -= int[3]
elif operands[2] == multi:
    temp *= int[3]
elif operands[2] == divide:
    temp /= int[3]
    
print(temp)

Aucun commentaire:

Enregistrer un commentaire