So I have an If-elif statement that I want to print some text and loop if the else condition is met. Here is the code:
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for specific user data\n3. kwin - Search a keyword in a specific user\n4. allin - Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
When people mess up and don't put one of the options properly, I want to loop back to the if statement so that when they put in the right one, the loop will end and the rest of the code will continue.
I tried a for loop and wrapped it all as a function but it would end up in an infinite loop of printing the error message. Is there a way to do it with a while loop? Do I need to block it ad a function to repeat it?
Thanks in advance!
In Python, the most idiomatic thing I see for this is while True:
while True:
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
continue
break
You can use a while loop and break statement. You can also reduce the elif statement as I see duplicate code.
Also, you can reduce the user error by converting the search_mode to lowercase.
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for
specific user data\n3. kwin - Search a keyword in a specific user\n4. allin -
Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
while True:
if "s" in search_mode.lower():
kwsearch = input("What Keyword do you want to use?: ")
break
elif search_mode.lower() in ('u','kwin','allin'):
username = input("What is the username?: ")
if "kwin" in search_mode.lower():
kwinword = input("What is the keyword?: ")
break
else:
print("Error. Please check spelling and capitalization")
search_mode = input("How would you like to search?: ")
The code enters the while loop after accepting value into variable search_mode.
If the value is 's', it asks for the keyword and breaks the loop.
if the value is not 's', then it checks if the value is 'u' or 'kwin' or 'allin'. If it is any of these, then it asks for the username. If the value is kwin, it also asks for keyword. Then it breaks the loop.
If the value is none of the above, it prints the error statement and asks the user the question again. It goes into the loop again with the new value from the user and checks the conditions again. It will exit only when the if or elif statement is true. Hope this helps.
Related
I have some homework which I'm not sure how to finish.
The task given was to make a script which would ask the user to enter his name, after entering it, the script would check if the name entered matches with any of the names on a pre-existing list.
If the name matches the script would ask the user if they would like to delete the name off the list or keep it.
If the name doesn't match with any names on the list, it asks if the user if they'd like to add it on it.
The script should write the list of names in the end.
I wrote it like this:
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
while name in lk:
print("Your name is already in our list.")
if name in lk:
bris = input("Would you like to delete your name off our list?[Y/N]:")
if bris == "Y":
lk.remove(name)
print("Your name was removed.")
print(lk)
break
elif bris == "N":
print("OK!",name,"Your name will be saved.")
print(lk)
break
while name not in lk:
doda = input("Your name is not registered on our list, would you like to add it?[Y/N]:")
if doda == "Y":
lk.append(name)
print("Your name has been added.")
print(lk)
elif doda == "N":
print("Alright, goodbye",name,"!")
break
Issue is, that I have no idea how to stop it once the user chooses to delete their name off the list, it always reads the next while because the deleted name is no longer on the list.
Also, I am very sorry if this looks like poo poo I'm new to coding
If the user needs to be entered only once, why using loop?
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
if name in lk:
print("Your name is already in our list.")
bris = input("Would you like to delete your name off our list?[Y/N]:")
if bris == "Y":
lk.remove(name)
print("Your name was removed.")
print(lk)
elif bris == "N":
print("OK!",name,"Your name will be saved.")
print(lk)
else:
doda = input("Your name is not registered on our list, would you like to add it?[Y/N]:")
if doda == "Y":
lk.append(name)
print("Your name has been added.")
print(lk)
elif doda == "N":
print("Alright, goodbye",name,"!")
Your loop structure is the root of the issue. Since you're using while loops I'm assuming you want your script to loop and keep asking for new inputs. In this case you'll want one loop that you can break out of when you're done entering names based on some user input:
lk = ['Peti','John','Mary','Claire','Hellen']
while keep_looping = 'Y':
# check a name
name = input("Please enter a name: ")
if name in lk:
# name in list logic here
else:
# name not in list logic here
# ask user if the loop should continue. Entering 'N' will break the loop
keep_looping = input("Would you like to try another name? (Y/N): ")
You can reuse your existing logic for checking for names in the list and adding/removing, but you'll also want the name checking logic as an if/else block so only one condition can be met per loop. Otherwise you'll run into the same issue when a name exists and gets removed.
There are other optimizations you can do but I'll let you figure those out on your own.
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
if name in lk:
print("your name already present in list")
k= input(("would you like to delete your name from the list: [y/n]:"))
if k=="y":
lk.remove(name)
print("your name is deleted from the list")
print(lk)
else:
print("your name kept as it is in the list")
else:
print("your name is not present in list")
k= input(("would you like to add your name to the list: [y/n]:"))
if k=="y":
lk.append(name)
print("your name is added to the list")
print(lk)
else:
print("list is kept as it is")
print(lk)
I have made a program which shows contact when contact name is given but the contact not found statement is coming twice
answer=""
while answer!= "yes":
contact_name = input("Entername: ")
contacts = {'Mom': 9469211475, 'Dad': 9419198443}
for name in contacts:
if name == contact_name:
print("Contact number is: ", contacts[name])
else:
print("Contact not found")
answer = input("Do you wish to exit? Please Enter Yes or No: ").lower()
print("Thank you")
Your code is currently an anti-pattern: you're using a dict but still looping over all its contents (with an O(n) complexity) to check if a certain key exists.
You don't need to loop the names if you're using a dict... Simply check if the name exists in the dict (with an O(1) complexity) and if it's not, print accordingly. In general, the pattern:
for x in iterable:
if x == y:
# do something with y
break
Is usually equivalent to:
if y in iterable:
# do something with y
So in your case:
contacts = {'Mom': 9469211475, 'Dad': 9419198443}
while answer != "yes":
contact_name = input("Entername: ")
if contact_name in contacts:
print("Contact number is: ", contacts[contact_name])
else:
print("Contact not found")
answer = input("Do you wish to exit? Please Enter Yes or No: ").lower()
print("Thank you")
Or, if you're comfortable with exception handling, this saves the double look-up:
contact_name = input("Entername: ")
try:
print("Contact number is: ", contacts[contact_name])
except KeyError:
print("Contact not found")
The loop for name in contacts: will iterate over the two elements in the contacts list. Hence, the code in the body of the for loop executes twice.
What you should do instead, is remove the else branch of the if statement and check once after the for loop completes whether the contact has been found or not.
A simple way to do this is by setting a new variable found to False before the loop, updating to True inside the loop if the contact is found and then checking the value of flag after the loop terminates.
You can set count of loop and change it every time it loops. then compare it with length of the dict. if it's same as the length of the dict, then that means the word is not found.
Like this:
answer=""
while answer!= "yes":
contact_name = input("Entername: ")
contacts = {'Mom': 9469211475, 'Dad': 9419198443}
loop = 0
for name in contacts:
loop += 1
if loop >= len(contacts):
print("Contact not found")
break
if name == contact_name:
print("Contact number is: ", contacts[name])
break
answer = input("Do you wish to exit? Please Enter Yes or No: ").lower()
print("Thank you")
Or just use for else
answer=""
while answer!= "yes":
contact_name = input("Entername: ")
contacts = {'Mom': 9469211475, 'Dad': 9419198443}
for name in contacts:
if name == contact_name:
print("Contact number is: ", contacts[name])
break
else:
print("Contact not found")
answer = input("Do you wish to exit? Please Enter Yes or No: ").lower()
print("Thank you")
I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==NamesArray[position]):
print("Name is: " +position)
break
if position>5:
print("The account number not found!")
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
When the user enters "P" it is supposed to call to def PopulateAccounts() and it does, but the problem is that it doesn't stop and the user keeps having to input account name, account number, and account balance. It is supposed to stop after the 5th name. How do I fix this?
It's because after PopulateAccounts() finishes while loop keeps iterating because choice is still P. If you want to ask user for another action simply ask him again for input.
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
choice = input("Please enter another action: ")
Also I'd recommend you use infinite loop to keep asking user for inputs, and break out of it when user enters 'E', this way you could also track invalid inputs.
while True:
choice = input("Please enter your choice: ")
if choice == "P":
PopulateAccounts()
elif choice == "S":
SearchAccounts()
elif choice == "E":
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid action \"{}\", avaliable actions P, S, E".format(choice))
print()
Your code asks for the user's choice only once -- before the loop begins. Because it never changes, that loop will stick with the user's choice for an infinite number of iterations.
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
# here at the end of this loop, you should
# get the user to enter another choice for the next
# iteration.
Your while loop has no counter to make it stop at the 5th name, and position only exists during the execution of the function that it is in. Also, position will never be greater than 4. range(5) starts at 0 and ends at 4.
Your for loop is fine. The problem is that your while loop is repeating. So after PopulateAccounts() is called, it correctly finishes after running through the for loop 5 times, but since choice is still equal to "P" (this hasn't been changed after the user first enters it), you still remain in the while loop, which means PopulateAccounts() will be called again and again. You can verify this by sticking an additional statement like "print("Hey, we're at the top of the While loop!")" after the "while" line.
Try rewriting your while loop with an explicit break if the user selects "E":
while True:
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
quit()
choice = input("Please enter either P, S or E: ")
Note that this extra input at the bottom also conveniently appears if the user typed something else besides "P", "S", or "E". You may also want to consider adding .upper() to the choice checks to make it case insensitive.
I have some code:
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
How can I keep asking for the player's name until they enter a name that is more than one character long, and tell them they must enter a valid name if they leave the field blank?
I tried
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
while len(PlayerName) < 1:
print("You must enter a name!")
but have been unsuccessful.
Use a while loop to get the input repetitively:
def get_player_name():
print()
player_name = ""
while len(player_name) <= 1:
player_name = input('Please enter your name: ')
print()
return player_name
The way you are currently using it, you use the while statement to only print the error message.
PS: I've converted your variable names etc to small_caps_format because that is what PEP recommends.
def GetPlayerName():
print()
while True:
PlayerName = input('Please enter your name: ')
if len(PlayerName) > 1:
break
print("Your name is too short! :c")
print()
return PlayerName
One solution amongst others, and doesn't require any variables outside of the while loop. As mentioned by #jme, the error message is rather easy to print with this solution. The issue with your code is that:
Your while loop is after the return statement is called, so it's affectively rendered mute.
Your while loop is infinite-- it doesn't give the user a chance to re-try!
I'm a bit confused on the logic of doing this.
I want the user to be able to input the number of items they have, and then ask them at the end if they are done. Right now I'm asking after every single item, and I don't like it.
How should I modify this code to get what I want?
Input:
if next1 == "2":
next2=input("How many would you like to add? ")
val = int(next2)
print("")
count = 0
while count < int(next2):
count = count + 1
next3=input(str(count) + ". Input: ")
print("")
check=input("Are you sure? (Y/N) ")
while check not in ("YyYesNnNo"):
check=input("Are you sure? (Y/N) ")
if check in ("YyYes"):
add(next3)
home()
elif check in ("NnNo"):
sort(numbers)
home()
Function:
def add(next2):
numbers.append(next2)
sort(numbers)
home()
Okay, well generally you might do something like this
def confirm_with_user():
user_data = ""
while user_data not in "YyYesNnNo":
user_data = input("Are you sure? (Y/N) ")
return user_data.lower() in "yes":
Then at the point in your code when you want to confirm with your user you just do
if confirm_with_user():
#proceed...
else:
#They don't want to proceed