I don’t know how to retrieve, store and print the values of parameters passed into a function. I do know that many posts are related to this question, but I couldn't find anything that matches the simple thing I would like to do.
Let’s take a very simple example:
def times(value, power):
return value**power
If I run this function and then write:
x = times(2.72, 3.1)
print(f'Result of calculation is: {x: .6f}')
then the output will be:
Result of calculation is: 22.241476
OK, but this is not what I would like to have; I would like to be able to print the result, the value and the power, and have the following lines as output, preferably using a print
as above; something like print(f’some text here: {something}’)
…
Desired output:
Result of calculation is: 22.241476
Value passed to function was: 2
Power passed to function was: 3
What is the most effective way to do that?
CodePudding user response:
You can always just add more "print" lines.
So the code would look something like this:
def times(value, power):
print(f'Result of calculation is: {x: .6f}')
print(f'Value passed to function was: {value}')
print(f'Power passed to function was: {power}')
and then you can just pass the values into the function like so:
times(2.72, 3.1)
CodePudding user response:
You will need to first store the parameters in variables in the code that calls the function.
Assuming the function 'times' is defined.
a = 2.72
b = 3.1
x = times(a, b)
print(f'Result of calculation is: {x: .6f}')
print(f'Value passed to function was: {a}')
print(f'Power passed to function was: {b}')
CodePudding user response:
Please try the following code. It uses the concept of closure (google it). Hope it is helpful.
def times():
value = float(input('Enter a value:'))
power = float(input('Enter a power: '))
def raise_to_power():
return value ** power
print(
f'Result of calculation is: {raise_to_power(): .6f}\nValue passed to function was: {value}\nPower passed to function was: {power}')
times()