返回后打印

时间:2018-03-07 22:50:01

标签: python

我想在返回这些值后打印intPsi2和intPsiHPsi,但Python不会打印它们。我认为他们返回后不会打印,因为它们是本地化的值。

#import libraries 
import numpy as np
import matplotlib.pyplot as plt
from numpy import pi

#(1)create an array called psi that is 51x51 pixels,(2) create an array called V that is 51x51 pixels
psi=np.zeros((51,51))
v=np.zeros((51,51))
#Using a for-loop, set each element of psi to a 2-D sin function:
#4) Using the same for-loop, set each element of V to a 2D gaussian:
n=50
Vm=80
a=.4*n
for x in np.arange(50):
    for y in np.arange(50):
        psi[x,y]=np.sin(pi*(x/n))*np.sin(pi*(y/n))
        v[x,y]=Vm*np.exp(-(x-y)**2/(a)**2)

 # 5) Plot psi.    
plt.imshow(psi)
plt.show()

def nn(psi):
  psi1=np.zeros_like(psi)
  psi1[1:n-1,1:n-1]=(psi[0:n-2,1:n-1]+psi[2:n,1:n-1]+psi[1:n-1,0:n-2]+psi[1:n-1,2:n])/4.
  return(psi1)


def integrate(psi,v):
  psi2=psi[x,y]*psi[x,y]
  intPsi2=(psi2/n**2).sum()

  psi3=(psi[x,y]*v[x,y]*psi[x,y]*(1/n**2))-(2*psi[x,y]*nn(psi))+(2*psi2)
  intPsiHPsi=psi3.sum()


  return(intPsi2, intPsiHPsi)
print(intPsi2, intPsiHPsi)

2 个答案:

答案 0 :(得分:0)

#import libraries 
import numpy as np
import matplotlib.pyplot as plt
from numpy import pi

#(1)create an array called psi that is 51x51 pixels,(2) create an array called V that is 51x51 pixels
psi=np.zeros((51,51))
v=np.zeros((51,51))
#Using a for-loop, set each element of psi to a 2-D sin function:
#4) Using the same for-loop, set each element of V to a 2D gaussian:
n=50
Vm=80
a=.4*n
for x in np.arange(50):
    for y in np.arange(50):
        psi[x,y]=np.sin(pi*(x/n))*np.sin(pi*(y/n))
        v[x,y]=Vm*np.exp(-(x-y)**2/(a)**2)

 # 5) Plot psi.    
plt.imshow(psi)
plt.show()

def nn(psi):
  psi1=np.zeros_like(psi)
  psi1[1:n-1,1:n-1]=(psi[0:n-2,1:n-1]+psi[2:n,1:n-1]+psi[1:n-1,0:n-2]+psi[1:n-1,2:n])/4.
  return(psi1)


def integrate(psi,v):
  psi2=psi[x,y]*psi[x,y]
  intPsi2=(psi2/n**2).sum()

  psi3=(psi[x,y]*v[x,y]*psi[x,y]*(1/n**2))-(2*psi[x,y]*nn(psi))+(2*psi2)
  intPsiHPsi=psi3.sum()


  return intPsi2, intPsiHPsi

intPsi2, intPsiHPsi=integrate(psi,v) #calling the function and storing output in variables
print(intPsi2, intPsiHPsi) #printing variables

答案 1 :(得分:0)

在函数内设置值不会更新函数外部的值。您必须为方法响应分配变量。

a,b = 1,2
def some_funct():
    a = 4
    b = 5
    return a,b

print (a, b)
c, d = some_funct()
print(a,b)
print(c,d)

给出

1 2
1 2
4 5

(除非你使用global关键字声明变量 - 这通常是一个坏主意)

a,b = 1,2
def some_other_funct():
    global a
    global b
    a = 4
    b = 5
    return a,b

print (a, b)
c, d = some_other_funct()
print(a,b)
print(c,d)

给出

1 2
4 5
4 5