0

I need to use a while loop with the choice function to terminate when a specific element in a list is randomly selected

I have successfully called the choice() function to select a random element but I get an infinite loop when I try to add a while loop

from random import *


while choice != 3:

    choice([1,2,3,4,5,6])

    print(choice)

    print('damn!')

I get an infinite loop. I need to print all randomly generated numbers that are not the condition for termination of the while loop. When the termination condition is reached a string is displayed and the program terminates

depperm
  • 10,606
  • 4
  • 43
  • 67
  • 1
    You never assigned anything to `choice`. BTW, using the same name for avariable as function name is a bad idea. – Austin Jul 08 '19 at 18:22

1 Answers1

5

There are some issues in your code.

  1. Your variable name choice shadows the function random.choice, so it's better to use another variable name like my_choice

  2. You need to assign the output of choice to the variable in order to use it.

  3. You should also avoid using star imports, i.e. import * if you are only planning to use one function from the module (Look at this question for more details on why it's bad)

Once you do those changes, your code will work fine

from random import choice

#Variable to hold choice
my_choice = 0

while my_choice != 3:

    #Assign return value of choice
    my_choice = choice([1,2,3,4,5,6])

    print(my_choice)

print('damn!')
print(my_choice)

A sample output will be

5
1
3
damn!
3
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40