为什么没有函数循环,循环输入?

问题描述 投票:0回答:1

我想使用带有三个不同输入(1,2,3)的函数serial_circuit。该功能假设接受来自用户的多个输入,直到用户点击返回,结束程序并总结所有输入。程序只接受一个输入并显示它。

def serial_circuit(num1):
    num = 0
    while(True):
        try:
            num += num1
        except:
            break
        return num

print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")

if choice == '1':
    num1 = float(input("Enter resistor value: "))
    num = serial_circuit(num1)
    print(f"Total resistance = {(num)} ohms")

elif choice == '2':
    num1 = float(input("Enter coil value: "))
    num = serial_circuit(num1)
    print(f"Total inductance = {(num)} henrys")

elif choice == '3':
    num1 = float(input("Enter capacitor value: "))
    num = serial_circuit(num1)
    print(f"Total capacitance = {(num):.6f} farads")
python-3.7
1个回答
0
投票

你的一个问题是你在循环中有return语句 - 注意你的缩进 - 在循环的第一次迭代中,循环中发生的最后一件事就是从serial_circuit函数返回。另一个问题是你只需要输入一次 - 在循环之外。

看看这个解决方案:

def serial_circuit(text):
    num = 0
    finishedEntering = False

    while(not finishedEntering):
        try:
            received_input = input(text)
            if received_input == "":
                finishedEntering = True
            else:
                num1 = float(received_input)
                num += num1
        except:
            break
    return num

print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")

if choice == '1':
    num = serial_circuit("Enter resistor value or hit enter to finish: ")
    print(f"Total resistance = {(num)} ohms")

elif choice == '2':
    num = serial_circuit("Enter coil value or hit enter to finish: ")
    print(f"Total inductance = {(num)} henrys")

elif choice == '3':
    num = serial_circuit("Enter capacitor value or hit enter to finish: ")
    print(f"Total capacitance = {(num):.6f} farads")
© www.soinside.com 2019 - 2024. All rights reserved.