如何让我的程序更有效率?

时间:2015-09-22 17:09:02

标签: python

我成功地制作了一个将二进制转换为十进制的程序。我有一种强烈的感觉,这可以比我创建它的方式更简单,更有效。这就是我所拥有的:

   #Binary to Decimal Conversion
#Input Data and assign variables
    def main():
    binary = input("Enter rhe binary number you'd like to convert: ")
    x = "1"
    y = "0"
    num1 = 0
    num2 = 0
    num3 = 0
    num4 = 0
    num5 = 0
    num6 = 0
    num7 = 0
    num8 = 0

    #Error Handling for incorrect number of characters 
    while len(binary)!= 8:
        print("Please enter a valid value")
        binary = input("Enter rhe binary number you'd like to convert: ")
        if binary == 8:
            break

    #Processing the data and conversion
    #Checks to see if character 1 in the string binary is equal to "1" or "0"
        if binary[0] == "1":
            num1 = 128
        elif binary[0] == "0":
            num1 = 0
        else:
            print('Error, value 1 is not = to "1" or "0"')
            main()

        if binary[1] == "1":
            num2 = 64
        elif binary[1]:
            num2 = 0
        else:
            print('Error, value 2 is not = to "1" or "0"')
            main()


        if binary[2] == "1":
            num3 = 32
        elif binary[2] == "0":
            num3 = 0
        else:
            print('Error, value 3 is not = to "1" or "0"')
            main()

        if binary[3] == "1":
            num4 = 16
        elif binary[3] == "0":
            num4 = 0
        else:
            print('Error, value 4 is not = to "1" or "0"')
            main()


        if binary[4] == "1":
            num5 = 8
        elif binary[4] == "0":
            num5 = 0
        else:
            print('Error, value 5 is not = to "1" or "0"')
            main()


        if binary[5] == "1":
            num6 = 4
        elif binary[5] == "0":
            num6 = 0
        else:
            print('Error, value 1 is not = to "1" or "0"')
            main()


        if binary[6] == "1":
            num7 = 2
        elif binary[6] == "0":
            num7 = 0
        else:
            print('Error, value 1 is not = to "1" or "0"')
            main()


        if binary[7] == "1":
            num8 = 1
        elif binary[7] == "0":
            num8 = 0
        else:
            print('Error, value 1 is not = to "1" or "0"')
            main()


    #output and rerun
        print("The converted number is: ", num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8)
        choice = ' ' 
        while choice != "1" and choice != "2":
            choice = input("Would you like to perform another coversion?:\n[1]Yes\n[2]Naw\n")
        if choice == "1":
            main()
        elif choice == "2":
            exit()
        else:
            print("Error please select [1] or [2]")

    main()

我以为可以使用循环运行实际的转换部分?另外,我对python还不太新...是的,我先做谷歌吧。此外,main()下的所有东西都缩进了,我在stackoverflow上格式化代码时遇到了麻烦。

1 个答案:

答案 0 :(得分:1)

功能编程即将到来。小心!

import com.opencsv.CSVReader;

import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
/*
 * Created by JFormDesigner on Tue Sep 22 13:24:36 IST 2015
 */



/**
 * @author Avinash Raj
 */
public class FileChooser extends JFrame {
    private JFileChooser fileChooser1;
    public FileChooser() {
        initComponents();
    }

    private void fileChooser1ActionPerformed(ActionEvent e) {

        int returnVal = fileChooser1.showOpenDialog(FileChooser.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            //File file = fc.getSelectedFile();
            setVisible(false);
            String path=fileChooser1.getSelectedFile().getAbsolutePath();
            String filename=fileChooser1.getSelectedFile().getName();
            //This is where a real application would open the file.

            System.out.println("Opening: " + path + "\n");
            CSVReader reader = null;
            try {
                reader = new CSVReader(new FileReader(path), ',', '\'', 1);
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
            String [] nextLine;
            try {
                while ((nextLine = reader.readNext()) != null) {
                    // nextLine[] is an array of values from the line
                    int no_cols = nextLine.length;
                    System.out.println(nextLine[0] + nextLine[1] + nextLine[2] );
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        } else {
            setVisible(false);
            System.out.println("Open command cancelled by user." + "\n");
        }
    }



    private void initComponents() {
      fileChooser1 = new JFileChooser();

        setLayout(new BorderLayout());
        setSize(700,500);

        fileChooser1.addActionListener(e -> fileChooser1ActionPerformed(e));
        fileChooser1.setFileSelectionMode(JFileChooser.FILES_ONLY);
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "csv files only", "csv");
        fileChooser1.setFileFilter(filter);
        add(fileChooser1, BorderLayout.CENTER);

       setVisible(true);
        setLocationRelativeTo(getOwner());

    }


    public  static  void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                FileChooser f = new FileChooser();
            }
        });
    }
}