죄송합니다. while 루프에 대해 조사해 보았습니다. 찾은 예제는별로 도움이되지 못했습니다. 나는 사람들 예제가 아닌 개념을 이해하는 데 어려움을 겪고있다. 나는 파이썬에 익숙하지 않으며 대부분의 튜토리얼은 다른 시나리오에서 while 루프를 사용한다. 그래서 여기 내 코드입니다 :while 루프를 사용하여 코드를 작성하는 방법은 무엇입니까?
# This is a guess the number game.
import random
# Ask the user what their name is
print ('Hello. What is your name?')
name = input()
# Ask the user if they would like to play a game.
# If user confirms, game continues
# If user denies, game ends
print ('Hi ' + name + ' It is nice to meet you.')
print ('Would you like to play a game with me?')
answer = input()
confirm = ['Yes', 'yes',' Y', 'y', 'Yea', 'yea', 'Yeah', 'yeah', 'Yup', 'yup']
deny = ['No', 'no', 'N', 'n', 'Nope', 'nope', 'Nah', 'nah']
if answer in confirm:
print ('Great! Let\'s get started!')
elif answer in deny:
print ('I am sorry to hear that. Maybe next time? Goodbye') + exit()
print ('I am thinking of a number between 1 and 20.')
print ('Can you guess what the number is?')
secretNumber = random.randint (1, 20)
print('DEBUG: The secret number is ' + str(secretNumber)) # DEBUG
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is to low.')
elif guess > secretNumber:
print ('Your guess is to high!')
else:
break # This condition is for the correct guess!
if guess == secretNumber:
print ('Good job, ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
play_again = input()
if play_again in confirm:
print('# Put code to make game restart')
elif play_again in deny:
print ('Thanks for playing!')
exit()
나는 "확인에 play_again 경우"에서 (내가 필요한 먹으 렴 생각하기 때문에, 나없는 경우 계몽하시기 바랍니다) while 루프를 사용하고자하는 문은 그것을 만들 수 반환 다시 "나는 1과 20 사이의 수를 생각하고있다"고 회상한다. 그렇게하면 사용자가 선택한 경우 계속해서 게임을 할 수 있습니다.
미리 감사드립니다. 나는 또한 최신 Python을 사용하고있다.
은 입력과 같은 단축 할 수 중복 코드를 많이도 있습니다이 :) 게시하기 전에 코드를 소개하세요 – Li357