简单的加减法

该博客主要展示了用Python编写的math_game.py脚本,可随机生成两个100以内数字,随机选择加法或减法,减法时用大数字减小数字。若用户答错三次,程序会给出正确答案,还提供了继续或退出的交互功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写math_game.py脚本,实现以下目标:

  1. 随机生成两个100以内的数字
  2. 随机选择加法或是减法
  3. 总是使用大的数字减去小的数字
  4. 如果用户答错三次,程序给出正确答案
    from random import randint, choice
    def exam(): counter = 0 while counter < 3: nums = [randint(1, 100) for i in range(2)] nums.sort(reverse=True) op = choice('+-') if op == '-': result = nums[0] - nums[1] else: result = nums[0] + nums[1] prompt = '%s %s %s =' % (nums[0], op, nums[1]) answer = int(input(prompt)) if answer == result: print('very Good') else: print('\033[31;1msorry,You are wrong\033[0m') counter += 1 def main(): while True: yn = input('Continue:/y/n ?').strip()[0] # 去除空白 然后取第一位 if yn in 'nN': print('\nBye-bye') break exam() if __name__ == '__main__': main()

     

    
    
    from random import randint, choice


    def add(x,y):
    return x-y
    def sum(x,y):
    return x+y

    def exam():

    cmds = {'-':add,'+':sum}
    nums = [randint(1, 100) for i in range(2)]
    nums.sort(reverse=True)
    op = choice('+-')
    result = cmds[op](*nums)
    # print(*nums)
    # if op == '-':
    # result = add(nums[0],nums[1])
    # else:
    # result = sum(nums[0],nums[1])
    prompt = '%s %s %s =' % (nums[0], op, nums[1])

    counter = 0
    while counter < 3:
    try:
    answer = int(input(prompt))
    except:
    print()
    continue
    if answer ==result :
    print('very Good')
    break
    else:
    print('\033[31;1msorry,You are wrong\033[0m')
    counter += 1
    else:
    print('%s %s' %(prompt,result))


    def main():

    while True:
    exam()
    try:
    yn = input('Continue:/y/n ?').strip()[0] # 去除空白 然后取第一位
    except IndexError:
    continue
    except (KeyboardInterrupt,EOFError):
    yn = 'n'

    if yn in 'nN':
    print('\nBye-bye')
    break



    if __name__ == '__main__':
    main()
     

     

转载于:https://www.cnblogs.com/lsgo/p/10554527.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值