I have successfully made a python password system but the password can only be out of numbers, not letters. Here is the coding behind it:
password = str(input("Please enter password to continue: "))
if password == 'dog':
print ("Welcome")
else:
print ("WRONG PASSWORD")
This doesn't work while having the password be an integer does work.
Edit: Sorry about putting the wrong code, new to this site.
I have now added quotes to 'dog' but it now gives this error in terminal
Please enter password to continue: dog
Traceback (most recent call last):
File "pass.py", line 1, in <module>
password = str(input("Please enter password to continue: "))
File "<string>", line 1, in <module>
NameError: name 'dog' is not defined
Final edit: Fixed it by changing str(input to str(raw_input. It was because I was using terminal which uses python 2. Does anyone know how to make terminal do python 3 instead of 2?
You are trying to pass a string type to an integer, which will not work. You can compare a string to an int!
Strings in python need speech marks ("STRING") around them. If there are no speech marks, python will assume it is an integer or float.
Your correct code should be:
password = str(input("Please enter password to continue: "))
if password == "dog":
print ("Welcome")
else:
print ("WRONG PASSWORD")
EDIT:
It also appears that you are using Python 2 (because you are using terminal). The input function in Python 2 tries to get input as a python expression, not as a string. Try using raw_input instead, if you are using Python 2. This will get the input as a string.
The string speech marks still applies. Your code would look like:
password = str(raw_input("Please enter password to continue: "))
if password == "dog":
print ("Welcome")
else:
print ("WRONG PASSWORD")
"Types" are the key here.
You're casting the input you get from the user (which is a String) to int - Integer:
3 == '3'
That's False! a String can never be equal to an Integer.
I would advise not casting it to int, keep it a str and it should work just fine.
To make it non-recurring:
password="dog"
password1=input("Enter password?")
if password==password1:
print("Welcome")
else:
print("Incorrect password")
However to make it rcurring you just do this:
condition = True
password="dog"
while condition:
password1=input("Enter password?")
if password==password1:
print("Welcome")
else:
print("Incorrect password")
If you're using python 2, try using:
inp = str(raw_input('Please enter password to continue: '))
print("Welcome") if password == "password_here" else print ("WRONG PASSWORD")
Related
In the beginning stages of learning Python and I've hit a bit of a snag
I'm trying to create a program that asks for a specific username and password. After 6 incorrect attempts, it will quit the program. Sample code works fine when I put in the correct info. The issue I'm having is when the username is correct but the password is not. I want it to print that the "password doesn't match" and re-ask for the password. It takes me back to the beginning of the program and asks for my username again. Any ideas to solve this? Thank you in advance!
Code can also be found here: https://pastebin.com/4wSgB0we
import sys
incorrect = 0
max_tries = 6
choices = ['Drake', 'swordfish']
run = True
while run:
while incorrect < max_tries:
user_input = input('Please enter username: ')
if user_input not in choices:
incorrect += 1
print(f"{user_input} is incorrect. Please try again.")
else:
print(f"Welcome back {user_input}.")
pass_input = input('Please enter password: ')
if pass_input not in choices:
incorrect += 1
print("Password does not match. Please try again")
else:
run = False
print('Access granted')
sys.exit()
if incorrect == max_tries:
sys.exit()
If it didn't help you solve the problem.
I will modify.
When your user is correct, you should leave While.
If you do not leave While, the user account will be asked again.
while run:
while incorrect < max_tries:
user_input = input('Please enter username: ')
if user_input not in choices:
incorrect += 1
print(f"{user_input} is incorrect. Please try again.")
else:
print(f"Welcome back {user_input}.")
break
while incorrect < max_tries:
pass_input = input('Please enter password: ')
if pass_input not in choices:
incorrect += 1
print("Password does not match. Please try again")
else:
run = False
print('Access granted')
sys.exit()
if incorrect == max_tries:
sys.exit()
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm very new at Python, and I'm trying to make a simple program that asks the user for a password, and if the user didn't guess the password they were asked, ask again until they guess it. How do I do that?
Password = input("guess the password: ")
while (password) != "12345":
Print(input("try again : "))
Welcome to Programming and StackOverflow. Have a look a this Example,
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
The break statement ends the while loop.
#g23's Answer is more apt in the context of the question
Make sure your capitalization is right, generally variables are lowercase, but you need to be consistent.
Also when you ask for the password again, you need to store what the user gives you so it can be checked in the loop condition (the while password != "12345": part)
Something like
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
This code does what you want. It has a while loop to check if the password was guessed until the right password is entered. Then it has an if statement to write a message: if the right password is entered, it writes it.
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
if password == "12345":
print("Correct password!")
I have a very simple try/except block to basically force the variable 'password' to be defined as an integer from user input.
It is likely a dumb question, but I have tried looking around and cannot find some solution.
try:
password = int(input('Password: '))
except ValueError:
print("Please do not type letters or symbols!!")
while type(password) != 'int':
try:
password = int(input('Password '))
except ValueError:
print("Please do not type letters or symbols!!")
print('Complete, we have your password.')
But, when I try run this python shell, it comes up with a Syntax Error, highlighting 'except'...
There were couple of problems:
You have to use the comparision like this type(password) is not int:
Define password variable beforehand, otherwise it would not be recognized in your while statement
password=""
try:
password = int(input('Bob should have issued you with your 4-digit numerical password, please enter it here: '))
except ValueError:
print("Please do not type letters or symbols!!")
while type(password) is not int:
try:
password = int(input('Bob should have issued you with your 4-digit numerical password, please enter it here: '))
except ValueError:
print("Please do not type letters or symbols!!")
print('Complete, we have your password.')
Remove the new line after password = .... Shell expects an except block not a new line. Also your parenthesis are not complete.
try:
password = int(input('Bob should have issued you with your 4-digit numerical password, please enter it here: '))
except ValueError:
print("Please do not type letters or symbols!!")
If I'm trying to prompt a user for their street name and they enter a # symbol i want to return an error and loop back to the top until they have entered a valid name.
Code:
def streetname():
while True:
try:
nameinput = str(input("Please enter a street name: "))
except Exception: # want to print error == if nameinput.find('#') > -1:
print("Error: name contains #, please try again")
continue
break
return nameinput
Goal of code: I want to prompt user for street name until they enter a valid name. If it contains '#', print error and try again. if it's valid, return nameinput.
I'm not quite sure how to use try and except with if statements
You probably shouldn't use try...except for such a simple input check, that can easily done with if alone.
def streetname():
while True:
nameinput = input("Please enter a street name: ")
if "#" in nameinput:
print("Error: name contains #, please try again")
continue
return nameinput
If you find a '#' in the string simply restart the loop, otherwise just return the name out of the function.
Also input already returns a str in Python 3, so there's no need to convert it. In Python 2 you should use raw_input instead which will also return a str.
First off, you're using a python's general Exception class. A string with a pound sign in it wouldn't trigger any of python's native exceptions, you have to write your own exception class and then call it.. or you can do something like this
if '#' in nameinput: #pound sign was found in the string
#either raise an Exception
raise('Can not use pound sign') # though this will probably break the while loop
# or
print 'can not use pound sign'
continue # to go back to the top of the while loop and prompt the user again
I came across a problem within my program that I'm writing. I've narrowed down the problem to these two functions. The problem occurs when you call the function enterPasswords, enter invalid data such as 'a', then break out of the passwordLength function by entering valid data such as 'hello'. I've left some print statements there to help you see the problem. I've tried adding returns, but the same problem still occurs.
Any advice will be greatly appreciated. If you could tell me why the problem is occurring, I'm sure I could fix it myself. Thanks.
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
enterPasswords()
def enterPasswords():
password = input("Input password: ")
passwordLength(password)
print(password)
password2 = input("Re-enter password: ")
print(password, password2)
enterPasswords()
Here is an image of my problem (What I'm wanting to know is, why isn't the program ending where I've highlighted, why does it carry on, and why is 'a' being printed towards the end?):
http://i.imgur.com/LEXQFTO.png
It appears that if the user inputs an invalid password at first, it repeats enterPasswords - however, if the user completes this successfully, it goes back to the initial enterPasswords. Instead, try
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
return False
return True
def enterPasswords():
password = input("Input password: ")
while not passwordLength(password):
password = input("Input password: ")
print(password)
password2 = input("Re-enter password: ")
print(password, password2)
This will continue to ask the user to reinput the first password until it is valid, and only then it will ask the user to confirm.
The password variable in passwordLength() is completely unrelated to the variable in enterPasswords(). The behaviour might also not be as you expect it to be. Try something like this:
def passwordLength(pw):
return 4 <= len(pw) <=15
def getPw():
return input("Enter password: ")
def enterPasswords():
pw = getPw()
while not passwordLength(pw):
print("Incorrect password length.")
pw = getPw()
# ...
Your functions are calling each other in a bad way. If you try to follow line by line your algorithme (using the case you mentioned with 'a' and 'hello') you will probably see the problem.
Here is a solution :
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
return False
else : return True
def enterPasswords():
passwordOK = False
while not passwordOK :
password = input("Input password: ")
passwordOK = passwordLength(password)
print(password)
password2 = input("Re-enter password: ")
print(password, password2)
enterPasswords()