我正在尝试用 python 编写一个猜数字游戏,但我的程序不起作用 [英] I'm trying to write a number guessing game in python but my program isn't working

查看:60
本文介绍了我正在尝试用 python 编写一个猜数字游戏,但我的程序不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序应该随机生成一个介于 1 到 10(含)之间的数字,并要求用户猜测该数字.如果他们猜错了,他们可以再次猜测,直到猜对为止.如果他们猜对了,程序应该向他们表示祝贺.

The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. If they get it wrong, they can guess again until they get it right. If they guess right, the program is supposed to congratulate them.

这是我所拥有的,但它不起作用.我输入了一个 1 到 10 之间的数字,但没有祝贺.当我输入负数时,没有任何反应.

This is what I have and it doesn't work. I enter a number between 1 and 10 and there is no congratulations. When I enter a negative number, nothing happens.

import random


number = random.randint(1,10)

print "The computer will generate a random number between 1 and 10. Try  to guess the number!"

guess = int(raw_input("Guess a number: "))


while guess != number:
    if guess >= 1 and guess <= 10:
       print "Sorry, you are wrong."
       guess = int(raw_input("Guess another number: ")) 
   elif guess <= 0 and guess >= 11: 
      print "That is not an integer between 1 and 10 (inclusive)."
      guess = int(raw_input("Guess another number: "))
   elif guess == number:
     print "Congratulations! You guessed correctly!"

推荐答案

只需将祝贺消息移出循环即可.然后,您也可以在循环中只有一个猜测输入.以下应该有效:

Just move the congratulations message outside the loop. You can then also only have one guess input in the loop. The following should work:

while guess != number:
    if guess >= 1 and guess <= 10:
        print "Sorry, you are wrong."
    else:
        print "That is not an integer between 1 and 10 (inclusive)."

    guess = int(raw_input("Guess another number: "))

print "Congratulations! You guessed correctly!"

这篇关于我正在尝试用 python 编写一个猜数字游戏,但我的程序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆