美文网首页python自学
【Python 3】简单的猜数字游戏

【Python 3】简单的猜数字游戏

作者: 雨水之后 | 来源:发表于2018-01-05 16:37 被阅读39次

可以让用户通过输入bes来猜测数字一和数字二的关系,分别表示“大于”、“等于”和“小于”。

import random

#比较两个数字并返回结果
def compare(x,y):
  if x > y:
    return 'b'
  elif x == y:
    return 'e'
  elif x < y:
    return 's'
  else:
    return 'not a number'

#游戏
def guess():
  
  #获取随机数
  num1 = random.randint(0,9)
  num2 = random.randint(0,9)
  
  user = str(input('Now you can guess the relation between the first and the second number. You can call it by "b", "e" or "s". Please guess: ')).lower()
  
  if user != 'b' and user != 'e' and user != 's':
    print('Please input "b", "e" or "s".')
    print('--------------------------------------------')
    return guess()
  else:
    if user == compare(num1,num2):
      print('Won! The first number is ',num1, ', the second one is ', num2)
      print('--------------------------------------------')
      return guess()
    else:
      print('Lost! The first number is ',num1, ', the second one is ', num2)
      print('--------------------------------------------')
      return guess()

guess()

执行:

执行状况

THE END.

相关文章

网友评论

    本文标题:【Python 3】简单的猜数字游戏

    本文链接:https://www.haomeiwen.com/subject/ubssnxtx.html