【问题标题】:Why is my code skipping the entire "for i in range" loop?为什么我的代码会跳过整个“for i in range”循环?
【发布时间】:2021-06-21 12:38:53
【问题描述】:

我遇到了一个问题,我的代码正在跳过带有所有输入提示的 for 循环,并直接打印循环下方的列表。

出了什么问题,我该如何解决?

import statistics

Age = list()
SaturnRT = list()
MarsRT = list()
Mars = list()
Saturn = list()
Houses = ['saturn', 'Saturn', 'Mars', 'mars']
CheckList = ['Saturn', 'saturn']
ReactionTime = list()
inputVar = None


for i in range(0, ):
    print("enter age: ")
    while inputVar != type(int):
        try:
            inputVar = int(input())
            while inputVar>16 or inputVar<12:
                print("error! invalid entry")
                inputVar = int(input("enter the age: "))
            break
        except:
            print("enter an integer! ")
    Age.append(inputVar)

    print("enter reaction time (ms): ")
    while inputVar != type(float):
        try:
            inputVar = float(input())
            while inputVar < 0 or inputVar > 500:
                print("enter a valid time! ")
                inputVar = float(input())
            House = str(input("enter the house: "))
            while House not in Houses:
                print("error! invalid entry")
                House = str(input("enter the house: "))
            if House in CheckList:
                SaturnRT.append(inputVar)
                Saturn.append(House)
            else:
                MarsRT.append(inputVar)
                Mars.append(House)
            break
        except:
            print("enter an valid time! ")
    ReactionTime.append(inputVar)

print(SaturnRT)
print(MarsRT)
print("saturn reaction times avg: ", statistics.mean(SaturnRT))
print("saturn fastest time: ", min(SaturnRT))
print("saturn slowest time: ", max(SaturnRT))
print("mars reaction times avg: ", statistics.mean(MarsRT))
print("mars fastest time: ", min(MarsRT))
print("mars slowest time: ", max(MarsRT))

print(ReactionTime)
print(Age)

【问题讨论】:

  • 你认为range(0, )是什么意思?
  • 可能是无限循环

标签: python python-3.x loops range


【解决方案1】:

range(0, ) 等同于 range(0)(另请参见:Should I add a trailing comma after the last argument in a function call?)。

但是range(0) 是一个空范围。对其进行迭代会导致迭代次数为零的循环,即跳过整个 for 循环。

如果您希望循环一直持续到内部遇到break 语句,请使用while True: 而不是for i in range(0, ):

您似乎没有使用i 变量,但如果您确实想在这样的循环中计算迭代次数,您可以使用itertools.count(参见:Easy way to keep counting up infinitelyCount iterations in while loop):

>>> import itertools
>>> for i in itertools.count():
...     print(i)
...     if i > 3:
...         break
... 
0
1
2
3
4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2013-02-05
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多