2015-02-10 2 views
0

Я делаю 4-значный пароль угадывателя в python 3. Я хочу убедиться, что вы можете вводить только 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

ответ

1

Перед тем, как бросить вход на междунар, брось на ул вместо этого, то вы можете позвонить в 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 

Я надеюсь, что помог ...

Смежные вопросы