Home > Software engineering >  For loop and Random.Choice in python
For loop and Random.Choice in python

Time:08-24

i am trying to write a for loop and if statement, my main aim is to print "Flee there is a bear when and if the random choice is red, i have tried many combination with no success

import random

Bee_Color = ["Red","Yellow", "Purple", "White"]

random.choice(Bee_Color)
        for x in random.choice(Bee_Color):
            
            if x == Bee_Color[0]:
                
                print("Flee!, There is a Bear!") ```

CodePudding user response:

First I point out your mistakes, there is no need to use a loop. Apply multiple combinations you clarify your code and what it can do. Here is your Code:

import random
Bee_Color = ["Red","Yellow", "Purple", "White"]
random.choice(Bee_Color)#useless line of code
for x in random.choice(Bee_Color):#useless line of code
    print(x)# to see what your code can do
    if x == Bee_Color[0]:
        print("Flee!, There is a Bear!")

your Codes output: With the help of print(x)

enter image description here

Now here is your Modified Code.

import random
Bee_Color = ["Red","Yellow", "Purple", "White"]
a=random.choice(Bee_Color)
print(a)
if a == 'Red':
    print("Flee!, There is a Bear!")

and here is your output:

enter image description here

CodePudding user response:

random.choice() is used when you have a sequence, like the Bee_Color list, and you want to randomly get one entry. This is how you would use random.choice() to get a random color, then check if the random color is red.

import random

Bee_Color = ["Red", "Yellow", "Purple", "White"]

random_color = random.choice(Bee_Color)
print("Bee color is:", random_color)

if random_color == Bee_Color[0]:
    print("Flee!, There is a Bear!")

If you wanted to randomize Bee_Color, loop over it, and only alert when the color we're looping over is red, you could do something like:

import random

Bee_Color = ["Red", "Yellow", "Purple", "White"]

# random.shuffle() will change the position of "Red",
# so we need to store it in alert_color
alert_color = Bee_Color[0]

# Randomize the Bee_Color list
random.shuffle(Bee_Color)

for x in Bee_Color:
    print("Bee color is:", x)
    if x == alert_color:
        print("Flee!, There is a Bear!")
  • Related