After printing a range I'm getting 100+ instances. Is there a way how many numbers were printed in that range before break?

huangapple go评论43阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年3月7日 22:02:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定