【问题标题】:Python 2.7 Random CodePython 2.7 随机代码
【发布时间】:2013-08-20 17:20:37
【问题描述】:

在 python 2.7 中,我正在尝试创建一个程序,该程序将生成一个介于 100000 和 999999999 之间的随机数,然后将其发送到用户电子邮件。到目前为止,它创建了一个随机数,然后将其发送到用户的电子邮件,但是当用户输入他们的代码时,它总是打印不正确。我该如何解决这个问题?

    code = random.randrange(100000, 99999999)

    entry = getpass.getpass('Code: ')
    if entry == code:   
        print 'Welcome!'
    else:
        print 'Incorrect!'

【问题讨论】:

  • entryint 吗?也许你需要`entry = str(getpass.getpass('Code: '))?
  • 如果通过电子邮件发送,用户应该如何输入?
  • 通过电子邮件发送的代码在哪里?它在code = 行和entry = 行之间,对吧?
  • @EricWilson, getpass.getpass 返回 str 对象。
  • 是的,代码位于 code= 和 entry= 之间,我只是将其丢弃以避免混淆。

标签: python python-2.7 random


【解决方案1】:

您将 int 对象(由 random.randrange 生成)与 str 对象(由 getpass.getpass 返回)进行比较; yield 始终为 false。

>>> 1 == '1'
False

code 转换为字符串。

>>> str(1) == '1'
True

或者,您可以将 entry 转换为 int。但是,您应该检查条目是否只包含数字或应该捕获 ValueError。

【讨论】:

  • 非常感谢。我永远不会猜到 random.randrange 会输出一个字符串。
  • @user2700766, random.randrange 返回一个 int,getpass.getpass 返回一个字符串。
【解决方案2】:

出于同样的原因4 == '4'False。您需要比较类似的数据类型。做

if int(entry) == code

if entry == str(code)

(另外,它是randrange,而不是randomrange

【讨论】:

  • 谢谢,我总是不小心输入 randomrange 谢谢你指出来。
猜你喜欢
  • 2016-11-06
  • 2018-03-25
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 2016-08-19
相关资源
最近更新 更多