Home > Net >  if statements with while loops
if statements with while loops

Time:01-17

I want to make it that after 10 sec you get and random letter of an random word and that the timer starts again like an infinite loop. Here is my code:

words = ["graveyard","church","apple","tree","crispy","air"]
hidden_word = random.choice(words)
hint = random.sample(hidden_word,1)

timer = 0

if timer == 10:
   print(hint)
else:
   while timer < 10:
        timer = timer   1
        time.sleep(1)
        print(timer)

I tried to place the if statement in the while loop but didn't work it only gave me errors

CodePudding user response:

This will do what you described, but it will never stop:

import time
import random

words = ["graveyard","church","apple","tree","crispy","air"]
hidden_word = random.choice(words)
hint = random.sample(hidden_word,1)

def random_select():
    while True:
        time.sleep(10)
        print(hint)

CodePudding user response:

think that if timer is 10 the block inside the while will never be executed. So you can use while-else if you want show the letter at the end

while timer < 10:
    timer = timer   1
    time.sleep(1)
    print(timer)
else:
    print(hint)
#['a']

If you want show the timer with infinite loop selection:

while True:
    for i in range(10):
        print(i)
        time.sleep(1) 
    else:
        print(random.sample(hidden_word,1))

if you don't want show the timer:

while True:
    time.sleep(10)
    print(random.sample(hidden_word,1))
  • Related