Home > front end >  Why isnt my loop completing the print function
Why isnt my loop completing the print function

Time:06-29

Im new to python can anyone please exsplain why my code isnt working all that happens when i run it is it prits out the numbers even when it prints a 10 it wont print done please help

while True:
    a = 10
    from random import seed
    from random import randint
    seed(1)
    for _ in range(10):
            b = randint(0, 10)
            print(b)
    if b == a:
        print('done')    
  
    else:
        continue

CodePudding user response:

The if statement should be indented in line with the for loop.

from random import randint, seed
loop = True
seed(1)
while loop:
    a = 10
    for _ in range(10):
        b = randint(0, 10)
        print(b)
        if b == a:
            print('done')
            loop = False
            break

I also changed some things like the seed(1) (moved out of loop) and continue (replaced with break)

CodePudding user response:

Okay so based on the code and the explanation given, I assume that you want the above script to generate a set of numbers randomly until a 10 gets printed. Once a 10 is printed you want to the program to stop.

For that you need to do something like this:

from random import seed
from random import randint

seed(1)

break_value = 10
b = 0

# The loop runs until b hits the designated break value (10)
while (b != break_value):
    # Every loop a new b value is generated and output
    b = randint(0, 10)
    print(b)

# After the while loop terminates, we print done
print("done")

Output:

2
9
1
4
1
7
7
7
10
done

CodePudding user response:

Well, you just have to use a post condition while loop so when val =10 it breaks. Also, the print("done") should be outside the loop so as to avoid repetition

import random as r #imported module
x = True 
stop_value = 10 #target value
while x:
    val = r.randint(1,10)
    print(val)
    if val == stop_value:
        x = False #this break the while loop when val = target value
print("done")
  • Related