如何在Python中修复“未定义名称”错误消息?

时间:2019-05-04 18:29:35

标签: python-3.x function undefined

我正在使用Python作为我的第一个“更大”项目创建一个简单的计算器。 我正在尝试使用def函数,当我尝试调用该函数时,它会显示“未定义名称”错误消息。

public class AjoutProduit {


private Form fAjout = new Form("", new BoxLayout(BoxLayout.Y_AXIS));
public AjoutProduit() {    

    TextField nomProduit = new TextField("", "Nom du produit");
    TextField descProduit = new TextField("", "Description du produit");
    ComboBox<String> opProduit = new ComboBox<>(
            "",
            "echanger",
            "donner",
            "recycler",
            "reparer"
    );

    final String[] jobPic = new String[1];
    Label jobIcon = new Label();

    Button image = new Button("Ajouter une image ");
    final String[] image_name = {""};
    final String[] pathToBeStored={""};

    /////////////////////Upload Image
    image.addActionListener((ActionEvent actionEvent) -> {
    Display.getInstance().openGallery(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ev) {
            if (ev != null && ev.getSource() != null) {
                String filePath = (String) ev.getSource();
                int fileNameIndex = filePath.lastIndexOf("/") + 1;
                String fileName = filePath.substring(fileNameIndex);
                Image img = null;
                try {
                    img = Image.createImage(FileSystemStorage.getInstance().openInputStream(filePath));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image_name[0] = System.currentTimeMillis() + ".jpg";
                jobIcon.setIcon(img);
                System.out.println(filePath);
                System.out.println(image_name[0]);

                try {
                         pathToBeStored[0] = FileSystemStorage.getInstance().getAppHomePath()+ image_name[0];
                        OutputStream os = FileSystemStorage.getInstance().openOutputStream(pathToBeStored[0]);
                        ImageIO.getImageIO().save(img, os, ImageIO.FORMAT_JPEG, 0.9f);
                        os.close();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }
    }, Display.GALLERY_IMAGE);});



            ////////////Copied with URL Symfony
            Button myButton = new Button("Valider");
            myButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    ServiceProduit sp = new ServiceProduit();
                    ServiceEchange se  = new ServiceEchange();
                    String path = "C:/Users/omark/.cn1/"+image_name[0];
                   File file = new File(path);
                   sp.ajoutProduit(file);


                }
            });


    fAjout.addAll(nomProduit,descProduit,opProduit,jobIcon,myButton,image);
    fAjout.show();

}

2 个答案:

答案 0 :(得分:1)

您已经不必要地将函数定义为采用两个参数,因为在函数内部 中定义了两个参数,因此无法提供这些参数:

    def calculation (argnum1, argnum2):  # argnum1 and argnum2 are immediately discarded
        argnum1 = float (input("Enter your fist number: "))  # argnum1 is defined here
        argnum2 = float (input("Enter your second number: "))
        # do things with argnum1 and argnum2
    ...
    calculation(argnum1, argnum2)  # argnum1 and argnum2 are not defined yet

请注意,仅在调用函数时才执行函数的主体。在您调用calculation时,argnum1argnum2尚未定义-即便如此,它们也只能在另一个作用域中定义。

理想情况下,将input调用移到函数的外部

    def calculation (argnum1, argnum2):
        # do things with argnum1 and argnum2
    ...
    argnum1 = float (input("Enter your fist number: "))  # argnum1 is defined here
    argnum2 = float (input("Enter your second number: "))
    calculation(argnum1, argnum2)

请注意,您应该在循环之外定义函数。否则,将在每次迭代时不必要地重新定义它。彼此之间有多个return语句也没有意义。

您的代码应如下所示:

def add(argnum1, argnum2):
    result = argnum1 + argnum2
    print (result)
    print("-"*25)
    return result

while True:
    print ("Options: ")
    print ("Enter '+' to add two numbers")
    print ("Enter '-' to subtract two numbers")
    print ("Enter '*' to multiply two numbers")
    print ("Enter '/' to divide two numbers")
    print ("Enter 'quit' to end the program")
    user_input = input(": ")


    if user_input == "quit":
        break
    elif user_input == "+":
        argnum1 = float (input("Enter your fist number: "))
        argnum2 = float (input("Enter your second number: "))
        add(argnum1, argnum2)

答案 1 :(得分:0)

您可以将功能定义移出while块。

def calculation():
    argnum1 = float(input("Enter your fist number: "))
    argnum2 = float(input("Enter your second number: "))
    result = argnum1 + argnum2
    print(result)
    return result

while True:
    print("Options: ")
    print("Enter '+' to add two numbers")
    print("Enter '-' to subtract two numbers")
    print("Enter '*' to multiply two numbers")
    print("Enter '/' to divide two numbers")
    print("Enter 'quit' to end the program")
    user_input = input(": ")

    if user_input == "quit":
        break

    elif user_input == "+":
        calculation()