So I know how to define the function, but I don't know how to output two results where t=0
and t=1
.
Here is my code:
from math import exp
from math import pi
from math import sin
def g(t):
a = exp(-t)
b = sin(pi*t)
g = a*b
return g
t=0
print(g)
g
is a function. print(g)
literally prints the function object. print(g(t))
prints the function g
evaluated at t
. So, you want this after the definition of g
:
print(g(0)) # Print g evaluated at t=0
print(g(1)) # Print g evaluated at t=1
Don't do g = a * b
. Rename it something like h
. By doing that, you're redefining g
to mean something different in the local scope which can get confusing. Functions are objects too!
For your g
function, you use a total of 3 intermediate variables. Normally, having intermediate variables is useful for readability. Here, it's not necessary:
def g(t):
return exp(-t) * sin(pi * t)
(This makes it resemble the task more anyway...)
If you want to call your function more times in the future, you could put your arguments into a list and do this:
for arg in [0, 1]:
print(g(arg))
Also, you can return the value directly without re-assigning to g
:
def g(t):
a = exp(-t)
b = sin(pi*t)
return a*b
Python uses tuples to return multiple values from a function:
def two_vals():
return 11,22
>>> two_vals()
(11, 22)
You can use tuple expansion to assign multiple values to multiple named values:
>>> g1, g2=two_vals()
>>> g1
11
>>> g2
22
So. Rewrite your function so that it calculates both values. Return both (as a list, tuple, dict, whatever data structure) and you have your two values to print.
To fulfill this assignment however, you could just call g
twice and place into a string to print:
def g(t):
a = exp(-t)
b = sin(pi*t)
g = a*b
return g
def both_g_str():
return "g(0): {}, g(1): {}".format(g(0), g(1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.