简体   繁体   English

用python猜游戏

[英]Guessing game in python

I have only just started to learn to program following http://learnpythonthehardway.org . 我才刚刚开始学习http://learnpythonthehardway.org上的编程。 After learning about loops and if-statements I wanted to try to make a simple guessing game. 在了解了循环和if语句之后,我想尝试制作一个简单的猜谜游戏。

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. 如果您做出了错误的猜测,它将陷入困境,并不断重复“ TOO HIGH”或“ TOO LOW”,直到您达到crtlC。

I have read about while loops and have read other peoples code but I simply dont want to just copy the code. 我已经阅读了while循环并阅读了其他人的代码,但是我只是不想只复制代码。

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"

You have to ask the user again. 您必须再次询问用户。

Add this line at the end (indented by four spaces to keep it within the while block): 在末尾添加此行(缩进四个空格以将其保留在while块中):

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

This is just a quick hack. 这只是一个快速的技巧。 I would otherwise follow the improvement proposed by @furins. 否则,我会遵循@furins提出的改进。

Moving the request inside the while loop does the trick :) 在while循环内移动请求可以达到目的:)

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM