You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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:

  1. Fixed list initialization: The original code only created the a list inside the first if block. If the user didn't select '0' for the first color, this would cause an error later when trying to append items. We moved a = [] to the top so it exists no matter what choices are made.
  2. Cleaned up redundant prints: The original code printed option2 and option3 repeatedly, which cluttered the output without contributing to the final resistance value. We removed those lines to keep the code focused.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:51:57