Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...