我有一个随机函数,它用1到11之间的随机数创建两个列表。
我想检查这两个随机数列表中是否包含9到11之间的任何数字。
如果列表中包含数字9-11,我希望程序打印一条消息,然后停止迭代。换句话说,我希望消息显示一次。
我尝试了以下方法,但代码在执行过程中多次打印消息。
split = [9,10,11]
container = []
for count in range (2):
rand_num = random.randrange (1, 11 + 1)
print(f"player_1 card is : {rand_num}")
container.append(rand_num)
for place in container:
if place in split :
print("you can go double down")
发布于 2021-01-30 11:32:04
您所需要的只是循环中的一条break
语句。当满足某一条件时,break
它。
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
输出:
s
t
r
The end
在breaking out of loops in Python上阅读这篇文章。
这是关于使用无限循环的another good article
发布于 2021-01-30 11:27:54
每次运行for循环时都会检查if语句。在第一次找到循环后,可以使用break语句退出循环。例如:
for place in container:
if place in split:
print("you can go double down")
break
发布于 2021-01-30 12:12:20
试试这个:
import random
split = [9,10,11]
container = []
for i in range (1):
rand_num = random.sample(range(1,12),2)
print ( f"player_1 card is : {rand_num}" )
container.append(rand_num)
for place in split:
if place in rand_num :
print("you can go double down")
https://stackoverflow.com/questions/65964309
复制相似问题