[英]Limiting the amount of numbers in a user input
I'm making a 4 digit password guesser in python 3. I want to make sure that you can only put in 4 digit passwords and not 5 or 6 digit passwords. 我正在python 3中创建4位数字密码猜测者。我想确保您只能输入4位数字密码,而不能输入5位或6位数字密码。 Here is the code I have so far.
这是我到目前为止的代码。
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)
Before you cast the input to an int, cast it to a str instead, then you can call the len() builtin method to check the length of the entered string. 在将输入强制转换为int之前,将其强制转换为str,然后可以调用len()内置方法来检查输入字符串的长度。 Check the documentation for details on this method.
检查文档以获取有关此方法的详细信息。 If it is greater than 4, then you should recall your input call.
如果它大于4,则应重新调用输入呼叫。 Something like the following should work:
类似于以下内容的东西应该起作用:
>>> 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: ")
In this condition the loop would not be ran, however if the entered string was not equal to 4, the loop would run until that condition was satisfied. 在这种情况下,不会运行循环,但是,如果输入的字符串不等于4,则循环将运行直到满足该条件。
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
I hope that helped... 希望对您有所帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.