Minuit
Minuit

Reputation: 15

Input Validation infinite Loop

    groupno = int(input('Please enter the size of group: '))
    while groupno >= 1 or groupno <= 20:
        groupsizes= int(input('Please enter a valid group size: '))
    g.append(groupno)

Ok so once i use this code if i enter a value above 20 or less than one it looped infinitely to enter the correct group size. This also applied to a meal rating system using the same algorithm

Upvotes: 0

Views: 137

Answers (4)

MattH
MattH

Reputation: 38247

Try this?

>>> def get_groupno():
...     groupno = 0
...     while not  1 <= groupno <= 20:
...         try:
...             groupno = int(input('Please enter a valid group size: '))
...         except ValueError:
...             continue
...     return groupno
...
>>> get_groupno()
Please enter a valid group size: 100
Please enter a valid group size: 0
Please enter a valid group size: 1
1

Upvotes: 0

Tim
Tim

Reputation: 43314

In addition to Elliot's answer, your while condition looks flawed, you should change it to this

while groupno <= 1 or groupno >= 20:

Assuming you want a group size between 1 and 20

Upvotes: 0

jarondl
jarondl

Reputation: 1663

A value above 20 is also above 1, so the first part of the or statement is true.

You want:

not ( 1 < groupno < 20)

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

You need to update groupno in your while loop

while groupno >= 1 or groupno <= 20:
    # groupsizes= int(input('Please enter a valid group size: '))
    groupno = int(input('Please enter a valid group size: '))

Upvotes: 1

Related Questions