Branching based on user input w/ raw_input(); no path followed - python

I don't understand why my code doesn't work.
Expected behaviour:
Read what the user is inputting
Respond with an appropriate message like "you have choose to encrypt"
The code below prompts the user for input, but none of the lines given in the if block is run, even if the user enters 1, 2, or 3.
Here's my code:
print ("Press 1 to encrypt, 2 to decrypt and 3 to exit")
raw_input()
if raw_input == "1":
print ("you have choosen to encrypt")
elif raw_input == "2":
print ("you have choosen to decrypt")
elif raw_input == "3":
print ("you have choosen to exit, goodbye!")

I assume you are using the raw_input() function from Python. You should store the user input into a variable before proceeding to the if-else statement. Adding an "else" will be nice.
print ("Press 1 to encrypt, 2 to decrypt and 3 to exit")
user_input = raw_input()
if user_input == "1":
print ("you have choosen to encrypt")
elif user_input == "2":
print ("you have choosen to decrypt")
elif user_input == "3":
print ("you have choosen to exit, goodbye!")
else:
print("Please enter 1, 2, or 3.")

Related

How to break loop to user's choice once valid input is received?

If the user does not select 1 or 2, I want the code to say "Please enter 1 or 2 to continue", that part works. However if user inputs "6" it asks "Please enter 1 or 2 to continue" as it should but if a valid input is entered directly after an invalid input, code does not display correctly.
I've tried to do this without the requirement function but nothing seems to work how I want it to.
def requirement():
choice = ""
while choice != "1" and choice != "2":
choice = input ("Please enter 1 or 2 to continue.\n")
if choice == "1" and choice == "2":
return choice
def intro():
print ("Enter 1 to enter the cave\n")
print ("Enter 2 to explore the river\n")
play_again = input ("What would you like to do?\n")
if play_again in "1":
print ("You win!")
elif play_again in "2":
print ("YOU LOSE")
print ("Thanks for playing!")
exit()
else:
requirement()
intro()
def intro():
print ("Enter 1 to enter the cave\n")
print ("Enter 2 to explore the river\n")
play_again = input ("What would you like to do?\n")
return play_again
def game(choice):
if choice == "1":
print ("You win!")
elif choice == "2":
print ("YOU LOSE")
print ("Thanks for playing!")
exit()
else:
choice = input ("Please enter 1 or 2 to continue.\n")
game(choice)
game(intro())
The else statement already takes care of whether or not a 1 or 2 is input, so there is no need for the requirement function.

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

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.

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

Python If/Else Statement Assistance

def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = str(input("Make a choice.."))
if user_choice in valid_answer:
def check_valid(user_choice):
if user_choice == 1: #Error section V
return("You started the game.")
else:
user_choice != 1
return("Credits to ____, created by ____")
check_valid(user_choice) #Error Section ^
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())
Okay, so the error should be labeled. That specific if/else statment shows up as "None" and I have tried every method to fix it. One method worked for the if/else statement on the outside, but not this one.
You're taking input as a string str(input()). Then, you're checking if user_input == 1; testing to see if it is an integer, even though it is a string. Instead, try converting to an integer using int(input()). Also, the line user_input != 1 is unnecessary, it's just the equivalent of writing True in your code. Furthermore, you define a function in your if statement, which shouldn't be there:
def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = int(input("Make a choice.."))
if user_choice in valid_answer:
if user_choice == 1:
return("You started the game.")
else:
return("Credits to ____, created by ____")
check_valid(user_choice)
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())

How to loop this cryptography program

I have this code, but I'm not sure how to make it loop, so that after you finish encoding or decoding it brings the menu back up. It's working well right now, just no idea how to loop it.
import string
key = "qetuoadgjlxvnw ryipsfhkzcbm"
abc = "abcdefghijklmnopqrstuvwxyz "
abc_key = string.maketrans(abc, key)
key_abc = string.maketrans(key, abc)
def encode():
"""Encodes input text"""
text = raw_input ("Please enter text to be encoded: ")
text_lower = string.lower(text)
text_lower;
print text_lower.translate(abc_key);
def decode():
"""decyphers code"""
code = raw_input ("Please enter code to be decyphered: ")
code_lower = string.lower(code)
code_lower;
print code_lower.translate(key_abc);
# Welcome message
print "Welcome to Jake's Cryptography program!"
# Print menu
print "SECRET DECODER MENU"
print "0) Quit"
print "1) Encode"
print "2) Decode"
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."
any help is appreciated!
Wrap it in a while statement. Something like this:
# Welcome message
print "Welcome to Jake's Cryptography program!"
# Print menu
while True:
print "SECRET DECODER MENU"
print "0) Quit"
print "1) Encode"
print "2) Decode"
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
break
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."
Notice the break statement!
The above will print the menu each time. If you just want to print the prompt, move the while True: line down after the menu (but before the raw_input line), and then fix your indentation.
# Welcome message here
option = -1
while option != 0:
# Print menu
# Raw input for the next option
# Processing of the options
option = 13
while (int(option) > 0):
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
print "and good night"
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."

Categories

Resources