2017-09-08 22 views
0

我想以某種方式執行我的def函數,如果它的參數中遇到None,它將返回一個空格,否則它將測量它的長度。如何執行我的程序,如果它的參數在python中遇到無

def get_display_info(dice_to_roll_again_str, dice_set_aside_str): 
    length1 =len(dice_to_roll_again_str) 
    if dice_set_aside_str == None: 
     return ' ' 
    else : 
     length2 =len(dice_set_aside_str) 
    if length2 != None: 
     if length1 and length2 > 0: 
      return "(Dice to roll again:" + str(dice_to_roll_again_str) +','+ "Dice set aside:" + str(dice_set_aside_str) + ')' 
     elif length1 > 0: 
      return "(Dice to roll again:" + str(dice_to_roll_again_str) + ')' 
     elif length2 > 0: 
      return "(Dice set aside:" + str(dice_set_aside_str) + ')' 

回答

0

你好阿德里安,

參考

1.什麼是空值或無關鍵字
http://pythoncentral.io/python-null-equivalent-none/

2.格式()函數
https://pyformat.info/

3的Python學習的Begniner
- https://www.tutorialspoint.com/python/(Beginer爲最佳) - https://www.learnpython.org/
- https://www.javatpoint.com/python-tutorial
- https://docs.python.org/3/tutorial/
- https://www.python.org/dev/peps/pep-0008/(編碼Stadered)
- https://docs.python.org/2/library/functions.html(Python的內置功能)

Your Mistack

當查看字符串長度時不要與None比較,而是與null, "", '', isEmpty()...etc比較各種功能。

建議

你是寫的所有條件的錯誤又沒條件適當所以寫適當的條件下,用編碼標準,所以要讀Python文檔更強大的程序更多的參考。

解決方案

我給的解決方案,但不會改變所有condtion,因爲我不知道你寫的是什麼項目,什麼。

def get_display_info(dice_to_roll_again_str, dice_set_aside_str): 
     if dice_set_aside_str == '': 
     return ' ' 
     else : 
     length2 =len(dice_set_aside_str) 

     if dice_to_roll_again_str == '': 
     return ' ' 
     else : 
     length1 =len(dice_to_roll_again_str) 

     if length2 != 0 and length1!=0: 
     if length1==1 and length2==1: 
      return "(Dice to roll again:{}".format(str(dice_to_roll_again_str))+",Dice set aside:{}".format(str(dice_set_aside_str))+")" 
     elif length1 > 1: 
      return "(Dice to roll again:{}".format(str(dice_to_roll_again_str))+")" 
     elif length2 > 1: 
      return "(Dice set aside:{}".format(str(dice_set_aside_str))+")" 

print get_display_info("vora","m") 

如果有任何查詢請這麼評論。
我希望我的回答是幫助完整。

+0

我不明白有關.format因爲我是新來的programming.Anyway我測試了它和它的作品爲一個參數 – Adrian

+0

但是當我嘗試落實到程序它說縮進錯誤 – Adrian

+0

你好阿德里安我在我的答案中添加更多鏈接,所以首先閱讀本教程如此容易理解或任何功能不明白如此搜索谷歌它給最好的答案... –

1

無真假測試用文字完成:

if dice_set_aside_str is not None: 
    return 0 

任何iterable沒有任何項目解析爲False布爾測試。所以做空字符串,無。這個我們可以結合:

if not dice_set_aside_str: 
    return 0 
else: 
    return len(dice_set_aside_str) 
相關問題