簡體   English   中英

如果參數是表示有效 integer 的字符串,如何在 python 中創建返回語句?

[英]How to make a return statement in python if the argument is a string that represents a valid integer?

如果我寫一個主程序來測試它的函數 def as_integer(an_object) 和 def main()

如果參數是表示有效 integer 的字符串,則返回該 integer。否則,返回 NoneType object。

為列表中的每個元素調用 as_integer function:['20', 10, len, True, '-six', '-10', '0'] 和 output 結果 object 在它自己的行我應該得到以下output:

輸出:

20
None
None
None
None
-10
0

我開發了以下代碼,但仍然出現錯誤。

我只嘗試了我的代碼的第一部分,並得到 ['20', 10, len, True, '-10', '0'] 打印為 [20, 10, len, True, -10, 0]線。 但沒有引號。 那會有問題嗎?

我不確定是否使用 (isinstance) 或 (isdigit)。 我嘗試使用 (isdigit) 來檢測 an_object 是數字還是 (startswith) 是“-”,但我會收到錯誤消息。 這是我到目前為止所擁有的。 另外,感謝您在整個過程中的耐心等待。

def main():
    my_list = ['20', 10, len, True, '-10', '0']
    for an_object in my_list:
        print(as_integer(my_list))

def as_integer(an_object):
    if isinstance(an_object, (str, int)):
        return int(an_object)
    else:
        return None

我收到此錯誤:

#TEST 1#
main() returned None
inputs:

outputs:
**  ERROR  ** None
* EXPECTED * 20
None
None
None
None
**  ERROR  ** None
* EXPECTED * -10
**  ERROR  ** no line
* EXPECTED * 0
----------
#TEST 2#
** ERROR **as_integer(True) returned 1
* EXPECTED * None
inputs:

outputs:
----------
#TEST 3#
as_integer('43') returned 43
inputs:

outputs:
----------
#TEST 4#
as_integer('-50') returned -50
inputs:

outputs:
----------
#TEST 5#
as_integer(id) returned None
inputs:

outputs:
----------
def as_integer(value):
    if isinstance(value, str):
        try:
            return int(value)
        except ValueError:
            return None
    return None

這將為as_integer(10)返回None ,但也許這是您的用例。 您仍然可以使用isinstance(value, (str, int))擴展條件,但這將使True轉換為1 ,這在更多編程語言中是常見的和預期的。 為了解決這個極端情況,您可以and value not in (True, False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM