'Loop is not reaching 100

I am not getting why my score not reaching 100 and breaking out

Code:

flag = 0 

while True:
 
  p1 = 0

  if flag == 0:

    p1_d = random.randint(1, 6)
    p1_s = p1 + p1_d # 0 + 3  : 3 
    p1 = p1 + p1_d

    print(p1_s)

    if p1_s == 100:
      print(p1_s)
      break

The p1_s value is not reaching 100

Following is the Output I am getting

1
2
3
1
5
1
2
3
1
5

if flag is zero it will enter into if condition keep adding the random values , until it reaches 100 and break

I want to write a code which could take random value and keep incrementing until it reach max 100 and exit code



Solution 1:[1]

This will solve your purpose of making p1_s reach 100.

import random

flag = 0
p1 = 0 # You need to move this outside of the while loop
while True:
  if flag == 0:
    p1_d = random.randint(1, 6)
    p1_s = p1 + p1_d # 0 + 3  : 3 
    p1 = p1 + p1_d

    print(p1_s)

    if p1_s >= 100: # Also, check for greater than 100
      print(p1_s)
      break

Sample Output:

4
9
13
14
19
25
27
33
39
45
50
53
59
63
64
67
70
75
81
84
86
87
91
93
96
100
100

What you were doing wrong?

  1. Setting p1 = 0 on every loop or iteration and this is why p1 was getting reset to 0.
  2. Checking for p1_s == 0 instead of p1_s >= 100. This will check if p1_s is greater than or equal to 100. Since you are adding a random integer to p1_s every time it's highly unlikely that p1_s will be equal to 100.

Solution 2:[2]

Let's track a couple times in the loop:

  1. p1 = 0
  2. p1_d = 5 lets say 5 this time
  3. p1_s = 0 + 5 = 5
  4. p1 = 0 + 5 = 5
  5. prints p1_s (5)
  6. p1_s isn't 100

...

  1. p1 = 0
  2. p1_d = 3 lets say 3 this time
  3. p1_s = 0 + 3
  4. p1 = 0 + 3
  5. prints p1_s (3)
  6. p1_s isn't 100

...

Have you seen the issue yet?

Solution 3:[3]

I see you are setting p1 = 0 in every iteration. Hence it is impossible for it to reach a 100 because it will always be of the value of random number

(But even if it is remove) You are adding random numbers again and again. p1_s will always be of greater value than it was an iteration before.

There is no guarantee that it will become 100 in increments. Also, at it is incrementing without any condition if exactly 100 didn't occur it will run forever to an infinite iterations. Probability of getting exactly 100 by these random increments is very very low.

I don't know what you want to achieve but try considering alternate method for what you are doing or try adding some condition that are more likely to occur(keeping your actual problem in mind)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhyuday Vaish
Solution 2
Solution 3