Home > Software engineering >  I'm python beginner and while writing the code, It seems too repetitive and I broke the DRY rul
I'm python beginner and while writing the code, It seems too repetitive and I broke the DRY rul

Time:12-05

choice = input("Choose Right(r) or LEfT(l): ")
if choice == "r":
    print("")
    choiceR2 = input("Choose Right(r) or LEfT(l): ")
    if choiceR2 == "r":
        print("")
        choiceR3 =input("Choose Right(r) or LEfT(l): ")
        if choiceR3 == "r":
            print("")
        elif choiceR3 == "l":
            print("")
    elif choiceR2 == "l":
        print("")
        choiceR4=input("Choose Right(r) or LEfT(l): ")
        if choiceR4 == "r":
            print("")
        elif choiceR4 == "l":
            print("")
elif choice == "l":
    print("")
    choiceL2 = input("Choose Right(r) or LEfT(l): ")
    if choiceL2 == "r":
        print("")
        choiceL3 =input("Choose Right(r) or LEfT(l): ")
        if choiceL3 == "r":
            print("")
        elif choiceL3 == "l":
            print("")
    elif choiceL2 == "l":
        print("")
        choiceL4=input("Choose Right(r) or LEfT(l): ")
        if choiceL4 == "r":
            print("")
        elif choiceL4 == "l":
            print("")

I want the user to choose to go left or right and whatever they choose, there will be another left or choice. This will go on until three time. I was writing place holders and it look very repetitive to me.

CodePudding user response:

choice = input("Choose Right(r) or LEfT(l): ")
print("")
choiceR2 = input("Choose Right(r) or LEfT(l): ")
print("")
choiceR3 = input("Choose Right(r) or LEfT(l): ")
print("")
choiceR4 = input("Choose Right(r) or LEfT(l): ")
print("")
print("Your choices were", choice, choiceR2, choiceR3, choiceR4)

this should work, you don't need to do all those if/else statements...

CodePudding user response:

As you ask user to choice 4 times.. Note you can change as per your reference

Code:-

i=1
while i<5:    
    ask=input("Choose Right(r) or LEfT(l): ")
    if ask=="r":
        print("choice " str(i) ": You choose to go Right")
    else:
        print("choice " str(i) ": You choose to go Left")
    i =1

Output:-

Choose Right(r) or LEfT(l): l
choice 1: You choose to go Left
Choose Right(r) or LEfT(l): r
choice 2: You choose to go Right
Choose Right(r) or LEfT(l): r
choice 3: You choose to go Right
Choose Right(r) or LEfT(l): l
choice 4: You choose to go Left
  • Related