简体   繁体   中英

Python: How do you get a programme to prompt the user a certian fixed amount of times for a user input?

In the programme the user must enter a password, if he gets it wrong the programme will prompt him 2 more times and if he does not get right those 2 times the programme will expire. How do I go about doing this. This is my programme so far...

password=input("Enter password:")
while password != 'cat': 
    print ("password is wrong, try it again")
    password= input ("Enter your password:")

print ("Password correct be happy")

The charitable programmer

for trial in range(3):
    print ("Attempt no.",trial, end=" ")
    passw = input('.  Enter password > ')
    if passw == 'cat' : break
else:
    passw = 'cat'

Yes, also the humble for loop has an else clause: "Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement." .

try this:

import sys
max_tries = 3; current_tries = 0
password=input("Enter password:")
while password != 'cat': 
    if current_tries > max_tries:
        print "too many tries"
        sys.exit(0)
    print ("password is wrong, try it again")
    password= input ("Enter your password:")
    current_tries +=1


print ("Password correct be happy")
max_tries = 3
password = None
for i in range(max_tries):
    password = input("Enter Password:")
    if password == "cat": break
if password != "cat": 
    print ("ERROR TOO MANY TRIES!")
else:
    print ("You Win!")

is a simple way to do it ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM