简体   繁体   中英

Why is my code skipping the entire “for i in range” loop?

I've come across an issue where my code is skipping the for loop with all the input prompts and is going straight to the printing of the lists below the loop.

What is wrong and how can I fix this?

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, ) is equivalent to range(0) (see also: Should I add a trailing comma after the last argument in a function call? ).

But range(0) is an empty range. Iterating over it results in a loop with zero iterations, ie, the whole for loop is skipped.

If you want a loop that goes on until a break statement is encountered inside, use while True: instead of for i in range(0, ): .

You seem to be not using the i variable, but if you do want to count the iterations in such a loop, you can use itertools.count (see: Easy way to keep counting up infinitely or Count iterations in while loop ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM