I have the following code:
print('WELCOME TO YOUR TASK MANAGER!')
#Asks the user for a filename.
filename = input('What would you like your filename to be: \n(Please type
\'.txt\' at the end of the name)');
#Creates an empty list and asks the user for the tasks needing to be written down and creates a file.
tasks = []
with open(filename, 'w+') as f:
prompt = 'Please enter what you need to do: \n When you are done putting in
tasks please type \'exit\' '
user_input = input(prompt).strip()
while (user_input != 'exit'):
tasks.append(user_input)
user_input = input(prompt).strip()
#Asks the user whether or not he/she would like to add, remove, or exit the program.
prompt1 = input('Would you like to add or remove a task? \nIf add please
type \'add\'. \nIf remove please type \'remove\'.\n If not please type
exit.')
if prompt1 == 'add':
prompt1 = input('Please say what you would like to add:')
tasks.append(prompt1)
if prompt1 == 'remove':
prompt1 = input('Please say what you would like to remove:')
tasks.remove(prompt1)
tasks.sort()
f.write(str(tasks))
else:
tasks.sort()
f.write(str(tasks))
#Outputs the list of the tasks to the user and tells the user where a copy of the list is saved.
print(tasks)
print('A copy of your tasks is in the file \'{}\''.format(filename))
I would like to be able to run the prompt1 input as many times as needed until the user enters exit. However, when running the code it only allows the user to enter one of the 3 choices: add, remove, or exit. Any ideas on how I could write the code to allow multiple entries from prompt 1 after the first entry is submitted?
This should work:
tasks = []
with open(filename, 'w+') as f:
prompt = 'Please enter what you need to do: \n When you are done putting in
tasks please type \'exit\' '
prompt1 = input(prompt).strip()
while (prompt1 != 'exit'):
tasks.append(user_input)
#Asks the user whether or not he/she would like to add, remove, or exit the program.
prompt1 = input('Would you like to add or remove a task? \nIf add please
type \'add\'. \nIf remove please type \'remove\'.\n If not please type
exit.')
prompt1 = prompt1.strip()
if prompt1 == 'add':
prompt1 = input('Please say what you would like to add:')
tasks.append(prompt1)
elif prompt1 == 'remove':
prompt1 = input('Please say what you would like to remove:')
tasks.remove(prompt1)
tasks.sort()
f.write(str(tasks))
else:
tasks.sort()
f.write(str(tasks))
#Outputs the list of the tasks to the user and tells the user where a copy of the list is saved.
print(tasks)
print('A copy of your tasks is in the file \'{}\''.format(filename))
Changes made:
Used elif instead of second if. Else even if first condition satisfies, second condition need also be treated.
replaced the user_input variable with prompt1 itself
Brought printing the tasks outside the user input loop
You can try something like this :
a = input("Enter a file name: ")
task = []
while a != ("stop"):
#if else logic
.....
print(task)
a = input("Enter a word: ")
I hopes this is the code, what are you looking for.
#!/usr/bin/python3
import sys
print('WELCOME TO YOUR TASK MANAGER!')
#Asks the user for a filename.
filename = input("What would you like your filename to be: \n(Please type\.txt\' at the end of the name)");
#Creates an empty list and asks the user for the tasks needing to be written down and creates a file.
tasks = []
while True:
prompt = 'Please enter what you need to do: \n When you are done putting in tasks please type \"exit\"" '
user_input = input(prompt).strip()
if user_input == 'exit':
with open(filename, 'w+') as f:
f.write(tasks)
sys.exit()
else:
tasks.append(user_input)
#Asks the user whether or not he/she would like to add, remove, or exit the program.
prompt1 = input('Would you like to add or remove a task? \nIf add please type \'add\'. \nIf remove please type \"remove\".\n If not please type exit.')
if prompt1 == 'add':
prompt1 = input('Please say what you would like to add:')
tasks.append(prompt1)
elif prompt1 == 'remove':
prompt1 = input('Please say what you would like to remove:')
tasks.remove(prompt1)
tasks.sort()
f.write(str(tasks))
else:
if user_input == 'exit':
with open(filename, 'w+') as f:
f.write(tasks)
sys.exit()
Related
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.
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.
Having an issue with checking if user input is in a dictionary.
Basics of program is there's a shop inventory. The items are stored in a dictionary with corresponding values e.g. {'kettle': 3,.....}
Then I want user to write what they want. So if the user has entered 'kettle' I want to remove the item from the shop inventory and put in user inventory.
The main problem right now is just getting an if statement together. This is what I'm trying:
user_choice = input('What would you like to buy? ')
if user_choice in shop_inventory:
print('Complete')
else:
print('Fail')
How can I get the program to print "Complete"?
You can use pop() to remove the item from the shop_inventory.
shop_inventory = {'kettle': 3}
user_choice = input('What would you like to buy? ')
if user_choice in shop_inventory:
shop_inventory.pop(user_choice)
print(shop_inventory)
print('Complete')
else:
print('Fail')
Instead of input(), use raw_input:
user_choice = raw_input('What would you like to buy? ')
if user_choice in shop_inventory:
print('Complete')
else:
print('Fail')
Explanation:
In Python 2, raw_input() returns a string, and input() tries to run the input as a Python expression.
In Python 3 there is only raw_input(). It was renamed in input().
As statet here
For the first bit, as I print out the "ask2", it prints out "exit" as opposed to the licence plate that it's supposed to be printing.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
ask2 = ""
plate = ""
if int(ask) == 1:
ask2 = ""
print("========================================================================")
while ask2 != 'exit':
ask2 = input ("Please enter it in such form (XX00XXX): ").lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
**print("The program, will determine whether or not the car "+str(plate),str(ask)+" is travelling more than the speed limit")**
Also I am looking for a few good codes that are good for appending (putting the data in a list), and printing.
This is what I've done;
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == ["y","Y"]:
do_the_quiz()
if tryagain==["n","N"]:
cars.append(plate+": "+str(x))
print(cars)
When you print ask2 it prints 'exit' because you set it to exit with ask2 = 'exit', and your loop cannot terminate before ask2 is set to 'exit'.
You could use ask2 for the user's input, and another variable loop to determine when to exit the loop. For example:
loop = True
while loop:
# ...
if valid.match(ask2) or ask2 == 'exit':
loop = False
I am not quite sure what your other block of code is trying to achieve, but the way that you test tryagain is incorrect, it will never be equal to a two element list such as ["y","Y"], perhaps you meant to use in?, This change shows one way to at least fix that problem:
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == "y":
do_the_quiz()
else:
cars.append(plate+": "+str(x))
print(cars)
Sorry I'm just a beginner at python so this is probably a very simple question, but I have a code and I want to loop it so after the code asks the user if they want to play again and the user inputs 'yes' to restart the code and 'no' to end the code. If they input anything other than yes or no it should ask tell them to enter yes or no then ask the question again. How would I do this exactly? (I do know about while and for loops but I'm not sure how I would use them in this way)
This is a simple one:
while True:
a = input("Enter yes/no to continue")
if a=="yes":
gameplay()
continue
elif a=="no":
break
else:
print("Enter either yes/no")
Where gameplay function contains the code to be executed
I would do it the following way:
while True:
# your code
cont = raw_input("Another one? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Another one? yes/no > ")
if cont == "no":
break
If you use Python3 change raw_input to input.
My approach to this:
# Sets to simplify if/else in determining correct answers.
yesChoice = ['yes', 'y']
noChoice = ['no', 'n']
# Prompt the user with a message and get their input.
# Convert their input to lowercase.
input = raw_input("Would you like to play again? (y/N) ").lower()
# Check if our answer is in one of two sets.
if input in yesChoice:
# call method
elif input in noChoice:
# exit game
exit 0
else:
print "Invalid input.\nExiting."
exit 1
I think this is what you are looking for
def playGame():
# your code to play
if __name__ == '__main__':
play_again = 'start_string'
while not play_again in ['yes', 'no']:
play_again = raw_input('Play Again? (type yes or no) ')
if play_again == 'yes':
playGame()
I tried this short boolean script that will maintain the loop until the if statement is satisfied:
something = False
while not something:
inout = raw_input('type "Hello" to break the loop: ')
if inout == 'Hello':
something = True
my approach is to just have a while loop
y_or_n = input("Do you want to validate another email or not? y/n: ")
while y_or_n == 'y' or email_again == 'yes':
name = input("Enter another name ")#adapt this to your needs
name = name.lower()#adapt this to your needs
#your code etc
y_or_n = input("Do you want to validate another email or not? y/n: ")