-2

i want to continue the loop for asking input(), i use "type(p) is not int" to check the alphabet number, but i get UnboundLocalError when i use "type(p) is not int"

def check(p):
    """
>>> get the value which is non-negative integer and not alphabet
    Checking if the input is negative or not.
    or repeat asking for input
    loop will terminate until positive integer
    """
    while p < 0 or type(p) is not int:
        p = float(input("Invaild response, please try again:"))
    return p

check("4")
check(4)

i want to continue the loop for asking input(), i use "type(p) is not int" to check the alphabet number, but i get UnboundLocalError when i use "type(p) is not int"

  • 1
    Please try to use correct upper case letters, e.g. in the beginning of your title, sentences or the word "I". This would be gentle to your readers. – buhtz Nov 21 '22 at 14:03
  • Python doesn't know what `p` is at the while loop. It is only created on the next line. Perhaps you should try adding `p = -1` on the line before the loop. – quamrana Nov 21 '22 at 14:04
  • replace `p` with `num` in your function body – whiplash Nov 21 '22 at 14:04
  • 2
    `p` is not defined at the first iteration. Also the check for `type(p) is not int` is a bit useless as `p = float(...)` so it will ***always*** be true... – Tomerikoo Nov 21 '22 at 14:12
  • 1
    The argument `4` or `"4"` to the function is unused and does nothing…?! – deceze Nov 21 '22 at 14:14

1 Answers1

0
def check(num):
    while type(num) is not int or num < 0:
        try:
            num = int(input("Invaild response, please try again:"))
        except ValueError:
            pass
    return num

      
check("4")

Outputs:

print(check(-4))

#Output: Invaild response, please try again:

print(check(4.2))

#Output: Invaild response, please try again:

print(check("4"))

#Output: Invaild response, please try again:

print(check(4))

#Output: 4
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34