2016-10-15 3 views
0

숫자 형식의 게임을 추측하기 시작했습니다. 나는이 프로그램을 실행하면 ... 완벽 흐름 중 하나가 작동하지 않습니다 중 하나스크립트를 실행할 때의 이상한 행동

import random 
from random import randint 

print("Welcome to guess the number!\nDo you want to play the game?") 

question = input("") 

if question == "Yes".lower(): 
print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") 

    number = random.randint(1, 10) 
    guess = int(input("Take a guess!\n")) 

    if guess > number: 
     print("Your guess is too high") 
     guess = int(input("Take a guess!\n")) 

    if guess < number: 
     print("Your guess is too low") 
     guess = int(input("Take a guess!\n")) 

    if guess == number: 
     print("Your guess was correct!") 

elif question == "No".lower(): 
    print("Too bad! Bye!") 
    quit() 

나는 그것 때문에 코드의 발생, 또는 pycharm 탓인지 전혀 생각!

+2

안녕하세요. 큰 세계에 오신 것을 환영합니다. 우리 세계에서 "작동하지 않는다"는 예외가 발생하면 자세한 설명과 스택 추적으로 표현됩니다. – spectras

+0

'print ('Sweet'...'들여 쓰기가 필요하고'question == "인 경우에 변경하고 싶을 때".lower()'~'question.lower() == "yes"'. – Jaco

답변

0

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 
+0

os.exit()을 사용할 때이 문제가 발생합니다 :이 검사는 해결해야하는 이름을 감지하지만 그렇지 않은 경우 이름을 감지합니다. 동적 디스패치 및 오리 입력으로 인해, 이것은 제한적이지만 유용한 경우에 가능하며, 최상위 레벨 및 클래스 레벨 항목은 인스턴스 항목보다 더 잘 지원됩니다. sys.exit()를 사용하려고했으나 같은 결과가 나타납니다. – ImaNoob

+0

'sys.exit()'아마도 PyCharm에서 온 것일까?'quit()'는 대화식 파이썬에서만 사용되어야한다. - http://stackoverflow.com/questions/6501121/difference-between-exit-and-sys를 보라. -exit-in-python ('exit()'과'quit()'도 같은 일을합니다). – cdarke

+0

또한 추측의 번호 I이 작성 triet : – ImaNoob

-1

이미 답변으로 제공되는이 개 테마의 변형이다.
이 옵션에서 추측 부분은 사용자가 지루할 때까지 반복적으로 게임을하는 옵션을 제공하는 기능으로 정의됩니다! 제공되는 다른 옵션은 사용자가 "예"또는 "아니오"를 입력하지 않고 "y"또는 "n"으로 시작하는 것입니다.

from random import randint 

def game(): 
    print("Guess the number between 1 and 10!") 
    number = randint(1, 10) 
    guess = None 
    while guess != number: 
     guess = int(input("Take a guess!\n")) 
     if guess > number: 
      print("Your guess is too high") 
     elif guess < number: 
      print("Your guess is too low") 
     else: 
      print("Your guess was correct!") 

    return input("Another game y/n ") #return a value which determines if the game will be repeated 

print("Welcome to guess the number!\nDo you want to play the game?") 
question = input("") 
repeat = "y" # define repeat so that the first iteration happens 

if question.lower().startswith('y') == True: 
    print("Sweet! Let`s begin!") 
    while repeat.lower().startswith('y') == True: # while repeat == "y" keep playing 
     repeat = game() # play the game and set the repeat variable to what is returned 
print("Bye Bye!")