Python公制单位转换代码简化与优化建议咨询
Hey there! Huge congrats on building your first metric unit converter—this is such a solid first project for a new Python learner, great work getting hands-on practice so early in your journey! Let's take a look at your code and go through some ways to make it cleaner, more maintainable, and less repetitive.
First, here's your original code for reference:
# User's original code Scale_1 = input("What scale would you like to convert from? [KG/HG/DAG/G/DG/CG/MG]") Scale_2 = input("What scale would you like to convert to? [KG/HG/DAG/G/DG/CG/MG] ") Num_1_Con = float(input("What number/amount would you like to convert?")) KG = "Kilogram" HG = "Hectogram" DAG = "Decagram" G = "Gram" DG = "Decigram" CG = "Centigram" MG = "Milligram" Yes = "Yes" No = "No" if Scale_1 == "KG": if Scale_2 == "HG": print("Your answer is:") print(Num_1_Con * 10) print("Hectograms") elif Scale_2 == "DAG": print("Your answer is:") print(Num_1_Con * 100) print("Decagrams") elif Scale_2 == "G": print("Your answer is:") print(Num_1_Con * 1000) print("Grams") elif Scale_2 == "DG": print("Your answer is:") print(Num_1_Con * 10000) print("Centigrams") # Bug: Should be Decigrams elif Scale_2 == "CG": print("Your answer is:") print(Num_1_Con * 100000) print("Centigrams") elif Scale_2 == "MG": print("Your answer is") print(Num_1_Con * 1000000) print("Milligrams") else: print("Something went wrong please try again!") if Scale_1 == "HG": if Scale_2 == "KG": print("Your answer is: ") print(Num_1_Con / 10) print("Kilograms") if Scale_2 == "DAG": print("Your answer is: ") print(Num_1_Con * 10) print("Decagrams") if Scale_2 == "G": print("Your answer is: ") print(Num_1_Con * 100) print("Grams") if Scale_2 == "DG": print("Your answer is: ") print(Num_1_Con * 1000) print("Decigrams") if Scale_2 == "CG": print("Your answer is: ") print(Num_1_Con * 10000) print("Centigrams") if Scale_2 == "MG": print("Your answer is: ") print(Num_1_Con * 100000) print("Milligrams") if Scale_1 == "DAG": if Scale_2 == "KG": print("Your answer is: ") print(Num_1_Con / 100) print("Hectograms") # Bug: Should be Kilograms if Scale_2 == "HG": print("Your answer is: ") print(Num_1_Con / 10) print("Hectograms") if Scale_2 == "G": print("Your answer is: ") print(Num_1_Con * 10) print("Grams") if Scale_2 == "DG": print("Your answer is: ") print(Num_1_Con * 100) print("Decigrams") if Scale_2 == "CG": print("Your answer is: ") print(Num_1_Con * 1000) print("Centigrams") if Scale_2 == "MG": print("Your answer is: ") print(Num_1_Con * 10000) print("Milligrams") if Scale_1 == "G": if Scale_2 == "KG": print("Your answer is: ") print(Num_1_Con / 1000) print("Hectograms") # Bug: Should be Kilograms if Scale_2 == "HG": print("Your answer is: ") print(Num_1_Con / 100) print("Hectograms") if Scale_2 == "DAG": print("Your answer is: ") print(Num_1_Con / 10) print("Decagrams") if Scale_2 == "DG": print("Your answer is: ") print(Num_1_Con * 10) print("Decigrams") if Scale_2 == "CG": print("Your answer is: ") print(Num_1_Con * 100) print("Centigrams") if Scale_2 == "MG": print("Your answer is: ") print(Num_1_Con * 1000) print("Milligrams") if Scale_1 == "DG": if Scale_2 == "KG": print("Your answer is: ") print(Num_1_Con / 10000) print("Hectograms") # Bug: Should be Kilograms if Scale_2 == "HG": print("Your answer is: ") print(Num_1_Con / 1000) print("Hectograms") if Scale_2 == "DAG": print("Your answer is: ") print(Num_1_Con / 100) print("Decagrams") if Scale_2 == "G": print("Your answer is: ") print(Num_1_Con / 10) print("Grams") if Scale_2 == "CG": print("Your answer is: ") print(Num_1_Con * 10) print("Centigrams") if Scale_2 == "MG": print("Your answer is: ") print(Num_1_Con * 100) print("Milligrams") if Scale_1 == "CG": if Scale_2 == "KG": print("Your answer is: ") print(Num_1_Con / 100000) print("Hectograms") # Bug: Should be Kilograms if Scale_2 == "HG": print("Your answer is: ") print(Num_1_Con / 10000) print("Hectograms") if Scale_2 == "DAG": print("Your answer is: ") print(Num_1_Con / 1000) print("Decagrams") if Scale_2 == "G": print("Your answer is: ") print(Num_1_Con / 100) print("Grams") if Scale_2 == "DG": print("Your answer is: ") print(Num_1_Con / 10) print("Decigrams") if Scale_2 == "MG": print("Your answer is: ") print(Num_1_Con * 10) print("Milligrams") if Scale_1 == "MG": if Scale_2 == "KG": print("Your answer is:") print(Num_1_Con / 1000000) print("Kilograms") elif Scale_2 == "HG": print("Your answer is:") print(Num_1_Con / 100000) print("Hectograms") elif Scale_2 == "DAG": print("Your answer is:") print(Num_1_Con / 10000) print("Decagrams") elif Scale_2 == "G": print("Your answer is:") print(Num_1_Con / 1000) print("Grams") elif Scale_2 == "DG": print("Your answer is:") print(Num_1_Conn / 100) # Bug: Typo, should be Num_1_Con print("Decigrams") elif Scale_2 == "CG": print("Your answer is") print(Num_1_Con / 10) print("Centigrams") else: print("Something went wrong please try again!") while True: input("What scale would you like to start with?")
Quick Fixes & Key Improvements to Make
Let's break down the most impactful changes you can make:
Fix tiny bugs first: You've got a few small typos and wrong unit labels scattered around—like when converting KG to DG, you print "Centigrams" instead of "Decigrams"; in the MG to DG section, you wrote
Num_1_Conn(extra 'n'); and many conversions (like G to KG) print the wrong unit name. These are easy to miss but make the output incorrect, so go through and double-check those print statements!Ditch nested ifs with a conversion dictionary: Right now you're writing tons of if-elif blocks for every unit pair. Instead, map each unit to its equivalent in grams (the base unit), then converting is just simple math. For example:
unit_map = { "KG": (1000, "Kilograms"), "HG": (100, "Hectograms"), # ... rest of the units }Then to convert:
total_grams = amount * unit_map[scale1][0]andresult = total_grams / unit_map[scale2][0]. One line of math instead of hundreds of lines of ifs!Simplify output: Instead of three separate print statements per result, use an f-string to combine everything into one line:
print(f"Your answer is: {result} {unit_map[scale2][1]}")Clean, concise, and easier to read.
Add input validation: Right now, if someone types "kg" (lowercase) or "kilo" by mistake, the code does nothing. Add a check to ensure users input valid units, and loop until they get it right. You can even make it case-insensitive!
Finish the loop for repeated use: Your final
while Trueline is a great start—wrap the entire conversion logic inside that loop so users can convert multiple times without restarting the program. Add a prompt to let them quit when they're done too!
Example Optimized Code
Here's a condensed, fixed version of your code using all these tips:
def get_valid_input(prompt, valid_options): """Helper function to get and validate user input""" while True: user_input = input(prompt).strip().upper() if user_input in valid_options: return user_input print(f"Invalid input! Please choose from: {', '.join(valid_options)}") # Define unit conversions (value in grams) and their full names unit_map = { "KG": (1000, "Kilograms"), "HG": (100, "Hectograms"), "DAG": (10, "Decagrams"), "G": (1, "Grams"), "DG": (0.1, "Decigrams"), "CG": (0.01, "Centigrams"), "MG": (0.001, "Milligrams") } valid_units = list(unit_map.keys()) print("Welcome to the Metric Unit Converter!") while True: # Get valid unit inputs scale_from = get_valid_input( "\nWhat scale would you like to convert from? [KG/HG/DAG/G/DG/CG/MG]: ", valid_units ) scale_to = get_valid_input( "What scale would you like to convert to? [KG/HG/DAG/G/DG/CG/MG]: ", valid_units ) # Get numeric amount with validation while True: try: amount = float(input(f"Enter the amount of {unit_map[scale_from][1]} to convert: ")) break except ValueError: print("Please enter a valid number!") # Calculate conversion grams_from = amount * unit_map[scale_from][0] result = grams_from / unit_map[scale_to][0] # Print formatted result print(f"\nYour answer is: {result} {unit_map[scale_to][1]}") # Ask to continue or quit again = get_valid_input("\nWould you like to convert another unit? [YES/NO]: ", ["YES", "NO"]) if again == "NO": print("Thanks for using the converter! Bye!") break
This version is way shorter, easier to update (just add one line to unit_map if you want new units), handles bad inputs gracefully, and lets users convert as many times as they want. Keep up the great practice—building projects like this is the best way to learn! 😊




