I am trying to write a program which will ask my name and password before giving me access. Somehow I am not writing it right
print("Enter your name:")
myName = input ()
if myName == "Akib":
print("Enter your password")
password = input()
password = "toma"
if password == "toma":
print("Access granted")
else:
print("Not granted")
The issue is you set password to the input and then rest password by setting it to toma so you need to remove password = "toma".
print("Enter your name:")
myName = input ()
if myName == "Akib":
print("Enter your password")
password = input()
if password == "toma":
print("Access granted")
else:
print("Not granted")
password = "password" # store your password here
name = "name" # store your name here
input_name = str(input("> enter your name: "))
input_password = str(input("> enter your password: "))
if input_name == name and input_password == password:
print("access granted !")
else:
print("declined !")
It can be done like-so. Hope this helps :)
You could achieve your desired function like so!
In this case, if the name entered is not 'Akib', it would not even prompt the user to enter the password.
# prompt for name
myName = input("Enter your name: ")
# check if name is correct
if myName == "Akib":
# prompt for password
password = input("Enter your password: ")
# check if password is correct
if password == "toma":
print("Access granted")
else:
print("Not granted")
else:
print("Not granted")
Related
while True:
print("please enter username")
input()
username = input()
if username == "Elias":
break
print("username correct")
break;
while True:
print("please enter password")
input()
password = input()
if password == "1234567890":
break
print("access granted");
print("rechner:")
variable_a = input("alle noten mit + zeichen eintippen")
print("Dein Durchschnitt ist", input()/2);
File "C:\Users\Odyesp\PycharmProjects\pythonlearning.py\main.py", line 3
print("please enter username")
^
IndentationError: expected an indented block after 'while' statement on line 1
I feel that you may be very new to Python, and that's perfectly ok! We were all really new at some point.
For your use case, I think it's important to step back and analyze what you're wanting to do.
Capture a username
Continue trying to capture a username until it is "Elias"
Capture a password
Continue trying to capture a password until it is "1234567890"
At the end, print "access granted" and "rechner:"
Here's some code:
# Capture username, and only proceed if "Elias"
username = ""
while username != "Elias":
username = input("Please enter your username: ")
print("username correct")
# Capture password, and only proceed if "1234567890"
password = ""
while password != "1234567890":
password = input("Please enter your password: ")
print("access granted")
print("rechner:")
Here's an example of the output from the terminal, along with my inputs
name = input(str("Enter your firstname "))
surname = input(str("Enter your surname "))
username = surname[0:2] + name[0:3]
password = input("Make a password ")
passwordconfirm = input("Enter password again ")
while password != passwordconfirm:
print("Password is not the same try again ")
password = input("Make a password ")
passwordconfirm = input("Enter password again ")
print("This is your username and password:\n" + username + "\n" + password)
attempt = 0
login1 = input("Enter your username ")
login2 = input("Enter your password ")
while True:
if login1 == username and login2 == password:
print("Welcome back " + name + " " + surname)
break
else:
print("Access denied")
attempt += 1
#When I run the program and username or password is incorrect it starts to infinitely print "Access Denied"
breakĀ breaks out of a loop, not anĀ ifstatement or function as others have mentioned above. Your program will stop running itself if conditions are matched.
if login1 == username and login2 == password:
print("Welcome back " + name + " " + surname)
else:
print("Access Denied.")
Alright, I think the code needs a few more steps to make it work. If I understand it well, you want the user to sign up for a new account using username and password. Then, you need to verify it to see if it's correct.
Here is a sample:
#*********** BEGIN ACCOUNT CREATION ***************
msg = "Invalid entry. Try again."
print("Welcome to Python Account!")
while True:
# ***** THIS BLOCK CREATES NEW USERNAME
try:
username = input("Create New Username: ") #create new username
except ValueError:
msg
else:
try:
username2 = input("Confirm username: ") # confirm username
except ValueError:
msg
else:
if username2 != username: # if no match, try again
print("Usernames do not match. Try again.")
continue
else:
print("Username created!")
#THIS BLOCK CREATES NEW PASSWORD
while True:
try:
password = input("Create a new password: ")
except ValueError:
msg
else:
password2 = input("Confirm password: ")
if password2 != password:
print("Passwords don't match. Try again.")
continue
else:
print("Password created!")
break
break
break
# ****************** END ACCOUNT CREATION ******************
# # ****************** BEGIN ACCOUNT LOGIN *****************
print("PLEASE LOG INTO YOUR ACCOUNT")
attempts = 5 # this will allow 5 attempts
while attempts > 0:
attempts -= 1
try:
usrnm = input("Enter username: ")
pwd = input("Enter password: ")
except ValueError:
msg
else:
if usrnm.isspace() or pwd.isspace():
print("Space not allowed.")
continue
elif usrnm == '' or pwd == '':
print("Value needed.")
continue
elif usrnm != username2 or pwd != password2:
print("Credentials do not match. Try again.")
print(f'You have {attempts} attempts left')
if attempts == 0: # once user exhausts attempts, account is locked
print("You have been locked out of your account")
break
continue
else:
print(f"Welcome {username2}!")
break
break
# *************** END ACCOUNT CREATION *************
WITHOUT TRY/EXCEPT
#*********** BEGIN ACCOUNT CREATION ***************
msg = "Invalid entry. Try again."
print("Welcome to Python Account!")
while True:
# ***** THIS BLOCK CREATES NEW USERNAME
username = input("Create New Username: ") #create new username
username2 = input("Confirm username: ") # confirm username
if username2 != username: # if no match, try again
print("Usernames do not match. Try again.")
continue
else:
print("Username created!")
#THIS BLOCK CREATES NEW PASSWORD
while True:
password = input("Create a new password: ")
password2 = input("Confirm password: ")
if password2 != password:
print("Passwords don't match. Try again.")
continue
else:
print("Password created!")
break
break
# ****************** END ACCOUNT CREATION ******************
# # ****************** BEGIN ACCOUNT LOGIN *****************
print("PLEASE LOG INTO YOUR ACCOUNT")
attempts = 5 # this will allow 5 attempts
while attempts > 0:
attempts -= 1
usrnm = input("Enter username: ")
pwd = input("Enter password: ")
if usrnm.isspace() or pwd.isspace():
print("Space not allowed.")
continue
elif usrnm == '' or pwd == '':
print("Value needed.")
continue
elif usrnm != username2 or pwd != password2:
print("Credentials do not match. Try again.")
print(f'You have {attempts} attempts left')
if attempts == 0: # once user exhausts attempts, account is locked
print("You have been locked out of your account")
break
continue
else:
print(f"Welcome {username2}!")
break
# *************** END ACCOUNT CREATION *************
It's for my school work. I need to fix this code. Can someone maybe help me? I would really appreciate that. I can't manage to fix the "else" part. :)
CorrectUsername = "Username"
CorrectPassword = "Password"
loop = 'true'
while (loop == 'true'):
username = raw_input("Please enter your username: ")
if (username == CorrectUsername):
password = raw_input("Please enter your password: ")
if (password == CorrectPassword):
print "Logged in successfully as " + username
loop = 'false'
else:
print "Password incorrect!"
else:
print "Username incorrect!"
This is what I've done so far
CorrectUsername = "Username"
CorrectPassword = "Password"
loop = "true"
while (loop == 'true'):
username = input("Please enter your username: ")
if (username == CorrectUsername):
password = input("Please enter your password: ")
if (password == CorrectPassword):
print("Logged successfully as " + str(username))
loop = "false"
else:
print("Password incorrect!")
else:
print("Username incorrect")
You have to indent the else properly it's matching if. Also use boolean values True/False, better than strings
CorrectUsername = "Username"
CorrectPassword = "Password"
loop = True
while loop:
username = input("Please enter your username: ")
if username == CorrectUsername:
password = input("Please enter your password: ")
if password == CorrectPassword:
print("Logged successfully as " + str(username))
loop = False
else:
print("Password incorrect!")
else:
print("Username incorrect")
I really want to learn how do I repeat my code when its statement is false in Python. I just wanna know, how do I make Python ask for username and password again if its wrong? Here is my code:
print("Enter username")
username = input()
print("Enter password")
pword = input()
if username=="Shadow" and pword=="ItzShadow":
print("Access granted to Shadow!")
else:
print("Wrong username and / or password")
I meant, how can I make Python ask for Username and Password again if one of it is false?
You need to enclose your code in a loop. Something like this:
def get_user_pass():
print("Enter username")
username = input()
print("Enter password")
pword = input()
return username, pword
username, pword = get_user_pass()
while not(username=="Shadow" and pword=="ItzShadow"):
print("Wrong username and / or password")
username, pword = get_user_pass()
print("Access granted to Shadow!")
Use a while loop:
while True:
print("Enter username")
username = input()
print("Enter password")
pword = input()
if username=="Shadow" and pword=="ItzShadow":
print("Access granted to Shadow!")
break # Exit the loop
else:
print("Wrong username and / or password") # Will repeat
stuff() # Only executed when authenticated
We are using the data entering function get_input in the loop each time the user and password aren't same.
def get_input():
# enter your declarations here
return [user_name,password]
user,pwd=get_input()
while (user!='your desired user' and pwd!='the password'):
print('Not authorized')
user,pwd=get_input()
print('Your success message')
user1 = "aqa code"
pass1 = "uzair123"
username = input("Enter username: ")
password = input("Enter password: ")
while username != user1:
print("Access denied: username is incorrect try again ")
username = input("Enter username again: ")
if username == user1:
print("access granted")
while password != pass1:
print("Password is still incorrect")
password=input("Enter password again: ")
if password == pass1:
print("Access granted")
while password != pass1:
print("Access denied,Password is incorrect")
password=input("Enter password again: ")
if password == pass1:
print("Access granted")
How do I add a .lower() to the username/user1 so it becomes case insensitive when you type in the answer? Please help.
You can call .lower on the return of the input function.
username = input("Enter username: ").lower()
password = input("Enter password: ").lower()
Adding .lower() is indeed the solution you're looking for, but you may want to try to simplify your flow a bit, so you have fewer places to edit whenever you want to modify your input statement. To do this I would suggest creating a variable for each loop that is initially false and only get user input once inside each loop:
loop_condition = False #initialize loop condition
while not loop_condition: #loop until we say so
value = input("please enter a value: ") #human input
value = value.lower() #convert to lower case for comparison
if value == "password": #test
print("success")
loop_condition = True #loop will terminate when we hit our `while` again
else:
print("fail")
print("rest of program goes here")
Here you can see we only call input() once, and only have to convert it to lowercase in one place as well. Simplicity is always your friend.
note: use raw_input() if you're using python 2.7