user14987264
user14987264

Reputation:

Easier way of calculator command?

So this is my calculator command but it takes over 430+ lines to calculate stuff and it seems to be very inefficient, you can only calculate with one operator and only 2 inputs can be given at one time in order to calculate it.

Is there a way how I can take each input and split with the factor inside? So multiple inputs can be entered at once?

@client.command(aliases=['calculate', 'calculator'])
async def calc(ctx, a: int, factor=None, b: int = None):

        if factor == None:
                await ctx.send(
                    f"""{ctx.author.mention}, you must include an operation to calculate: ``add`` ``subtract`` ``multiply`` ``divide`` **or** ``+`` ``-`` ``x`` ``/`` **or** ``>`` ``==`` ``<``
eg. &calc 1 (add or +) 100```
eg. &calc 1 (subtract or -) 100```
eg. &calc 1 (multiply or x) 100```
eg. &calc 1 (divide or /) 100```
eg. &calc 1 == 100```
eg. &calc 1 < 100```
eg. &calc 1 > 100```""")

Upvotes: 0

Views: 144

Answers (1)

Cohen
Cohen

Reputation: 2415

Yes, you simply can by joining each of the *args with the operator that was provided and continuously joining each of the integers given after the operator.

@client.command()
async def calculate(ctx, operation, *nums):
    if operation not in ['+', '-', '*', '/']:
        await ctx.send('Please use a valid operation type. ``+,-,*,/`` eg. ``calc + 10 10 100``')
        return
    var = f' {operation} '.join(nums)
    await ctx.send(f'{var} = {eval(var)}')

Upvotes: 1

Related Questions