繁体   English   中英

试图使这个Python程序工作

[英]Trying to make this python program work

所以这就是我想要做的。 我在计算机上的特殊目录中有很多文件夹可以藏起​​来。我有4个级别的文件夹,每个文件夹的文件夹编号为1-4。

例:

1>1>1>1
1>1>1>2
...
1>2>1>1
...
4>1>1>1
...
4>4>4>4

我编写了一个python程序,要求输入图钉,然后打开与图钉对应的文件目录。 [例如。针号4322将打开4> 3> 2> 2]。 我遇到的唯一问题是我无法将输入限制为仅1-4,并且当我输入此范围之外的数字时,Internet Explorer会打开(UGH!IE)。

这是代码...(Python 2.7.6)

pin=str(raw_input("What is your 4-digit pin number? "))
intpin=int(pin)
#==============##==============#
pin1=pin[0:1]
pin2=pin[1:2]
pin3=pin[2:3]
pin4=pin[3:4]
#==============##==============#
ipin1=int(pin1)
ipin2=int(pin2)
ipin3=int(pin3)
ipin4=int(pin4)
#==============##==============#
print("")
print pin1
print pin2
print("")
path=("D:/Documents/Personal/"+pin1+"/"+pin2+"/"+pin3+"/"+pin4)
import webbrowser as wb
wb.open(path)
#==============##==============#
print("Thank You!")
print("Your window has opened, now please close this one...")

您可以测试输入以确保所有输入都是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

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

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

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(raw_input...证明如下:

>>> d = raw_input("What is your 4-digit number? ")
What is your 4-digit number? 5
>>> print type(d)
<type 'str'>

其次,接受的答案不能保护您免受超过4位数字的输入的影响。 即使输入12341234也将被接受,因为它无法检查传入的字符串的长度。

一种解决方法是不检查字符串,而是检查等效的整数。 您所需的范围只是[1111, 4444] 在这一点上,可以使用assert所以当他们输入低于或高于该值的任何内容时,您都可以引发断言错误。 但是,这样做的一个1111.4是可以传递类似1111.4 ,该内容仍满足包含检查的要求(尽管由于ValueError而在转换时失败)。

考虑到以上因素,这是您的代码的另一种选择。

def is_valid(strnum):

    # Returns false when inputs like 1.2 are given.
    try:
        intnum = int(strnum)
    except ValueError, e:
        return False

    # Check the integer equivalent if it's within the range.
    if 1111 <= intnum <= 4444:
        return True
    else: return False

strnum = raw_input("What is your 4-digit PIN?\n>> ")
# print is_valid(strnum)

if is_valid:
    # Your code here...

一些测试如下:

# 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
>>> 

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM