试图使这个python程序工作

试图使这个python程序工作,python,input,range,directory,Python,Input,Range,Directory,这就是我要做的。我有相当多的文件夹在我的电脑上的一个特殊目录下隐藏的东西。我有4个文件夹级别,每个文件夹的文件夹编号为1-4 例如: 1>1>1>1 1>1>1>2 ... 1>2>1>1 ... 4>1>1>1 ... 4>4>4>4 我编写了一个python程序来请求pin,然后打开与pin对应的文件目录。[例如,针脚4322将打开4>3>2>2]。我唯一的问题是我不能将输入限制在数字1-4,当我输入

这就是我要做的。我有相当多的文件夹在我的电脑上的一个特殊目录下隐藏的东西。我有4个文件夹级别,每个文件夹的文件夹编号为1-4

例如:

1>1>1>1
1>1>1>2
...
1>2>1>1
...
4>1>1>1
...
4>4>4>4
我编写了一个python程序来请求pin,然后打开与pin对应的文件目录。[例如,针脚4322将打开4>3>2>2]。我唯一的问题是我不能将输入限制在数字1-4,当我输入一个超出这个范围的数字时,internet explorer就会打开(呃!IE)

这是密码。。。。(Python 2.7.6)


您可以测试输入,以确保所有数字都是1-4:

bol = False
while bol == False:
    pin=str(raw_input("What is your 4-digit pin number? "))
    for digit in pin:
        if int(digit) in [1,2,3,4]:
            bol = True
        else:
            print "invalid pin"
            bol = False
            break

添加到代码开头的代码应该可以工作。您的代码肯定会更简洁,但这不是我可以纠正您的地方。

您可以使用正则表达式。Regex总是一个好朋友

import re
if not re.match("^([1-4])([1-4])([1-4])([1-4])$", pin):
        print "Well that's not your pin, is it?"
        import sys
        sys.exit()

首先,
raw_input
始终输出字符串,无论您是否输入数字。您不需要执行
str(原始输入…
)。证明如下:

>>> d = raw_input("What is your 4-digit number? ")
What is your 4-digit number? 5
>>> print type(d)
<type 'str'>
# On decimal/float-type inputs.
>>> 
What is your 4-digit PIN?
>> 1.2
False
>>> 
# On below or above the range wanted.
>>> 
What is your 4-digit PIN?
>> 5555
False
>>> 
What is your 4-digit PIN?
>> 1110
False
>>> 
What is your 4-digit PIN?
>> 1234
True
>>> 
一些测试如下:

>>> d = raw_input("What is your 4-digit number? ")
What is your 4-digit number? 5
>>> print type(d)
<type 'str'>
# On decimal/float-type inputs.
>>> 
What is your 4-digit PIN?
>> 1.2
False
>>> 
# On below or above the range wanted.
>>> 
What is your 4-digit PIN?
>> 5555
False
>>> 
What is your 4-digit PIN?
>> 1110
False
>>> 
What is your 4-digit PIN?
>> 1234
True
>>> 

希望这有帮助。

总是一个强有力的词。没有必要做
str(原始输入…
因为无论您是否输入数字,原始输入总是输出字符串类型。此外,此检查不保护您不受五位或五位以上数字的影响。我可以在此处输入
4444
,它仍然有效。我只是为pin变量复制了OP的赋值行。以及leng的实现这很简单,只要测试len(pin)=4。然而,这不是问题的一部分,仅限于范围(1,5)。