2017-04-30 1751 views
-1

TypeError: '<' not supported between instances of 'NoneType' and 'int'Python類型錯誤 - 類型錯誤:'<'不支持'NoneType'和'int'的實例

我在Stack Overflow找了個答案,發現我應該帶一個int(輸入(提示符) ),但是這就是我

def main():  
while True: 
     vPopSize = validinput("Population Size: ") 
     if vPopSize < 4: 
      print("Value too small, should be > 3") 
      continue 
     else: 
      break 

def validinput(prompt): 
while True: 
    try: 
     vPopSize = int(input(prompt)) 
    except ValueError: 
     print("Invalid Entry - try again") 
     continue 
    else: 
     break 
+1

您將需要添加'的'高清ValidInput的(提示)返回vPopSize':' – abccd

+0

問題是不是輸入。 Python會隱式地從有效的輸入函數中返回None。並且這裏有兩個不同的'vPopSize'變量 –

+0

感謝您的編輯,我會使'validinput'布爾值 –

回答

0
Try: 
    def validinput(prompt): 
    print(prompt) # this one is new!! 
    while True: 
     try: 
      vPopSize = int(input(prompt)) 
     except ValueError: 
      print("Invalid Entry - try again") 
      continue 
     else: 
      break 

而當函數被調用時,你會發現。

問題是validinput()不會返回任何東西。你不得不返回vPopSize

+0

! –

1

,你需要在你的函數添加一回,讓你輸入的號碼,否則它返回一個隱含的無

def validinput(prompt): 
    while True: 
     try: 
      return int(input(prompt)) 
      # there is no need to use another variable here, just return the conversion, 
      # if it fail it will try again because it is inside this infinite loop 
     except ValueError: 
      print("Invalid Entry - try again") 


def main():  
    while True: 
     vPopSize = validinput("Population Size: ") 
     if vPopSize < 4: 
      print("Value too small, should be > 3") 
      continue 
     else: 
      break 

或在評論中指出,讓ValidInput的還檢查它是否是一個合適的值

def validinput(prompt): 
    while True: 
     try: 
      value = int(input(prompt)) 
      if value > 3: 
       return value 
      else: 
       print("Value too small, should be > 3") 
     except ValueError: 
      print("Invalid Entry - try again") 


def main():  
    vPopSize = validinput("Population Size: ") 
    # do stuff with vPopSize 
+0

非常感謝!我想我會讓自己陷入思考,回報是隱含的!真的,真的,但你去...再次感謝。 – Dino3GL

相關問題