【问题标题】:Python 2.7 Control FlowPython 2.7 控制流
【发布时间】:2015-05-11 20:08:27
【问题描述】:

我目前有一个小问题: 我正在为我的机器人创建一个“命令”,一个小的密码生成器,目前,我已经有了命令本身,它会像这样

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。 谢谢。

【问题讨论】:

  • if 语句中的 : 在哪里,应该遵循它的缩进套件在哪里?
  • length = Argument[0] if Argument[0] else 12
  • 感谢 Peter Wood,您已修复它! @彼得伍德

标签: python python-2.7 controls flow password-generator


【解决方案1】:

假设Argument 是一个列表,您可以尝试检索长度值,如果Argument 为空,即引发IndexError,则为length 提供所需的默认值:

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

处理其他类型的错误输入,例如负值,None 值,使用简单的if 语句或三元赋值就足够了。

【讨论】:

    【解决方案2】:

    根据你所拥有的,尝试:

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

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 2018-01-19
      • 2017-05-27
      • 2011-08-06
      • 1970-01-01
      • 2016-09-23
      • 2016-12-30
      • 2020-08-22
      • 2011-12-29
      相关资源
      最近更新 更多