How to request input Iterations from users in python code - python

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.

Related

Select parts of my code have been greyed out

I wrote a while loop asking the user whether they're male or female. Everything after "else" has been greyed out. When I hover over it with my mouse it says:
"Code is unreachable Pylance".
sex = input('What is your sex? (m/f/prefer not to say) ')
while True:
sex = input('What is your sex? (m/f/prefer not to say' )
print('success:)')
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")
How can this be fixed?
Note the differences. the break exit the loop totally.
The while loop continues operation as long as it condition evaluates as True. so therefore you need to create condition to either break from the loop within your code or modify the loop to evaluate as false.
Also, you would realise that when the loop eventually turns false only then is the else statement called. However, the else wont be called if break keyword was used to exit the loop.
tries = 5
opt =('m','f','prefer not to say')
while tries: #evaluates True but false if tries = 0
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
tries -=1
continue
print('success:)')
tries=0 # note here the bool(0) == False
else:
print('happens if there is no break from the loop')
print("we're out of the loop")
#opt 2
while True:
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
continue
print('success:)')
break. # completely exits the loop
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")

How to stop code running when if statement is not fulfilled

I am doing a school project and what i want to add is a line of code that would stop the code from running if age < 15 or if age > 100
I tried break but it would continue to the next line.
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
if age < 15:
print("sorry you are too young to enter the store!")
break
if age > 100:
print("Please come back in the next life")
break
else:
break
print("")
print("Welcome to Jim's Computer Store", name)
print("") while True:
try:
cash = int(input("How much cash do you currently have? $"))
except ValueError:
print("Please enter a valid value! ")
continue
else:
break
I would advise you to proceed step by step. The code in the question is too long for the purpose. When the first step behaves like you want, you can do another step.
Is is this working like you want ?
name = "John"
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
break
# Here, we can assume that 'age' is an integer
if age < 15:
print("sorry you are too young to enter the store!")
exit()
if age > 100:
print("Please come back in the next life")
exit()
print("")
print("Welcome to Jim's Computer Store", name)
# When the code above will be validated, the next step will be easy
The while loop is to assure that age is an integer when he breaks the loop (if age is not an integer, the program will execute the continue instruction and go back to the start of the loop).
Just adding a exit() after the if condition will do the job.
An example would be:
x = 5
if x < 2:
print "It works"
else:
exit()
Or without the else statement:
x = 5
if x < 2:
print "It works"
exit()

How do I fully break out of a while loop nested inside a while loop? [duplicate]

This question already has answers here:
How can I break out of multiple loops?
(39 answers)
How can I fix the if statements in my while loops?
(1 answer)
Closed 5 years ago.
I am wondering if someone can help me figure out how to fully break out of my while loop(s) and continue with the rest of my program. Thanks!
import time
while True:
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
break
#Continue with rest of my program
The solution below adds a flag to control when to break out of the external loop that is set to break out each loop, and set back if no break has occurred in the internal loop, i.e. the else statement has been reached on the inner loop.
import time
no_break_flag = True
while no_break_flag:
no_break_flag = False
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
no_break_flag = True
#Continue with rest of my program
Obviously as you have a condition of while True on the inner loop you will always exit by breaking, but if you had some other condition this would break the external loop only if a break statement was reached on the inner loop.

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