Python - Nested IF - python

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

Related

Stuck at WHILE LOOP when pressing N for escaping from the loop

# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)

How to request input Iterations from users in python code

Pardon my cheap question, I am still a beginner!
Task: In the block of code below, I want the user to be able to try 3 wrong names,
and the program should possible print ‘you have reached the maximum attempts’
before the ‘Break’ command will execute. How can I achive this?
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
name = input()
#[I need to add some iterations here!]
break
print('Thank you!')
Try this:
tries=1
while True:
name = input('Please type your name\n')
if name != 'Louis':
if tries!=3: #==== If tries is not equal to 3
print('Name is incorrect check and enter your name again!')
tries+=1 #=== Add 1 to tries
else:
print("You have reached maximum attempts.")
break #=== Break out of loop
else:
print('Thank you!')
break #=== Break out of loop
Here, this should help. You just iterate over the number of attempts you want to give the user (here it is 3 attempts). You could also use the while True loop with a counter.
nbr_of_tries = 3
for i in range(nbr_of_tries):
print('Please type your name')
name = input()
if name == 'Louis':
print('Thank you!')
#[I need to add some iterations here!]
break
elif i < nbr_of_tries-1:
print('Name is incorrect check and enter your name again!')
else:
print('Maximum number of tries reached. Exiting')
you can do something like this:
x=0
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
name = input()
#[I need to add some iterations here!]
if x==3:
print("you have reached the limit")
break
else:
x=x+1
else:
print('Thank you!')
break
count = 0
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
count += 1
#[I need to add some iterations here!]
if count > 2:
break
else:
print ("Required name entered")
break
print('Thank you!')
You can do this without break, something like this.
attempt = 0
while True and attempt < 3:
attempt += 1
print('Please type your name')
name = input()
if name != 'Louis':
if attempt == 3:
print('you have reached the maximum attempts')
else:
print('Name is incorrect. Please check and try again!')
print('Thank you!')
like this?
while True:
print('Please type your name')
name = input()
attempts = 3
while attemps:
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
attempts -= 1
name = input()
else:
print('maximum attempts reached')
print('Thank you!')
Explanation:
During the while loop the attempts-counter will be decremented if the if statement is True and the user can enter another name. If the counter reaches 0, the loop will stop and the maximum attempts reached message will be printed.

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 = ''

The variable does not update for some reason?

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

How to I make a code Loop 3 times in Python as well as having a while loop around it

Very limited on using python and totally stuck, I've managed to get a while loop running on the code below so that the user can keep entering a code until they put in the correct one.
What I'm now looking to do is add a for loop so that it only asks the user to enter the code (4 wrong digits) 3 times and then locks them out. At the same time it needs a while loop to ensure if the user puts more than or less than 4 digits it continually runs and doesn't lock them out.
I just cant get the for loop and while loop working at the same time and don't know what I'm doing wrong.
user = ("1234")
valid = False
while not valid:
#for i in range (3):
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
if user != ("1234") :
print ("that is incorrect, please try again")
valid = False
elif len(user) > 4:
print ("That is incorrect, please try again")
valid = False
elif len(user) < 4:
print ("That is incorrect, please try again")
valid = False
else:
print ("You have been locked out!! Alarm!!!!!!")
user = ("1234")
counter = 0
while counter < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if len(user) != 4:
print("I said 4 digits!")
continue
if user == ("1234") :
print("You have cracked the code, well done")
break
print ("that is incorrect, please try again")
counter += 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
else:
print ("Everything is fine.")
I adapted your code a little bit and added a counter variable
user = ("1234")
valid = False
counter = 0
while not valid:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
elif len(user) != 4:
print ("That is incorrect, please try again")
else:
print ("that is incorrect, please try again")
counter = counter + 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
#Do stuff to actually abort here...
It counts up if there is a wrong answer now
the inner loop is just for valid input:
user = '1234'
locked = False
miss_cnt = 0
while True:
while True:
ans = raw_input('User -> ')
if len(ans) == 4 and ans.isdigit():
break
if ans != user:
miss_cnt += 1
if miss_cnt >= 3:
locked = True
break
else:
break
I left out the prints for clarity of flow
The following code should work for you.
answer = "1234"
valid = False
count = 0
while not valid and count < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == answer:
print("You have cracked the code, well done")
valid = True
elif count < 2:
print ("that is incorrect, please try again")
else:
print ("You have been locked out")
count += 1
I took the () off of the strings because that would make them sets so the if statement would never be true, because sets don't equal string inputs.

Categories