Помогите разобраться в Цикле, while
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word
points = 50
# create a jumbled version of the word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
# start the game
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
print(word)
guess = input("\nYour guess(if you need advance press 1): ")
if guess == '1':
points -= 5
if correct == 'python':
print("pyt")
elif correct == 'jumble':
print("jum")
elif correct == 'easy':
print("ea")
elif correct == 'difficult':
print("diff")
elif correct == 'answer':
print("ans")
elif correct == 'xylophone':
print("xylo")
else:
print("Sorry, that's not it.")
while guess != correct and guess != "":
guess = input("Your guess(if you need advance press 1): ")
if guess == '1':
points -= 5
if correct == 'python':
print("pyt")
elif correct == 'jumble':
print("jum")
elif correct == 'easy':
print("ea")
elif correct == 'difficult':
print("diff")
elif correct == 'answer':
print("ans")
elif correct == 'xylophone':
print("xylo")
if guess == '1':
continue
print("Sorry, that's not it.")
if guess == correct:
print("That's it! You guessed it!\n")
print(f"Thanks for playing. Your score:{points}")
input("\n\nPress the enter key to exit.")
Это игра, которая разбрасывает буквы в слове и просит разгадать что за слово, я не могу разобраться что происходит в этом цикле, очень прошу- простыми словами и детально обьясните что происходит здесь:
# create a jumbled version of the word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
Ответы (1 шт):
Автор решения: Wairua
→ Ссылка
jumble = "" # объявляем пустую переменную типа str
while word: # до тех пор пока в слове осталась хотя-бы одна буква
# (Не пустая строка == True, пустая == False)
position = random.randrange(len(word)) # определяем рандомную позицию
jumble += word[position] # к переменной jumble добавляем симовл находящийся в позиции position
word = word[:position] + word[position + 1:] # делаем word равным части word до position + часть слова после position
# тоесть удаляем из него символ с индексом position
# и так пока word не станет == ''
В догонку к коментарию:
lword = list(word)
random.shuffle(lword)
jumble = ''.join(lword)
Сделает тоже самое