限制用户输入中的数字量

时间:2015-02-10 17:05:41

标签: python python-3.x

我在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)

2 个答案:

答案 0 :(得分: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,循环将一直运行直到满足该条件。

答案 1 :(得分: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

我希望有帮助...