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?
Could you explain the line of the print? I know what this line does, but I don’t think I understand the syntax.
– Lucas Souza
@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.– Isac