英文:
After printing a range I'm getting 100+ instances. Is there a way how many numbers were printed in that range before break?
问题
for i in range(1000):
my_ticket = random.randint(1, 1000)
if my_ticket % 100 == 0:
break
else:
print(my_ticket)
我正在尝试解决Eric Matthes书中包括的"Python crash course"中的彩票分析问题。我试图找出我获得指定数字的概率。
英文:
for i in range(1000):
my_ticket = random.randint(1, 1000)
if my_ticket % 100 == 0:
break
else:
print(my_ticket)
I am trying Lottery Analysis problem included in the Eric Matthes book "Python crash course". I am trying to find out the probability of me getting the number
答案1
得分: 1
你的迭代器已经在跟踪数量,break 会结束循环,所以你只需要直接在此之前打印 i
。
if my_ticket % 100 == 0:
print(i)
break
英文:
Your iterator is already tracking how many, the break ends the loop so all you have to do is literally print i
immediately prior.
if my_ticket % 100 == 0:
print(i)
break
答案2
得分: 0
你可以在 for
循环之前使用一个计数变量 c
。
每次进入 else
语句时,它将增加1。
import random
c = 0
for i in range(1000):
my_ticket = random.randint(1, 1000)
if my_ticket % 100 == 0:
break
else:
c += 1
print(my_ticket)
print("打印的总数: ", c)
英文:
You can use a counter variable c
before the forloop
.
Everytime it goes to else it will increase by 1
import random
c=0
for i in range(1000):
my_ticket = random.randint(1, 1000)
if my_ticket % 100 == 0:
break
else:
c+=1
print(my_ticket)
print("Total numbers printed: ", c)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论