如何为Python电阻色环程序输出添加'ohms'字符串?含用户选择分支
Fix: Modify Resistance Output to Include "ohms"
Let's adjust your code to produce the desired "X ohms" output, while also fixing a small hidden bug in the original code. Here's the revised version first, then we'll break down the changes:
option1 = input("Choose the First Colour\n0. Black\n1. Brown\n2. Red \n") option2 = input("Choose the Second Colour\n0. Black\n1. Brown\n2. Red\n") option3 = input("Choose the Third color\n0. Black\n2. Brown\n3. Red\n") Black, blue, red = 5, 4, 7 a = [] # Initialize the list outside conditionals to avoid errors if option1 == '0': a.append(Black) # Removed unnecessary print statements for option2/option3 - they weren't needed for the final output if option2 == '1': a.append(blue) if option3 == '3': a.append(red) # Combine list elements into a single string and add " ohms" resistance_value = ''.join(map(str, a)) print(f"{resistance_value} ohms")
Key Adjustments:
- Fixed list initialization: The original code only created the
alist inside the firstifblock. If the user didn't select '0' for the first color, this would cause an error later when trying to append items. We moveda = []to the top so it exists no matter what choices are made. - Cleaned up redundant prints: The original code printed
option2andoption3repeatedly, which cluttered the output without contributing to the final resistance value. We removed those lines to keep the code focused. - Rewrote the final output: Instead of looping through the list and printing each digit individually, we convert all elements to strings, join them into one number string, then use an f-string to append " ohms" for a clean, readable result.
When you input the correct options (0 for first color, 1 for second, 3 for third), the output will be:
547 ohms
内容的提问来源于stack exchange,提问作者Manlam Konyak Arolim
相关产品推荐
相关产品推荐

