不确定我做错了什么,Python猜数游戏

时间:2015-12-08 17:09:31

标签: python python-3.x random

import random


print("Hey there, player! Welcome to Emily's number-guessing game! ")
name=input("What's your name, player? ")

random_integer=random.randint(1,25)

tries=0
tries_remaining=10

while tries < 10:
  guess = input("Try to guess what random integer I'm thinking of, {}!   ".format(name))
  tries += 1
  tries_remaining -= 1

# The next two small blocks of code are the problem.

  try:
    guess_num = int(guess)
  except:
    print("That's not a whole number!   ")
    tries-=1
    tries_remaining+=1


  if not guess_num > 0 or not guess_num < 26:
    print("Sorry, try again! That is not an integer between 1 and 25!   ")
    break



  elif guess_num == random_integer:
    print("Nice job, you guessed the right number in {} tries!   ".format(tries))
    break


  elif guess_num < random_integer:
    if tries_remaining > 0:
      print("Sorry, try again! The integer you chose is a litte too low! You have {} tries remaining.   ".format(int(tries_remaining)))
      continue
    else:
      print("Sorry, but the integer I was thinking of was {}!   ".format(random_integer))
      print("Oh no, looks like you've run out of tries!   ")



  elif guess_num > random_integer:
    if tries_remaining > 0:
      print("Sorry, try again! The integer you chose is a little too high. You have {} tries remaining.   ".format(int(tries_remaining)))
      continue
    else:
      print("Sorry, but the integer I was thinking of was {}!   ".format(random_integer))
      print("Oh no, looks like you've run out of tries!   ")

我会尝试解释这个以及我可以...我试图让问题区域在用户输入除1到25之间的整数之外的任何东西时再次输入猜测,但我可以'弄清楚如何。我怎样才能使用户可以选择在赢得或失败后重新启动程序?

编辑:请注意,我没有其他问题的陈述,因为没有相反的输出。

2 个答案:

答案 0 :(得分:1)

使用函数。如果用户想再试一次,请在函数中输入所有内容并再次调用该函数! 这将再次重新启动整个过程!如果用户想要重新启动,也可以这样做。 再次调用该方法是一个很好的计划。在方法/函数中包含完整的东西。

答案 1 :(得分:0)

这将解决错误的间隔

 if not guess_num > 0 or not guess_num < 26:
    print("Sorry, try again! That is not an integer between 1 and 25!   ")
    continue

对于其他人,你可以做这样的事情

创建一种方法并坚持你的游戏数据

def game():
   ... 
   return True if the user wants to play again (you have to ask him)
   return False otherwise

play = True
while play:
   play = game()