While循环猜数游戏-Python

2024-09-18 18:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个'猜猜1-10之间的数字'游戏,但while循环似乎继续运行。我想程序让用户猜测一个数字,然后显示如果它太高或太低等,然后重新开始自动(循环)允许用户再次挑选。这段代码让它永远运行。 你们能帮我吗?

import random

def numberGuess():
  printNow("I'm thinking of a number between 1 and 10")
  guess = 0 # give guess a starting value
  randNum = random.randrange(1,11) # this line generates a random number
  guess = int(input("Try to guess the number:")) # ask user for a number
  print randNum 
  while guess != randNum:
    if (guess == randNum): 
      print "You got it!"
    if (guess > randNum):
      print "Wrong! You guessed too high"
    if (guess < randNum):
      print "Wrong! You guessed too low"

Tags: 用户程序you游戏numberif数字random
3条回答

你忘了在圈里猜

  while guess != randNum:
    guess = int(input("Try to guess the number:"))
    if (guess > randNum):
      print "Wrong! You guessed too high"
    if (guess < randNum):
      print "Wrong! You guessed too low"
  print "You got it!"

使用这个:

import random

def numberGuess():
  print("I'm thinking of a number between 1 and 10")
  randNum = random.randrange(1,11) # this line generates a random number
  while guess != randNum:
    guess = int(input("Try to guess the number:")) # ask user for a number
    if (guess == randNum): 
      print "You got it!"
    if (guess > randNum):
      print "Wrong! You guessed too high"
    if (guess < randNum):
      print "Wrong! You guessed too low"

numberGuess()

如果将input语句移到while循环中,就应该可以了。

相关问题 更多 >