簡體   English   中英

Python 2.7控制流程

[英]Python 2.7 Control Flow

我目前有一個小問題:我正在為我的機器人制作一個“命令”,一個小的密碼生成器,目前,我已經有了該命令本身,它將像這樣

if Command.lower() == '!pwgen' #First message, the user calls the command
length = Argument[0] #The length he wants, Argument[0] == the length
import os, random, string 
length = 13
chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random.seed = (os.urandom(1024))
password = ''.join(random.choice(chars) for i in range(length))
messages.Main(password,xSock,BotID)

有一個問題,我想確保,如果參數為空,我希望密碼生成器使用默認數字,例如12,因此如果用戶未指定長度,則長度將為12。 謝謝。

假設Argument是一個列表,您可以嘗試檢索長度的值,並且如果Argument為空,即引發IndexError ,則為length所需的默認值:

try:
    length = Argument[0]
except IndexError as error:
    length = 12

要處理其他類型的錯誤輸入,例如負值, None值,使用簡單的if語句或三元賦值就足夠了。

根據您所擁有的,嘗試:

length = Argument[0] if len(Argument)>0 and Argument[0] is not None else 12

暫無
暫無

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

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