简体   繁体   中英

How do you make a while loop in python that stops two variables with the same answer?

I'm trying to make a 'who wants to be a millionaire' style program with random questions, random answers in random places (in Python). I'm struggling to form a while loop that repeats itself so that two variables are never the same. My loop (that clearly doesn't work) is:

while rnd4 == rnd2:
    rnd4 = random.randint(1,3)
    break

In context of my current program:

if rnd2 == 1:
    position1 = answer      #the random question has already been printed and the     
                            #answer set                   
elif rnd2 == 2:
    position2 = answer
elif rnd2 == 3:
    position3 = answer

rnd3 = random.randint(1,4)


rnd4 = random.randint(1,3)


while rnd3 == rnd1:
    rnd3 = random.randint(1,4)     #these loops are meant to mean that the same 
    break                          #answer is never repeated twice + the same  
while rnd4 == rnd2:                #position is never overwritten
    rnd4 = random.randint(1,3)
    break
if rnd3 == 1:
    if rnd4 == 1:
        position1 = (no1[1])
    elif rnd4 == 2:
        position2 = (no1[1])
    elif rnd4 == 3:
        position3 = (no1[1]) 

... (code skipped)

print (position1)
print (position2)
print (position3)  

Due to the random nature of the program it has been difficult to test but I'm expecting a format like:

q1

answer
()  #only two of the positions have had code written for them yet
random answer

Or a combination of the above. (basically one right answer and one wrong answer in different positions) Ocassionally I get:

q1

answer
answer
()

or

q1

random answer
()
()

So this is obviously wrong with sometimes the same answer printed twice or the wrong answer overwriting the right one.

Apologies for such a long drawn out question with probably a very simple answer (how to fix the loop) but I know I'm not supposed to ask for code!!

Thanks a lot!

In Your Example break statement in while loops seems to be unnecessary.

this brake ends loop even if numbers are equal.

As I understand main ussue is to generate rnd1 ... rnd4

can You try random.shuffle for these purposes

a = range(1, 5)
random.shuffle(a)
rnd1, rnd2, rnd3, rnd4 = a

random.shuffle shuffle the sequence x in place. so one can generate sequence with desired values and shuffle it

Delete those break statements and it should work.

Assume your two variables are equal. Then you enter the loop, and you create a new value for rnd4. The next step would be to check if the 2 variables are now different, if not, repeat. But before you get to the while clause again you break out of the loop. So effectively you run the loop body at most once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM