Guessing game in python

夙愿已清 提交于 2019-12-13 00:38:12

问题


I have only just started to learn to program following http://learnpythonthehardway.org. After learning about loops and if-statements I wanted to try to make a simple guessing game.

The problem is:

If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.

I have read about while loops and have read other peoples code but I simply dont want to just copy the code.

print ''' This is the guessing game! 
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''

import random

random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False

while not correct:
    if guess == random_number:
        print "CONGRATS YOU GOT IT"
        correct = True
    elif guess > random_number:
        print "TOO HIGH"
    elif guess < random_number:
        print "TOO LOW"
    else:
        print "Try something else"

回答1:


You have to ask the user again.

Add this line at the end (indented by four spaces to keep it within the while block):

    guess = input("What could it be? > ")

This is just a quick hack. I would otherwise follow the improvement proposed by @furins.




回答2:


Moving the request inside the while loop does the trick :)

print ''' This is the guessing game! 
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''

import random

random_number = random.randrange(1, 10)
correct = False

while not correct:
    guess = input("What could it be? > ")  # ask as long as answer is not correct
    if guess == random_number:
        print "CONGRATS YOU GOT IT"
        correct = True
    elif guess > random_number:
        print "TO HIGH"
    elif guess < random_number:
        print "TO LOW"
    else:
        print "Try something else"


来源:https://stackoverflow.com/questions/13917097/guessing-game-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!