简体   繁体   English

猜数字游戏python

[英]Guessing number game python

So i'm working on a guessing number game and one of the requirements is for the "range" of numbers to be updated so that the user with have an easier time with their guess'. 所以我正在做一个猜测数字游戏,要求之一是要更新数字的“范围”,以便用户可以更轻松地进行猜测。 I created a new input for when the number is either too high or too low. 当数字太高或太低时,我都创建了一个新输入。 However, i'm not very good with loops and I can't figure out why my loop is repeating only once without my pasting the code over and over again. 但是,我对循环不是很好,而且我无法弄清楚为什么我的循环只重复一次而没有一遍又一遍地粘贴代码。 Can anyone help so the elif statements will repeat until the number is correct? 任何人都可以帮忙,以便elif语句会重复直到数字正确为止?

This is my code thus far... 到目前为止,这是我的代码...

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.")
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.")

For which case does your loop only repeats once? 在哪种情况下,您的循环仅重复一次?

The loop would break (since you have a break statement in line 15 under the "if not guess_num > 0 or not guess_num < 101:") if the input guess is less than 0 or greater than 100. 如果输入的猜测值小​​于0或大于100,则循环将中断(因为在第15行的“ if notgues_num> 0或notgues_num <101:”下有一个break语句)。

If the user input an incorrect guess between 1 and 100, then the code does loop and hence the user is asked to input another number. 如果用户输入的错误猜测在1到100之间,则代码会循环,因此要求用户输入另一个数字。

Although it does loop, the loop is not updating the range. 尽管确实循环,但该循环不会更新范围。 What you can do is set range_min and range_max as variables and change these variables according to if the guess is too low or too high. 您可以做的是将range_min和range_max设置为变量,并根据猜测值太低还是太高来更改这些变量。 See the following code: 请参见以下代码:

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.") 
  1. Do not use break , as they terminate the while loop. 不要使用break ,因为它们会终止while循环。 See python language reference. 请参阅python语言参考。

  2. You should ask only once for guess_num . 您只需要询问一次guess_num Remove the two input when the guess is too high or too low (BTW variable name guess was incorrect). 当猜测值太高或太低(BTW变量名称guess不正确)时,请删除两个input

  3. The last condition (out of tries) should be outside the while loop, since it will be executed when the number of tries is over 800. 最后一个条件(尝试次数除外)应在while循环之外,因为它将在尝试次数超过800次时执行。

  4. Hint. 暗示。 A user can play this game with the equivlent of a binary search (start with 50, then guess 25 or 75 depending if higher/lower, etc). 用户可以进行与二分搜索相当的游戏(从50开始,然后猜测25或75,具体取决于更高/更低,等等)。 You should allow about 8 tries (not 800). 您应该允许大约8次尝试(而不是800次)。

Here is how to update the ranges: 以下是更新范围的方法:

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.")

Here is how I would do it. 这就是我要怎么做。 Not sure if it works but the approach would be: 不知道它是否有效,但是方法是:

import random

random_number = random.randint(1,100)
max_tries = 100 
tries = 0
left = 0
right = 100
found = False


def get_number():
    try:
        guess = int(input("Guss a random number between {} and {}".format(left, right)))            
        if guess > right or guess < left:
            print("That number is not between {} and {}".format(left, right))
        return guess
    except:
        print("That's not a whole number!")
        get_number()

def update_range(guess):
    if guess >= left:
        left = guess
    else:
        right = guess        

while tries <= max_tries and not found:
    guess = get_number()
    tries=+1
    if guess == random_number:
        print("Congratulations! You are correct!")
        print("It took you {} tries.".format(tries))
        found = True
    else:
        update_range(guess)

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

As you can see I am using helper functions in order to reduce the number of if/else structures. 如您所见,我正在使用辅助函数以减少if / else结构的数量。

Also updating the range is necessary. 此外,还需要更新范围 And thanks to parametrized strings I can tell the user what's the range. 并且由于参数化的字符串,我可以告诉用户范围是多少。

I also set a flag to know whether the user found the number or not at the end of the game 我还设置了一个标志来了解用户是否在游戏结束时找到了号码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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