2014-03-25 27 views
2

所以這就是我想要做的。我有一個特殊的目錄做相當多的文件夾,我的電腦隱藏的東西對我有4個級別的文件夾,使用文件夾每個文件夾編號爲1 - 4試圖使這個python程序工作

例子:

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將打開(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

您可以測試輸入,以確保所有的數字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 

這,添加到你的代碼的開始,應該工作。你的代碼絕對可以更簡潔,但這不是我的地方去糾正你。

+0

無需輸入str(raw_input ...),因爲'raw_input'總是輸出一個字符串類型,不管你輸入了一個數字還是這個檢查不能保護你的五位或更多位數。可以在這裏輸入'4444444444',它仍然有效 – Manhattan

+0

我簡單地複製了OP針對引腳變量的賦值行,並且長度的實現很簡單,只需測試len(pin)= 4就可以了,這不是問題的一部分,然而,只限於範圍(1,5)。 – Luigi

1

你可以使用正則表達式。正則表達式總是一個好朋友。

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() 
+0

總是一個強詞。http://programmers.stackexchange.com/questions/223634/what-is-meant-by-now-you-have-two -問題 – Dannnno

1

首先,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的東西,它仍然滿足包含檢查(儘管由於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 
>>> 

希望這有助於。