How to avoid repeating commands through a function?

Asked

Viewed 112 times

1

I am creating a program to do some math math with some commands and has 1 line of code that repeats in all conditions, with only a small change in each of the conditions. My question is how to create a function to call her instead of typing this line every time(I know it’s not worth creating a function just not to repeat a line when sometimes I would even write more, but I think I’ll need to learn how to replace large pieces of code with functions). Follow my code and finally the function I tried to create for this.

from script_calc import *


command = input()

if '!' in command:
    a = int(command.strip('!')) # esse comando que eu gostaria de substituir todas as vezes que ele é repetido mudando só o caractere que está dentro do strip.
    print(fact(a))

elif 'root' in command:
    a = int(command.strip('root'))
    print(root(a))

elif '²' in command:
    a = int(command.strip('²'))
    print(square(a))

elif '³' in command:
    a = int(command.strip('³'))
    print(cube(a))

The functions that have been called:

from math import factorial


def fact(a):
    return factorial(a)


def root(a):
    return a ** (1/2)


def square(a):
    return a ** 2


def cube(a):
    return a ** 3

I tried to create this function not to repeat the command I said and gave error:

def same(x):
    a = int(command.strip({}).format(x))

And then execute her like this:

elif 'root' in command:
        x = 'root'
        same(x) 
        print(root(a))

What is the error in this function?

1 answer

1


A good way to avoid repeating these commands in the structure if else that has is using a dictionary with the respective text to be found in the command and function to use:

commands = [
    {'match':'root', 'func': root },
    {'match':'!',    'func': fact },
    {'match':'²',    'func': square },
    {'match':'³',    'func': cube },
]

For consistency with the code you already have I used names in English

Then just use one for to iterate on each of the commands and if any correspond to the match execute it and show the value:

input_command = input()

for command in commands:
    if command["match"] in input_command:
        val = int(input_command.strip(command["match"]))
        print(command["func"](val))
        break 

See this example working on Ideone

In this last loop/cycle command["match"] refers to the text to be found in the command and command["func"] the function to be executed. We can also write it in more detail:

input_command = input()

for command in commands:
    # o texto a ser procurado no comando
    match = command["match"] 

    if match in input_command:
        # valor obtido do comando
        val = int(input_command.strip(match)) 

        # obter a função armazenada no comando
        command_func = command["func"] 

        # executa-la passando o valor
        result = command_func(val)

        print(result)
        break 

With this solution adding a command boils down to adding a new object in the command list, leaving the for unchanged.

  • Could you explain the line of the print? I know what this line does, but I don’t think I understand the syntax.

  • @Lucassouza command["func"] has a reference to a function, which comes from the list of commands, so you call as if calling a normal function with () passing the relevant value. I will create a more detailed version in the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.