python - 在 Python 3.4.3 中使用 001 时 token 无效

标签 python python-3.4

我已在网上寻找解决此问题的方法,但未找到任何相关内容。我的类(class)作业要求我编写一个程序,让计算机尝试猜测用户输入的数字。该数字需要介于 001 和 100 之间,因此我首先尝试确保用户只能输入该范围内的数字。

我目前的代码:

import random
code=(int(input("Input a three digit code. Must be more than 001 and less than 100.")))
print(code)
if (code < 001) or (code > 100): 
    print ("Invalid code")
elif (code > 001) or (code < 100):
    print ("Valid code") 

它在 001 更改为 1 时工作正常,但如果我用 001 运行它,我会收到无效 token 错误。 这需要在 Python 3.4.3 中完成。 任何形式的帮助将不胜感激。

最佳答案

Python 中整数不能有前导零。前导零以前(Python 2)用于表示八进制数字。由于许多人不知道这一点并且对为什么 070 == 56 感到困惑,Python 3 使前导零成为非法。

您不应将 code 转换为整数 - 仅将实际数字(您打算用于计算的数字)存储在数值变量中。保留字符串:

while True:
    code = input("Input a three digit code. Must be more than 001 and less than 100.")
    try:
        value = int(code)
    except ValueError:
        print("Invalid code")
        continue
    if 1 <= value <= 100: 
        print ("Valid code")
        break
    else:
        print ("Invalid code") 

关于python - 在 Python 3.4.3 中使用 001 时 token 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384144/

相关文章:

python - 从一个 csv 文件中选择特定列并在 python 中写入另一个文件时出错

python - 使用窗口函数在 Postgres 上使用 SqlAlchemy 限制查询

python - 如何为 Apache Beam 中的复合变换提供参数?

python - Pygame:一个方 block 使其他方 block 弹跳

python - salesforce python Beatbox 导入错误

python - 使用 pip3 卸载 Python 包

python - 是否可以使用 Pulumi 创建 Azure 服务主体?

python - 总结numpy数组中的非零元素

python - NoReverseMatch at/Reverse 未找到 'post_detail'

python - 为什么 asyncio 的事件循环会抑制 Windows 上的 KeyboardInterrupt?