-1

In a Python 'while' loop that is collecting user input, is there a way to put a condition on the last loop? The user determines the number of loops but I want to put a condtion on the last input to be greater or equal to 1.

I already have a general value error to ensure no inputs are string. I would want float inputs for the first x amount of inputs but then limit the last one to 1 or more.

while True:
    try:
        for x in range(itemNum):
            globals ()['itemValue%s' % x] =float(input("Enter value for "+(globals()['itemName%s' % x])+(": ")))
    except ValueError:
        print("Sorry, Please enter only numbers. Try again.")
        continue
    else:
        break
smci
  • 32,567
  • 20
  • 113
  • 146
jDog
  • 11
  • 3
  • 3
    just separate the last input. Iterate first for loop till `itemNum - 1`. And then have the last input() separately. – vb_rises May 20 '19 at 01:21
  • So, items `0..(itemNum-2)` are totally unconstrained, they could be string, whitespace, empty, scientific notation, complex number, emoji of cats, whatever? Anyway as @Vishal says, just keep a while-loop counter `i`, and apply piecewise checking depending on `i < itemNum - 1` or `i == itemNum - 1`, that should go outside the `try...except ValueError` clause, or use `if..else` instead. And only increment the loop-counter `i` when you get valid input, i.e. if it fails the check, just `break/continue` before the counter can get incremented. – smci May 20 '19 at 01:25
  • If you're ready to create dynamically named globals, you're ready to learn about lists. – Ry- May 20 '19 at 01:33

1 Answers1

0

You can add if condition in your for loop to check for the last iteration:

for x in range(itemNum):
    # check for the last iteration
    if x == itemNum-1:
        # do your stuff here
Mahmoud Elshahat
  • 1,873
  • 10
  • 24