while 루프가 필요합니다. 첫 번째 추측이 너무 높으면 다른 기회가 생기지 만 너무 낮거나 같은지 만 테스트합니다. 추측이 너무 낮 으면 두 번째 기회가 맞아야합니다.
테스트를 계속할 필요가 없으므로 단순화 할 수 있지만 실제로 디자인 단계에서이 작업을 수행해야합니다. 여기 내 버전은 다음과 같습니다
import random
# from random import randint << no need for this line
print("Welcome to guess the number!")
question = input("Do you want to play the game? ")
if question.lower() == "yes":
print("Sweet! Let`s begin!\nGuess the number between 1 and 10!")
number = random.randint(1, 10)
guess = None # This initialises the variable
while guess != number: # This allows continual guesses
guess = int(input("Take a guess!: ")) # Only need one of these
if guess > number:
print("Your guess is too high")
elif guess < number:
print("Your guess is too low")
else: # if it isn't <or> then it must be equal!
print("Your guess was correct!")
else:
# why do another test? No need.
print("Too bad! Bye!")
# No need for quit - program will exit anyway
# but you should not use quit() in a program
# use sys.exit() instead
지금 당신이 그들이 바로 그것을 얻을 전에 플레이어가이 추측의 수를 추가하고, 마지막에 있음을 인쇄 제안!
편집 : 내 import
성명이 @Denis Ismailaj가 제공 한 것과 다르다는 것을 알게 될 것입니다. 우리는 하나만 import
이 필요하다는 데 모두 동의하지만 어떤 것에 관해서는 다른 의견을 가지고 있습니다. 내 버전이 import random
인데, 이는 random.randint
이라고 말하는 반면, 다른 쪽은 randint
입니다.
작은 프로그램에서는 선택할 수있는 프로그램이별로 없지만 프로그램은 결코 작아지지 않습니다. 6,7,8 개 이상의 모듈을 쉽게 가져올 수있는 더 큰 프로그램은 기능을 가져 오는 모듈을 추적하기가 어렵습니다. 이것은 이름 공간 오염으로 알려져 있습니다. randint
과 같이 잘 알려진 함수와 혼동하지 않을 것이며 함수의 이름을 명시 적으로 지정하면 쉽게 추적 할 수 있습니다. 개인적인 취향과 스타일에 관한 질문 일뿐입니다. 추측의 수와
추가 :
여기
import random
print("Welcome to guess the number!")
question = input("Do you want to play the game? ")
if question.lower() == "yes":
print("Sweet! Let`s begin!\nGuess the number between 1 and 10!")
number = random.randint(1, 10)
guess = None
nrGuesses = 0 # Added
# Allow for continual guesses
while guess != number and nrGuesses < 6: # Changed
guess = int(input("Take a guess!: ")) # Only need one of these
nrGuesses += 1 # Added
if guess > number:
print("Your guess is too high")
elif guess < number:
print("Your guess is too low")
else: # if it isn't <or> then it must be equal!
print("Your guess was correct!")
else:
print("Too bad! Bye!")
print("Number of guesses:", nrGuesses) # Added
안녕하세요. 큰 세계에 오신 것을 환영합니다. 우리 세계에서 "작동하지 않는다"는 예외가 발생하면 자세한 설명과 스택 추적으로 표현됩니다. – spectras
'print ('Sweet'...'들여 쓰기가 필요하고'question == "인 경우에 변경하고 싶을 때".lower()'~'question.lower() == "yes"'. – Jaco