Why is my loop not stopping at the number I set? - python

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.

Related

Python 3 Menu with Quit option

I'm trying to create a sort of CLI menu in Python (very new to this) and having an issue with the quit option mostly, it won't actually quit and jumps to the "Oooops that isn't right" option instead, or repeats the last step. It does seem to work if you put it as the first choice though
I know I must be doing something daft. I've tried just putting the variable at the end of the function, as well as the menu function itself but that didn't seem to work.
Snippet below if anyone can point me in the right direction.
def my_menu():
choice = input("Please choose an choice: ")
choice = choice.lower()
while (choice != "quit"):
if choice == "b":
a_thing()
my_menu()
if choice == "quit":
break
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
Try to input the choice another time at the end of the loop, remove the call to the my_menu() function and remove the if choice=="quit" block (because the loop will automatically quit when the choice is set to "quit")
def my_menu():
choice = input("Please choose an choice: ").lower()
while (choice != "quit"):
if choice == "b":
a_thing()
else:
print("Oooops that isn't right")
choice = input("Please choose an choice: ").lower()
def a_thing():
print("a thing")
my_menu()
Or you can remove the loop and just verify using if statements and in the case of "quit" you just put return to break the loop
def my_menu():
choice = input("Please choose an choice: ").lower()
if choice == "b":
a_thing()
elif choice == "quit":
return
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
I ran your code, and on its first iteration it runs as expected. After that, the recursive call to my_menu() starts to cause problems.
Walking through it, first you enter some random string, "hi", and it will enter the while loop and use the else case. This will call my_menu(), which then calls another while loop. When you enter that new while loop, any exiting that you do (e.g. break) won't exit the first loop, only the loop that your currently in, so you're in an infinite loop because you can never "go back" and change the value of choice in the first loop.
A way you could achieve this behavior with the least amount of changes to your code would be like this:
def my_menu():
choice = ""
while (choice != "quit"):
choice = input("Please choose an choice: ")
choice = choice.lower()
if choice == "b":
a_thing()
if choice == "quit":
break
else:
print("Oooops that isn't right")
def a_thing():
print("a thing")
my_menu()
(I removed your recursive calls to my_menu(), moved the input lines to within the loop, and initialized choice before the loop)

Computer Generates a Number, User Guesses Number, No Matter What it is Always Incorrect

I made a simple program where a user guesses a randomly generated computer number. To test if the program is working, I changed the generated computer value to 5. However, when I "guess" 5, I am somehow still incorrect.
Can someone please tell me what is wrong with this code?
I tried messing about with returning variables but I don't understand how the return command works so I was not successful.
def computer_roll():
global comproll
comproll = random.randint(1,3)
# comproll = 5
user_guess()
def user_guess():
global user
user = input("Input a number: ")
guess_evaluation()
def guess_evaluation():
if user != comproll:
print("You are incorrect.")
again = input("Would you like to try again? ")
if again in("y"):
user_guess()
elif again in ("n"):
print("Thanks for playing.")
elif user == comproll:
print("You are correct.")
again = input("Would you like to play again? ")
if again in("y"):
user_guess()
elif again in ("n"):
print("Thanks for playing.")
computer_roll() # Start```
# Expected Results:
# When I enter 5 it should say "You are correct." and then "Would you like to play again?"
# Actual Results:
# When I enter 5 it says "You are incorrect" and then "Would you like to play again?"
You are comparing integer with string which is why it will never be correct.
Try, user = int(input("Input a number: "))
On a sidenote, you really shouldn't be using global variables. Learn to use returns especially since you are using functions, otherwise there is no point using functions at all.
Below is a sample code:
import numpy as np
import random
def computer_roll():
return random.randint(4,6)
def user_guess():
return int(input("Input a number: "))
def guess_evaluation():
if user_guess() != computer_roll():
print("You are incorrect.")
else:
print("You are correct.")
again = input("Would you like to play again? ")
if again in ("n"):
print("Thanks for playing.")
else:
guess_evaluation()
guess_evaluation()
For me it works, except for the syntax error at the input field:
def guess_evaluation():
if user != comproll:
print("You are incorrect.")
again = input("Would you like to try again? ")
if again in("y"): # syntax error here, enter space between "in" and "('y')".
user_guess()
elif again in ("n"):
print("Thanks for playing.")
user input curently a string when comproll is a int. You can change this with:
user = int(input("Input a number: "))

How do I ask the user if they want to play again and repeat the while loop?

Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break

How to stop the beginning of my function's loop from repeating

I have created a code in which the user will input their choice which will continue in a loop if the variable 'contin' equals "yes". When the user enters the choice "no" or any other input it will print their overall answers or the error message and end the loop. Instead it then repeats the beginning of the function (in this case it's whether the user wanted to continue or not). Is there a way for me to prevent this from happening?
This is the code:
def userinput():
while True:
contin = input("Do you wish to continue the game? If so enter 'yes'. If not enter 'no'.")
if contin == 'yes':
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"']
guess = input("What symbol do you wish to change? ")
symbol_dictionary[guess] = input("Input what letter you wish to change the symbol to.(Make sure the letter is in capitals.) ")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
else:
print("Please enter a valid input.")
All you need to do is exit the function; add a return in your no branch:
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
# exit the function
return
Just add a break or a return at the end of the elif statement:
print("Well done! You have completed the game!")
break # or return
This will exit the loop. Break makes more sense in this context.

Ask the user if they want to repeat the same task again

If the user gets to the end of the program I want them to be prompted with a question asking if they wants to try again. If they answer yes I want to rerun the program.
import random
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
total = 0
final_coin = random.randint(1, 99)
print("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
total = total + user_input
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
while total != final_coin:
user_input = int(input("Enter next coin: "))
total = total + user_input
if total > final_coin:
print("Sorry - total amount exceeds", (final_coin))
if total < final_coin:
print("Sorry - you only entered",(total))
if total== final_coin:
print("correct")
You can enclose your entire program in another while loop that asks the user if they want to try again.
while True:
# your entire program goes here
try_again = int(input("Press 1 to try again, 0 to exit. "))
if try_again == 0:
break # break out of the outer while loop
This is an incremental improvement on the accepted answer:
Used as is, any invalid input from the user (such as an empty str, or the letter "g" or some such) will cause an exception at the point where the int() function is called.
A simple solution to such a problem is to use a try/except- try to perform a task/ code and if it works- great, but otherwise (except here is like an else:) do this other thing.
Of the three approaches one might try, I think the first one below is the easiest and will not crash your program.
Option 1: Just use the string value entered with one option to go again
while True:
# your entire program goes here
try_again = input("Press 1 to try again, any other key to exit. ")
if try_again != "1":
break # break out of the outer while loop
Option 2: if using int(), safeguard against bad user input
while True:
# your entire program goes here
try_again = input("Press 1 to try again, 0 to exit. ")
try:
try_again = int(try_again) # non-numeric input from user could otherwise crash at this point
if try_again == 0:
break # break out of this while loop
except:
print("Non number entered")
Option 3: Loop until the user enters one of two valid options
while True:
# your entire program goes here
try_again = ""
# Loop until users opts to go again or quit
while (try_again != "1") or (try_again != "0"):
try_again = input("Press 1 to try again, 0 to exit. ")
if try_again in ["1", "0"]:
continue # a valid entry found
else:
print("Invalid input- Press 1 to try again, 0 to exit.")
# at this point, try_again must be "0" or "1"
if try_again == "0":
break

Categories

Resources