Home > Mobile >  how can I shorten a lot of if statement ? python
how can I shorten a lot of if statement ? python

Time:10-15

"this code aims to display a statement if the value of the lists (s,w) == 1. if not, it moves to the next index to check the condition and print its unique statment"

if(s[0]==1):
    print("you are a !")
if(s[1]==1):
    print("high !")
if(s[2]==1):
    print("jj")
if(s[3]==1):
    print("dkkdkd")
if(s[4]==1):
    print("kkkk")

if(w[0]==1):
    print("you are a low!")
if(w[1]==1):
    print("low !")
if(w[2]==1):
    print("jj")
if(w[3]==1):
    print("dkkdkd")
if(w[4]==1):
    print("kkkk")

CodePudding user response:

rtn_msgs = ["you are a!", "high !", "jj", "ddkk", "whatever"]

for i, msg in zip(s, rtn_msgs):
   if i:
     print(msg)
     break

CodePudding user response:

If I understand it correctly, you want to trigger different actions depending on the value on each index:

One solution would be a for loop:

array = [0,0,0,1,0,1,0,1]
texts = ["text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8"]

for i in range(len(array)):
    if(array[i] == 1):
        print(texts[i])
  • Related