2014-09-18 3 views
0

Цель этой игры - угадать число в трех попытках, и если вы это исправите, поздравите вас, и если вы ошибетесь, скажите «Нет». Я думаю, что у меня есть код правильно, но я новичок в программировании и не уверен. Я тестирую его, если он работает, но это может занять ОЧЕНЬ долгое время. Любая помощь приветствуется!Что касается Python Guessing Game

# Guess My Number 
# 
# The computer picks a random number between 1 and 100 
# The player tries to guess it and the computer lets 
# the player know if the guess is too high, too low 
# or right on the money 

import random 

print("\tWelcome to 'Guess My Number'!") 
print("\nI'm thinking of a number between 1 and 100.") 
print("Try to guess it in as few attempts as possible.\n") 

# set the initial values 
the_number = random.randint(1, 100) 
guess = int(input("Take a guess: ")) 
tries = 1 

# guessing loop 
while guess != the_number: 
    if guess > the_number: 
     print("Lower...") 
    elif tries == 3: 
     break 
    else: 
     print("Higher...") 

    guess = int(input("Take a guess: ")) 
    tries += 1 

if guess == the_number: 
    print("You guessed it! The number was", the_number) 
    print("And it only took you", tries, "tries!\n") 
    input("\n\nPress the enter key to exit.") 

if tries == 3: 
    print("no") 
    input("\n\nPress the enter key to exit.") 
+0

Вы должны запустить его и посмотреть. Если потребуется некоторое время, вы узнаете, как обнаружить, исправить и, надеюсь, предотвратить ошибки в будущем. – cwallenpoole

ответ

0

Чтобы проверить код, попробуйте напечатать номер, сохраненный в the_number = random.randint(1, 100) перед входом в то время цикла. Например:

# Guess My Number 
# 
# The computer picks a random number between 1 and 100 
# The player tries to guess it and the computer lets 
# the player know if the guess is too high, too low 
# or right on the money 

import random 

print("\tWelcome to 'Guess My Number'!") 
print("\nI'm thinking of a number between 1 and 100.") 
print("Try to guess it in as few attempts as possible.\n") 

# set the initial values 
the_number = random.randint(1, 100) 
print("The number is: " + str(the_number)) 
guess = int(input("Take a guess: ")) 
tries = 1 

# guessing loop 
while guess != the_number: 
    if guess > the_number: 
     print("Lower...") 
    elif tries == 3: 
     break 
    else: 
     print("Higher...") 

    guess = int(input("Take a guess: ")) 
    tries += 1 

if guess == the_number: 
    print("You guessed it! The number was", the_number) 
    print("And it only took you", tries, "tries!\n") 
    input("\n\nPress the enter key to exit.") 

if tries == 3: 
    print("no") 
    input("\n\nPress the enter key to exit.") 
0

Оберните свой код функцией.

def guessing_game(number=None): 
    if number is None: 
     number = int(input("Take a guess: ")) 
    ... continue the rest of your code. 
    # Probably want a return True or a return false 
# end guessing_game 

Проверьте свой код, создавая юнит тест

import unittest 

class GuessTest(unittest.TestCase): 
    def setUp(self): 
     """Setup variables. This runs before every test method.""" 
     self.number = random.randint(1, 100) 
    # end setUp 

    def test_guess(self): 
     """Run the test for the guessing game.""" 
     result = guessing_game(self.number) 

     myvalue = result # You want this to be the expected result 

     # check result - for your game you may just want to run a loop 
     self.assertEqual(result, myvalue, "Hey this doesn't work") 
    # end test_guess 

    def test_other_method(self): 
     pass 

    def tearDown(self): 
     """This runs after every test is finished.""" 
     # If you have to clean up something 
     pass 
    # end tearDown 
# end class GuessTest 

if __name__ == "__main__": 
    # Code that runs when you run this file, so importing this file doesn't run your code 
    # guessing_game() # Run your function 

    unittest.main() # Run the unittests 

Другие примечания: Если вы знаете, сколько раз вы хотите, чтобы петля затем использовать для цикла.

for i in range(3): 
    print(i) # Will print 0, 1, 2 
    if guess > the_number: 
     print("Lower ...") 
    elif guess < the_number: 
     print("Higher ...") 
    else: 
     break # You are correct