2015-02-10 253 views
0

我在python 3中創建了一個4位密碼猜測器。我想確保只能輸入4位密碼而不是5或6位密碼。這是我迄今爲止的代碼。限制用戶輸入的數字量

print('your password will not be used or saved for later use you do not have to put in your real password') 
real_password = int(input("please enter your four digit phone password here:")) 
computer_guess = 0000 
guess_counter = 0 
yes = 'yes' 
no = 'no' 
print ("guessing your password...") 
while computer_guess < real_password: 
    computer_guess = computer_guess + 1 
    guess_counter = guess_counter + 1 
    print("guess number", guess_counter) 
print ("your password is", computer_guess) 
+1

'如果real_password> 9999:'?你的問題到底是什麼? – jonrsharpe 2015-02-10 17:07:27

回答

1

之前,你投的輸入爲int,其轉換爲STR代替,那麼你可以調用LEN()內置的方法來檢查輸入的字符串的長度。檢查documentation瞭解有關此方法的詳細信息。如果它大於4,那麼你應該回憶你的輸入呼叫。像下面這樣的東西應該工作:

>>> real_password = input("please enter your four digit phone password here: ") 
please enter your four digit phone password here: 1234 
>>> while len(str(real_password)) != 4: 
...  real_password = input("please enter your four digit phone password here: ") 

在這種條件下循環就不會跑了,但如果輸入的字符串不等於4,循環將運行,直到條件很滿意。

0
print('your password will not be used or saved for later use you do not have to put in your real password') 

def get_password(): 
    real_password = int(input("please enter your four digit phone password here:")) 
    if len(str(real_password)) != 4: # condition is not met if your variable 
     get_password()    # is not 4, easily changed if you 
    else:       # want 
     return real_password 

#define a method and ask it to call itself until a condition is met 
# 

real_password = get_password() # here the method is called and the return 
computer_guess = 0    # value is saved as 'real_password' 
guess_counter = 0 
yes = 'yes'     # these are not used in your code 
no = 'no'      # but I'm am sure you knew that 
print ("guessing your password...") 
while computer_guess != real_password: # your loop should break when the 
    computer_guess += 1    # is found, not some other implied 
    guess_counter += 1     # the '+=' operator is handy 
    print("guess number", guess_counter) 
print ("your password is", str(computer_guess)) # explicitly define the int 
               # as a string 

我希望幫助...