我想继续输入()的循环,我使用"type(p)不是"检查字母数字,但我得到UnboundLocalError时,我使用"类型(p)不是">
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)
我想继续循环询问input(),我使用"type(p)不是"检查字母数字,但我得到UnboundLocalError时,我使用"类型(p)不是">
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")
输出:
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