猜数字游戏python

时间:2016-03-08 03:01:33

标签: python loops input while-loop

所以我正在开发一个猜数字游戏,其中一个要求是更新数字的“范围”,这样用户可以更轻松地进行猜测。我为数字太高或太低时创建了一个新输入。但是,我对循环并不是很好,我无法弄清楚为什么我的循环只重复一次,而不是一遍又一遍地粘贴代码。任何人都可以帮忙,所以elif语句会重复,直到数字正确吗?

到目前为止,这是我的代码......

import random
random_number = random.randint(1,100)
tries = 0
while tries < 800:
  guess = input("Guess a random number between 1 and 100.")       
  tries += 1
  try:
    guess_num = int(guess)
  except:
    print("That's not a whole number!")
    break

  if not guess_num > 0 or not guess_num < 101:
    print("That number is not between 1 and 100.")
    break

  elif guess_num == random_number:
    print("Congratulations! You are correct!")
    print("It took you {} tries.".format(tries))
    break

  elif guess_num > random_number:
      print("Sorry that number is too high.")
      guess_high = input("Guess a number between 0 and {} .".format(guess_num))

  elif guess_num < random_number:
      print("Sorry that number is too low.")
      guess_low = input("Guess a number between {} and 100 .".format(guess_num))

  else:
      print("Sorry, but my number was {}".format(random_number))
      print("You are out of tries. Better luck next time.")

5 个答案:

答案 0 :(得分:1)

import random
random_number = random.randint(1,100)
tries = 0
guess = input("Guess a random number between 1 and 100.")       
while tries < 800:
  tries += 1
  try:
    guess_num = int(guess)
  except:
    print("That's not a whole number!")
    break

  if not guess_num > 0 or not guess_num < 101:
    print("That number is not between 1 and 100.")
    break

  elif guess_num == random_number:
    print("Congratulations! You are correct!")
    print("It took you {} tries.".format(tries))
    break

  elif guess_num > random_number:
      print("Sorry that number is too high.")
      guess = input("Guess a number between 0 and {} .".format(guess_num))

  elif guess_num < random_number:
      print("Sorry that number is too low.")
      guess = input("Guess a number between {} and 100 .".format(guess_num))

else:
  print("Sorry, but my number was {}".format(random_number))
  print("You are out of tries. Better luck next time.")

答案 1 :(得分:0)

在哪种情况下你的循环只重复一次?

循环会中断(因为如果输入的猜测小于0或大于100,则在“if not guess_num&gt; 0或者不是guess_num&lt; 101:”下的第15行中有break语句)。

如果用户输入1到100之间的错误猜测,则代码会循环,因此要求用户输入另一个数字。

虽然它确实循环,但循环不会更新范围。 您可以做的是将range_min和range_max设置为变量,并根据猜测是否过低或过高来更改这些变量。 请参阅以下代码:

import random
random_number = random.randint(1,100)
tries = 0
range_min = 0
range_max = 100
while tries < 800:
  guess = input("Guess a random number between " + str(range_min +1) + " and " +  str(range_max))       
  tries += 1
  try:
    guess_num = int(guess)
  except:
    print("That's not a whole number!")
    break

  if not guess_num > range_min or not guess_num < (range_max+1):
    print("That number is not between str(range_min +1) + " and " +      str(range_max)")
    break

  elif guess_num == random_number:
    print("Congratulations! You are correct!")
    print("It took you {} tries.".format(tries))
    break

  elif guess_num > random_number:
      print("Sorry that number is too high.")
      guess_high = input("Guess a number between 0 and {} .".format(guess_num))
range_max = guess_num

  elif guess_num < random_number:
      print("Sorry that number is too low.")
      guess_low = input("Guess a number between {} and 100 .".format(guess_num))
range_min = guess_num

  else:
      print("Sorry, but my number was {}".format(random_number))
          print("You are out of tries. Better luck next time.") 

答案 2 :(得分:0)

  1. 不要使用break,因为它们会终止while循环。请参阅python语言参考。

  2. 您应该只询问guess_num一次。当猜测太高或太低时(BTW变量名input不正确),删除两个guess

  3. 最后一个条件(尝试之外)应该在while循环之外,因为当尝试次数超过800时它将被执行。

  4. 提示。用户可以使用等效的二分搜索来玩这个游戏(从50开始,然后猜测25或75,取决于更高/更低等)。你应该允许大约8次尝试(而不是800次)。

答案 3 :(得分:0)

以下是更新范围的方法:

import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 800:
  if(tries == 0):
    guess = input("Guess a random number between {} and {}.".format(low, high))       
  tries += 1
  try:
    guess_num = int(guess)
  except:
    print("That's not a whole number!")
    break    

  if guess_num < low or guess_num > high:
    print("That number is not between {} and {}.".format(low, high))
    break    

  elif guess_num == random_number:
    print("Congratulations! You are correct!")
    print("It took you {} tries.".format(tries))
    break    

  elif guess_num > random_number:
      print("Sorry that number is too high.")
      high = guess_num
      guess = input("Guess a number between {} and {} .".format(low, high))    

  elif guess_num < random_number:
      print("Sorry that number is too low.")
      low = guess_num
      guess = input("Guess a number between {} and {} .".format(low, high))    

  else:
      print("Sorry, but my number was {}".format(random_number))
      print("You are out of tries. Better luck next time.")

答案 4 :(得分:0)

我将如何做到这一点。不确定它是否有效,但方法是:

import UIKit
    import GoogleMaps
    import CoreLocation

    class ViewController: UIViewController, CLLocationManagerDelegate {


        var locationManager: CLLocationManager!

        var currentLocation: CLLocation!
        var long: Float64!
        var lat: Float64!

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.


            locationManager = CLLocationManager()
            locationManager.delegate = self;
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()

            let camera = GMSCameraPosition.cameraWithLatitude(lat,
                longitude: long, zoom:6)
            let mapView = GMSMapView.mapWithFrame(CGRectZero, camera:camera)

            let marker = GMSMarker()
            marker.position = camera.target
            marker.snippet = "Hello World"
            marker.appearAnimation = kGMSMarkerAnimationPop
            marker.map = mapView

            self.view = mapView
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            currentLocation = locations.last! as CLLocation
            long = currentLocation.coordinate.longitude;
            lat = currentLocation.coordinate.latitude;
        }


    }

正如您所看到的,我正在使用辅助函数来减少if / else结构的数量。

还需要更新范围。并且由于参数化字符串,我可以告诉用户该范围是什么。

我还设置了一个标记,以确定用户是否在游戏结束时找到了该号码