【问题标题】:Python: I need to include stepping values in the input query within a for loopPython:我需要在 for 循环中的输入查询中包含步进值
【发布时间】:2014-05-19 03:19:00
【问题描述】:

我必须使用 for 循环来收集用户输入值的数据:

Number of electrodes: 5
Current in Electrode #1: 10
Current in Electrode #2: 211
Current in Electrode #3: 350
Current in Electrode #4: 410
Current in Electrode #5: 220

并使用 for 循环(必须是 for 循环)为输入创建提示,如上所示

目前我的代码如下所示:

cap=int(input("Number of capacitors: "))
for num in range(cap):
    val=num+1
    input("Current in Electrode#",val)

但我遇到了问题,因为您显然不能在这样的输入语句中具有值...?我基本上不知道如何在由 for 循环创建的输入语句中单步执行数字。请帮忙!

【问题讨论】:

    标签: python loops for-loop input


    【解决方案1】:

    以下代码应该适合您:

    cap = int(input("Number of electrodes: "))
    info = []
    for i in range(1, cap+1):
        current = int(input("Current in Electrode #"+str(i)+": "))
        info.append(current)
    
    print info
    

    运行如下:

    Number of electrodes: 5
    Current in Electrode #1: 45
    Current in Electrode #2: 12
    Current in Electrode #3: 786
    Current in Electrode #4: 120
    Current in Electrode #5: 210
    [45, 12, 786, 120, 210]
    

    这使用for 循环来获取您想要的每个数字,然后转换为字符串,以便我们可以进行字符串连接。您的问题可能是您没有转换为首先是一个字符串。

    【讨论】:

    • current 应该是int
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2019-01-18
    • 2021-12-09
    • 2021-04-08
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    相关资源
    最近更新 更多