Issue
So I was just trying to understand the while
loop in python 3 by creating a simple password-unlock system that will make you wait 30 seconds after 3 incorrect attempts. Well the code works, but now, I want it to loop after the 30 second delay and prompt the user for input again.
Here's the code:
'''
Purpose of code: To make a password protector that will lock for 30 seconds after 3
failed attempts.
Plan:
Use input to take user input(possible password.
If input was correct, give you access
If input was wrong, give 2 more chances.
After 3 incorrect attempts, lock "system" for 30 seconds (or just waiting as a
timer).
'''
import time
f_a = 3
while f_a > 0:
set_password = "passw0rd"
user_input = input("Please enter your password :\n")
if set_password == user_input:
print("You got access !")
break
else:
f_a = f_a - 1
print("Error, you have", f_a, "attempts left.")
if f_a == 0:
print("Time out for 15 seconds.")
print("15")
time.sleep(1)
print("14")
time.sleep(1)
print("13")
time.sleep(1)
print("12")
time.sleep(1)
print("11")
time.sleep(1)
print("10")
time.sleep(1)
print("09")
time.sleep(1)
print("08")
time.sleep(1)
print("07")
time.sleep(1)
print("06")
time.sleep(1)
print("05")
time.sleep(1)
print("04")
time.sleep(1)
print("03")
time.sleep(1)
print("02")
time.sleep(1)
print("01")
time.sleep(1)
print("00")
time.sleep(1)`
So now I wanted the code to repeat itself after "time.sleep(1)" .One way i tried was by f_a == 3 after the last line. But i got a warning "Statement seems to have no use.". I then tried "while f_a == 0: f_a == 3 ". Failed as well. Any suggestions?
Solution
You seem to misunderstand how a while
loop works. You don't have to check the condition separately in the loop body, that is implied in the expression between while
and the colon :
. As long as you make sure that this expression will change its value, e.g. by decreasing a counter, you're fine.
Adding a stand-alone f_a == 3
in the loop body will be evaluated to either True or False. But then, nothing will happen with that value if you don't assign it to a variable or check it in a if
or while
statement. That's why you get the warning Statement seems to have no use.
. It's equivalent of just having True
or False
on a separate line with nothing else.
Answered By - Jan Wilamowski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.