The variable does not update for some reason? - python

pss = input("Enter a password")
symb = ["!","£","$","%","^","&"]
num = ["1","2","3","4","5","6","7","8","9","0"]
done = 0#to break symbol check
done2 = 0#break num check
check = 0#keep track of things correct
found = False
while found == False:
#checks for a symbol in the password
for ch in pss:
done = done + 1
if ch in symb:
check = check + 1
break
elif done == len(pss):#done , only to say once
print("Add a symbol to your password")
#WORKS!! :D
#checks for number in password
for ch in pss:
done2 = done2 + 1
if ch in num:
check = check + 1
break
elif done2==len(pss):
print("Add a number to your password")
#capital letter check
if pss == pss.lower():
print("You need to have at least one capital letter")
else:
check = check + 1
#checking
if check == 3:
print("Password Validated")
found = True
else:
pss = input("Correct you password")#re enters password
check = 0
#need to make pss update correctly
Its the final few lines that I am having trouble with, the program works, its just that the password doesn't get updated, so unnecessary lines are printed. For example, when entering the initial password "Jellybean" i get reminded to add a number and a symbol to the password. Next, when i get the oppouruntiy to correct, I enter "Jellybean5£" and I still get prompted to add a number and a symbol. However the program recognizes the change and exits, due to the password being successful .

Update the done and done2 variables back to 0 when you're trying to validate
#checking
if check == 3:
print("Password Validated")
found = True
else:
pss = input("Correct you password")#re enters password
check = 0
done = 0
done2 = 0

Related

Username and Password Variable Incorrect

Helo guys
i'm trying to create a login system, it's run normally when i input username and password directlt after i signed up on my own code, but when i try to login using false username or password bruteforcely variable "p" or "u" is changed by itself. I dunno why it's happened here's my code
sorry for my bad english and my bad code(it's weird"), i'm new in programming language and python "i've tried my best" so if anyone wants to fix my code or something else please help me, 1 more question is there any code to loop when the input is false? i used a function that call the lastest function if the input is false
import os
import sys
import re
def apus():
sys.stdout.write(CURSOR_UP_ONE)
sys.stdout.write(ERASE_LINE)
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
def main():
os.system("cls")
print(""""
Welcome To X Bank
Enter Any Key To Continue
""")
x = input()
menu()
def menu():
os.system('cls')
print("------------------------------------------------------------------------")
print('''
Don't Have An Account Yet? Please Sign Up
1. Login
2. Sign Up
''')
print("------------------------------------------------------------------------")
opsimenu()
def opsimenu():
#os.system("cls")
a = int(input())
os.system("cls")
if a == 1:
login()
elif a == 2:
signu()
else:
menu()
def ulog():
login()
def login():
os.system('cls')
print("Enter Your Username And Password \n \n")
C = input("Username = ")
D = input("Password = ")
while True:
if C == u and D == p:
login2()
break
else:
print("Your Username Or Password Is Incorrect")
ulog()
def login2():
os.system("cls")
print("Login Succesful")
def signu():
global Address
global Name
#print("\n ")
print("""
Your Username And Password *
*Must be at least 8 characters.
*must be between [a-z]
*Must be at least one alphabet should be of Upper Case [A-Z]
*Must be at least 1 number or digit between [0-9].
*Must be at least 1 character from [!##$%^&*].
""")
Name = str(input("Full Name:"))
Address = str(input("Address: "))
enteruser()
def signup():
enteruser()
def enteruser():
global u
Username = (input("Username:"))
flag = 0
while True:
if (len(Username) < 8):
flag = -1
break
elif not re.search("[a-z]", Username):
flag = -1
break
elif not re.search("[A-Z]", Username):
flag = -1
break
elif not re.search("[0-9]", Username):
flag = -1
break
elif not re.search("[!##$%^&*]", Username):
flag = -1
break
elif re.search("\s", Username):
flag = -1
break
else:
flag = 0
break
if flag == -1:
apus()
#print("Invalid Username")
signup()
u = Username
pw()
def ulangpw():
pw()
def pw():
global p
Password = str(input("Password:"))
while True:
if (len(Password) < 8):
flag = -1
break
elif not re.search("[a-z]", Password):
flag = -1
break
elif not re.search("[A-Z]", Password):
flag = -1
break
elif not re.search("[0-9]", Password):
flag = -1
break
elif not re.search("[!##$%^&*]", Password):
flag = -1
break
elif re.search("\s", Password):
flag = -1
break
else:
flag = 0
break
if flag == -1:
print("Invalid Password")
apus()
apus()
ulangpw()
p = Password
os.system("cls")
validating()
def validating():
print(" ---------------------------------------------------")
print(" You have successfully created your account.\n Press Any Key To Login. \n \n Validating Your Data")
print("\n • Full Name ="+ Name)
print(" • Address ="+ Address)
print(" • Username ="+ u)
print(" • Password ="+ p)
print(" ---------------------------------------------------")
#p = Password
confirm = str(input("\n Make sure all registration data that is filled in is correct> Y/N "))
while True:
if confirm == "Y" or confirm =="y":
login()
break
elif confirm == "N" or confirm == 'n':
os.system("cls")
signu()
break
else:
confirm = str(input("\n Make sure all registration data that is filled in is correct> Y/N ="))
break
>main()
python wont print this:
print("""
Your Username And Password *
*Must be at least 8 characters.
*must be between [a-z]
*Must be at least one alphabet should be of Upper Case [A-Z]
*Must be at least 1 number or digit between [0-9].
*Must be at least 1 character from [!##$%^&*].
""")
Because it is syntax for uncommenting text
""" multiline comment line 1
multiline comment line 2 """
You have to use quotes like
print("Hi Dad")

How can i check if an inputted variable either starts with "Q" or it is a number

I am new so plz help. i am writting a program that adds numbers. it asks for input and until "Q" is inputed it keeps asking for input
def add_num(vari = "" , total = 0):
vari = input("Enter a num or press \"Q\" to stop: ")
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
print("Error")
vari = input("plz enter again: ")
else:
print("Nice")
there are no indentation error. The problem i have is how can i check if it starts with "Q" or it is a number. I think this is the code that has errors
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
vari.isdigit() is enough to check that all characters are digits.
You have a logic error in the while condition: it cannot be that vari.startswith("Q") and at the same time vari.isdigit(), so that would be always false, and comparing that to False would always be true.
Change it to while (vari.startswith("Q") or vari.isdigit()) == False:

python wait nth digit before continue

from pad4pi import rpi_gpio
# Setup Keypad
KEYPAD = [
["1","2","3","A"],
["4","5","6","B"],
["7","8","9","C"],
["*","0","#","D"]
]
ROW_PINS = [5,6,13,19] # BCM numbering
COL_PINS = [26,16,20,21] # BCM numbering
factory = rpi_gpio.KeypadFactory()
keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS)
def processKey(key):
print("enter 3 digit")
print(key)
if key == 123:
print("correct")
else:
print("wrong password")
keypad.registerKeyPressHandler(processKey)
I want the code to wait for the user enter for example 3 digits before comparing with the password in the code which is 123 in above code.
What it should do:
Wait user enter 3 digit from the keypad , for example 123 , then print correct.
What it actually do:
it will print correct or incorrect password straight away after user enter 1 digit code
Update for raspberry taking #furas example:
# Initial keypad setup
code = ''
def processKey(key):
print("Enter your 3 digit PWD: \n")
global code
MAX_ALLOWED_CHAR = 3
code += key
if (len(code) == MAX_ALLOWED_CHAR):
if (code == "123"):
print("You entered the correct code.")
dostuff()
else:
code = ''
print("The passcode you entered is wrong, retry.")
def dostuff():
# do your things here since passcode is correct.
This might do it for your case.
def processKey():
key = input("enter 3 digit")
if (key == "123"):
print("Correct password.")
return True
else:
print("You typed {0} wich is incorrect.".format(key))
return False
So now you don't give processKey a value because as you said the user input it, calling processKey() will ask the user to enter a password and return true/false based on the "123" in the check.
This is if you want to input the password, but if the following answer is not suiting your needs (didn't quite fully understand what you want to accomplish) just provide more clever example.
Edit:
Since you wanted to strictly have a 3 digit input and a re-input password in case they enter the wrong one you can do the following:
On the call to processKey() you can:
while (processKey() == False):
processKey()
Revisioned code to match your needs:
def processKey():
MAX_ALLOWED_CHAR = 3
key = input("Enter 3 digit PWD: \n")
if (key == 123):
print("Correct password.")
return True
elif (len(str(key)) > MAX_ALLOWED_CHAR):
print("The max allowed character is {0}, instead you entered {1}.".format(MAX_ALLOWED_CHAR,key))
return False
else:
print("You typed {0} wich is incorrect.".format(key))
return False
while (processKey() == False):
processKey()
Output:
Enter 3 digit PWD:
3333
The max allowed character is 3, instead you entered 3333.
Enter 3 digit PWD:
321
You typed 321 wich is incorrect.
Enter 3 digit PWD:
123
Correct password.
keypress is executed after every key press - and it is natural. You have to keep all keys on list or in string and check its length.
code = ''
def processKey(key):
global code
code += key
if len(code) == 3:
if code == "123":
print("correct")
else:
print("wrong password, try again")
code = ''

Python - Nested IF

Like many here, I'm new to Python. I'm working on a snippet that asks the user to give their ID, then checks to see if the ID is exactly 6 digits in length. Then the code will ask the user to confirm their ID and if they mistyped, allows them to reset it. If the user confirms their entry was correct, then it asks for a location ID and follows the same path. If both IDs are confirmed, the user then can move on to the rest of the project.
This is something that will have to be input at the start of every use.
The issue I'm running in three sided.
1.) I can enter the empID 101290 and sometimes it tells me it's a valid entry while others it wont (but 101256 works regardless - both are 6 digits)
2.) Entering "1," to confirm the ID, the code moves to block 2 and asks for location ID but if the user enters "2" to say the Employee ID is wrong, it moves on anyway.
Any advice on what's in need of change here?
import time
print('What is your employee ID?') #user assigned ID
empID = input()
while empID != 0:
print('Try again.')
empID = input()
# employee ID is only 6 digits in length, no letters
if len(empID) != 6:
print('Try again.')
elif len(empID) == 6:
print('Thank you. Your ID is set to ' + empID + '.')
time.sleep(.5)
print('Is this correct?'''
'[1] Yes [2] No ')
yesNo = input()
while True:
yesNo == '1'
print('Thank you. ID set.')
break
# reset ID
else:
print('ID has been reset. Please enter your employee ID.')
empID = input()
break
break
#Store Location ID
print('What is your Location ID?')
locID = input()
while locID != 0:
print('Try again.')
locID = input()
# store locations are 3-5 digits
# TODO: prepend any input with less than len 5 with 0
if len(locID) != 5:
print('Try again.')
elif len(locID) == 5:
print('Thank you. Your location is set to ' + locID + '.')
time.sleep(.5)
print('Is this correct?'''
'[1] Yes [2] No ')
yesNo = input()
while True:
yesNo == '1'
print('Thank you. Location ' + locID + 'set.')
break
else:
print('Location ID has been reset. Please enter your location code.')
empID = input()
break
break
break
#next
I see some Bugs in your code to start with.
while True:
yesNo == '1'
yesNo == '1' is a condition statement which returns true or false depending on the user input, but it is not used in as a condition anywhere
if len(empID) != 6:
print('Try again.')
elif len(empID) == 6:
`elif len(empID) == 6:` is redundant.. a simple else will do
What I would do is:
Define functions to validate the user credentials:
def isEmpID(id):
'''
Employee ID is 6 characters in Length
'''
if len(id) != 6:
return False
return True
def isStoreID(id):
'''
Store ID is 3-6 characters in Length
Note: The function when called with id, checks if the length is between (exclusive) 3 and (inclusive) 6 and returns true if condition is satisfied else false which is the default return policy
'''
if 3 < len(id) <= 6:
return True
return False
validEmpID = False
validStoreID = False
while not (validEmpID and validStoreID): # Both has to be True to exit the loop, Otherwise the condition continues to go to True.
if not validEmpID:
print('Enter Employee ID:')
empID = input()
validEmpID = isEmpID(empID)
if not validEmpID:
print('Invalid Employee ID\nTry Again...\n')
continue
print('Enter Store ID:')
strID = input()
validStoreID = isStoreID(strID)
if not validStoreID:
print("Invalid Store ID\nTry Again!...\n")
continue
Here the loop exists or in other words continue executing the code afterwards only if both the variables are True

How do I display my user's errors?

My user wants to make a password and I'm supposed to be checking if it's valid or not. So far, I have down the code to check if it is valid/not valid. Now, the next step (after determining it is not valid) is to tell the user it is not valid AND why their password is not a valid option.
while True:
pw = input('Enter password to be tested if valid or not: ')
correct_length = False
uc_letter = False
lc_letter = False
no_blanks = True
first_letter = False
if len(pw) >= 8:
correct_length = True
for ch in pw:
if ch.isupper():
uc_letter = True
if ch.islower():
lc_letter = True
if pw.isalnum():
digit = True
if pw[:1].isalpha():
first_letter = True
if not pw.find(' '):
no_blanks = True
if correct_length and uc_letter and lc_letter and digit and first_letter and no_blanks:
valid_pw = True
print('Your password to be tested is valid.')
else:
valid_pw = False
print('Your password to be tested is not valid because:')
print(----------)
#This is the part where I'm suppose to display the errors if the user gets it wrong.
#Initially, in the test for ch. above, I put in an else: with a print statement but because of the for- statement, it prints it out for every single character.
answer = input('Try another password input? y/n ')
if answer == 'y':
answer = True
else:
break
Hm.. I think you can simply put the extra else statement, then raise an error:
if not pw.find(' '):
no_blanks = True
else:
raise ValueError('Invalid input!')
And similarly with your other conditionals.
If you want your loop to keep going, you can just print the message, and then continue:
else:
print("Invalid input! Please re enter it:")
continue
Hope this helps!
You check for all valid conditions. The correct approach is, instead of checking for the condition to be true like this,
if len(pw) >= 8:
correct_length = True
check for
if len(pw) < 8:
correct_length = False
print "Password not lengthy"
This will help identify the error. basically, find what all evaluate to false, so that the user could be pointed out those errors.

Categories