[英]For loop and Random.Choice in python
我正在尝试编写一个 for 循环和 if 语句,我的主要目的是打印“当随机选择为红色时,有一只熊逃跑,我尝试了很多组合但没有成功
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!") ```
首先我指出你的错误,没有必要使用循环。 应用多种组合,您可以阐明您的代码及其可以做什么。 这是您的代码:
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!")
您的代码 output:借助print(x)
现在这是您的修改后的代码。
import random
Bee_Color = ["Red","Yellow", "Purple", "White"]
a=random.choice(Bee_Color)
print(a)
if a == 'Red':
print("Flee!, There is a Bear!")
这是你的output:
random.choice()当你有一个序列时使用,比如 Bee_Color 列表,并且你想随机获取一个条目。 这就是您如何使用random.choice()
获得随机颜色,然后检查随机颜色是否为红色。
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!")
如果您想随机化Bee_Color
,对其进行循环,并且仅在我们循环的颜色为红色时发出警报,您可以执行以下操作:
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!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.