【问题标题】:python random arithmetic gamepython随机算术游戏
【发布时间】:2014-11-15 05:22:26
【问题描述】:

我想创建一个程序,它生成两个随机数并对它们应用随机算术函数,然后打印答案。 到目前为止,我已经完成了数字和计算,但我不知道如何打印总和或生成答案。

from random import randint
import random
arithmatic = ['+','-','*','/']
beginning = (randint(1,9))
calculation =(random.choice(arithmatic))
end = (randint(1,9))
print (beginning)
print (calculation)
print (end)

【问题讨论】:

    标签: python python-3.x random arithmetic-expressions


    【解决方案1】:
    import random
    
    # Generate your first number
    >>> first = random.randint(1,9)
    >>> first
    1
    
    # Generate your second number
    >>> second = random.randint(1,9)
    >>> second
    5
    

    现在将列表中的所有运算符映射到实际的运算符函数。

    import operator
    ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div}
    

    现在可以随机选择运算符了

    >>> op = random.choice(ops.keys())
    >>> op
    '+'
    

    然后从您的字典中调用该函数。

    >>> ops[op](first,second)
    6
    

    【讨论】:

    • 但我只能让它在 python 2 而不是 3 中工作。
    • @futureprogress 为什么会这样?您能否发布导致问题的代码行以及您收到的完整错误消息?
    【解决方案2】:

    相反,请考虑从真正的函数中选择操作:

    import operator
    arithmetic = [operator.add, operator.sub, operator.mul, operator.div]
    # ...
    print calculation(beginning, end)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多