简体   繁体   中英

While Loop Guessing Number Game - Python

I'm trying to make a 'guess the number between 1-10' game but the while loops seems to keep running. I want to program to let the user guess a number then display if its too high or low etc then start again automatically (loop) to allow the user to pick again. This code makes it run forever though. Can you guys help me?

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"

You forgot to guess inside the loop

  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!"

如果将input语句移动到 while 循环中,则应该没问题。

Use this:

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()
import random

def numberGuess():
  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 True:
    if (guess == randNum):
        print ("You got it!")
        break
    if (guess > randNum):
        print ("Wrong! You guessed too high")
        guess = int(input("Try to guess the number:"))  # ask user for a number
    if (guess < randNum):
        print ("Wrong! You guessed too low")
        guess = int(input("Try to guess the number:"))  # ask user for a number

numberGuess()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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