Home > Software design >  Python For , While loops: change if-else into loops
Python For , While loops: change if-else into loops

Time:10-02

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)

CodePudding user response:

This might be helpful

lst= [1, 6, 8, 4]  # input int
operands=[' ', '-', '*'] # input operands
temp=lst[0]

for i in range(len(lst)-1):
  expr = "temp=" str(temp) operands[i] str(lst[i 1])
  exec(expr)

print(temp)

CodePudding user response:

First of all [' ', '-', '*'] these all are called operators..

You can take help from this..

lst = [1, 6, 8, 4]  # input int
operators =[' ', '-', '*'] # input operators

sum = ' '
sub = '-'
multi = '*'
divide = '/'
z = 1
temp =0
for i in range(len(lst)-1):
    if i < len(lst):
        if operators[i] == sum:
            temp = lst[i]   lst[i   1]
        elif operators[i] == sub:
            temp = lst[i] - lst[i   1]
        elif operators[i] == multi:
            temp = lst[i] * lst[i   1]
        elif operators[i] == divide:
            temp = lst[i] / lst[i   1]
print(temp)

CodePudding user response:

I think, for loops is what you need

ints = [1, 6, 8, 4]  # input int
operands = [' ', '-', '/'] # input operands

plus = ' '
minus = '-'
multi = '*'
divide = '/'
z = 1

temp = ints[0]

for i in range(len(operands)): # We need to get range from 0 to length of operands

    if operands[i] == plus:
        temp = temp   ints[i   1]
    elif operands[i] == minus:
        temp = temp - ints[i   1]
    elif operands[i] == multi:
        temp = temp * ints[i   1]
    elif operands[i] == divide:
        temp = temp / ints[i   1]

print(temp)

Also keep in mind that naming variables as int or sum is bad idea, because it's built-in python functions.

  • Related