Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

list - How do I make 2 or more variable never be equal in Python?

I'm new at programming and I've heard that one thing to do to improve your programming skills is try to create some projects, just for fun, and I'm trying to create some kind of Q&A game using the random function to shuffle the alternatives (A, B, C, D, E) at each try. Here is an example of what I want to do.

import random

list = [1, 2, 3, 4, 5]

n1 = (random.choice(list))
n2 = (random.choice(list))
n3 = (random.choice(list))
n4 = (random.choice(list))
n5 = (random.choice(list))

print("Question 1 - What is the result of 2+2?")

print("A){}.".format(n1))
print("B){}.".format(n2))
print("C){}.".format(n3))
print("D){}.".format(n4))
print("E){}.".format(n5))

The output is:

Question 1 - What is the result of 2+2?

A)4.
B)1.
C)2.
D)2.
E)4.

Process finished with exit code 0

I know its barely impossible to make each alternative be different every time with this code, and my question is: How can I make sure the alternatives will never be equal?

question from:https://stackoverflow.com/questions/65948540/how-do-i-make-2-or-more-variable-never-be-equal-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try changing:

n1 = (random.choice(list))
n2 = (random.choice(list))
n3 = (random.choice(list))
n4 = (random.choice(list))
n5 = (random.choice(list))

To:

n1, n2, n3, n4, n5 = random.sample(list, 5)

random.sample never gives duplicate values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...