Why is my program not looping back to the 3rd line whenever I have exhausted all my attempts?
counter = 1;
for i in range(1):
password = input('Enter your desired password: ');
print('Registration successful');
x = 5;
for i in range(5):
print(' Login ');
login = input('Enter password: ');
if login == password:
counter -= 1
print(' Welcome ');
print('Account Information: ');
print('Name: ',name);
print('Age: ',age)
break;
else:
x=x-1;
if x==0:
print('Account locked');
else:
print(' Wrong password');
print(x,' trial(s) left ');
CodePudding user response:
You can simplify and start to make the code reusable by putting it into a function. Also, it's a good idea to make it pythonic and remove all the ;
that will only serve to confuse the reader as to what language they're looking at.
def login(name, age):
password = input('Enter your desired password: ')
print('Registration successful')
tries = 5
for i in range(tries):
print(' Login ')
login = input('Enter password: ')
if login == password:
return True
else:
print(' Wrong password')
print(f'{tries-1-i} trial(s) left ')
return False
name = 'Bob'
age = 12
if login(name, age):
print(' Welcome ',
'Account Information: ',
f'Name: {name}',
f'Age: {age}',
sep='\n')
else:
print('Account locked')
Example Output:
# Success 1st try:
Enter your desired password: password
Registration successful
Login
Enter password: password
Welcome
Account Information:
Name: Bob
Age: 12
# Success 3rd try:
Enter your desired password: password
Registration successful
Login
Enter password: pass
Wrong password
4 trial(s) left
Login
Enter password: pass
Wrong password
3 trial(s) left
Login
Enter password: password
Welcome
Account Information:
Name: Bob
Age: 12
# Fail:
Enter your desired password: password
Registration successful
Login
Enter password: pass
Wrong password
4 trial(s) left
Login
Enter password: pass
Wrong password
3 trial(s) left
Login
Enter password: pass
Wrong password
2 trial(s) left
Login
Enter password: word
Wrong password
1 trial(s) left
Login
Enter password: pasword
Wrong password
0 trial(s) left
Account locked
CodePudding user response:
I got this working, hope it helps!
(It seems we have a downvote bot who downvoted so i added proof it works)
def login():
counter = 1;
x = 5;
for i in range(5):
print(' Login ');
login = input('Enter password: ');
if login == password:
counter -= 1
print(' Welcome ');
print('Account Information: ');
print('Name: ',name);
print('Age: ',age)
break;
else:
x=x-1;
if x==0:
print('Account locked');
start();
else:
print(' Wrong password');
print(x,' trial(s) left ');
def start():
for i in range(1):
global password
password = input('Enter your desired password: ');
print('Registration successful');
login();
start();