无效的语法错误,但我无法发现它? (Python)

问题描述 投票:0回答:1

这是我的代码,语法错误位于第 18 行。我很难理解为什么会出现此错误。

    from visual import *

    def Efield(pos, charge)
    
        """
        Calculate electric field due to point charge
        
        Inputs
        ======
        
        pos        - Position where the E field is required (vector)
        charge.pos - Position of the charge (vector)
        charge.q   - Charge (float)
        
        Returns
        =======
        
        The electric field vector
        """
        
        r = vector(charge.pos) - vector(pos)  # Vector from pos to chargepos
        
        E = float(q) * r / abs(r)**3  # Coulomb's law
        
        return E

# Create some charges

    charge1 = sphere(pos=(0,2,0), q=1, radius=0.2, color=color.red)    # Positive charge
    charge2 = sphere(pos=(0,-2,0), q=-1, radius=0.2, color=color.blue)  # Negative charge

# Generate arrows at random locations
    random.seed(1234)  # Specify a random seed

    n = 500
    for i in range(n):
        x = random.uniform(-4 4)
        y = random.uniform(-4,4)
        z = random.uniform(-4,4)
    
        pos = vector(x,y,z)
    
        # Make sure pos is not too close to both positive and negative charge
        if abs(pos - charge1.pos) > 1 and abs(pos - charge2.pos) > 1:
        # Create an arrow if it's far enough from both charges
        a = arrow(pos=pos, axis= Efield(pos, charge1) + Efield(pos,charge1))
python
1个回答
2
投票

您在

:
 之后缺少 
def Effield(pos, charge)

您还漏掉了一行中的逗号:

x = random.uniform(-4 4)

应该是

x = random.uniform(-4, 4)

而且这个函数根本没有缩进,这会抛出:

IndentationError:需要缩进块

© www.soinside.com 2019 - 2024. All rights reserved.