Python Redirecting - python

So I am trying to make a Password checker and generator. So first i need to make a menu to tell if the user wants to check or generate or password. But I'm having a bit of a problem to redirect the user to their choice.
I've tried to use this 'if main = name' but that doesn't even work. I've also tried to place the 'def' above the all the other text. But wouldn't work because it would display that def first instead of displaying the menu
import sys, os
def mainmenu():
print()
print("________________________________________________________")
print("Hello and welcome to the password checker and generator.")
print("________________________________________________________")
input()
print("Mainmenu")
input()
print("Press 1 to Check a password.")
print("Press 2 to Generate a password.")
print("Press 3 to quit.")
UserOp = int(input("What is your choice?:"))
if UserOp == 1:
checkpass()
elif UserOp == 2:
generatepass()
elif UserOp == 3:
sys.exit(0)
else:
print("This option is seen to be invalid.")
mainmenu()
def checkpass():
print()
print("You have chosen to check a password.")
def generatepass():
print()
print("You have chosen to generate a password.")
So what I'm trying to re-arrange or add code to make the program display the menu first then redirect the user to their designated options.

Unless you just typed it in wrong on stackoverflow it looks like none of your initial print options are in the mainmenu function
It’s looks at tho the options are also outside of the functions and mix in with your other functions

Check your indentation, pieces of your code are out of places where they should be.
import sys, os
def mainmenu():
print()
print("________________________________________________________")
print("Hello and welcome to the password checker and generator.")
print("________________________________________________________")
input()
print("Mainmenu")
input()
print("Press 1 to Check a password.")
print("Press 2 to Generate a password.")
print("Press 3 to quit.")
UserOp = int(input("What is your choice?:"))
if UserOp == 1:
checkpass()
elif UserOp == 2:
generatepass()
elif UserOp == 3:
sys.exit(0)
else:
print("This option is seen to be invalid.")
mainmenu()
def checkpass():
print()
print("You have chosen to check a password.")
def generatepass():
print()
print("You have chosen to generate a password.")
if __name__ == '__main__':
mainmenu()

Related

Create Loop in if / else statement

I am trying to loop this function in the case the 'else' is reached but I'm having difficulties.
I tried while False and it doesn't do the print statements, I guess it kicks out of the function as soon as it ends up being false. I tried the True and I think that's the way to go but when it hits Else it just repeats. I'm thinking... maybe I need to do another Elif for the repeat of the whole function and the else as just an escape if needed.
def login(answer):
while False:
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")
while False:
should be
while True:
otherwise you never enter the loop
Further:
else:
print("I don't understand your selection")
should be:
else:
print("I don't understand your selection")
answer = input("enter a new choice")
You might even refactor your code to call the function without parameter:
def login():
while True:
answer = input("enter a choice (a for login or b for account creation")
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")

How do I fix my Python function so that it returns with input prompts?

I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...

Menus Looping on Python

for an assignment, I made a menu and must have it work in a way to execute multiple functions. However, the problem is that when I use the menu and put in an answer that doesn't exist, I cannot get it to work correctly. So when I re-enter an option number for "Incorrect option, try again: ", I do not get the number re-evaluated to execute. Since my code is far from finished, right now I want to be able to choose "4" as an input and get "Incorrect option, try again" as an output and input "1" into this to get the output "Choose the level of difficulty".
def main_menu():
print(10*"=","GAME",10*"=",'\n')
print("1. Choose level of difficulty ")
print("2. Start Game")
print("3. Exit the Game",'\n')
print("Current Difficulty: /5")
print("Highest Score Reached:",'\n')
option=input("Enter an option: ")
return option
def user_input():
while True:
try:
if option==1:
difficulty()
break
elif option==2:
start()
break
elif option==3:
exit()
break
except:
option=input("Incorrect option, try again: ")
def difficulty():
d=int(input("Choose level of difficulty: "))
if 1<=d<=5:
start()
else:
int(input("Incorrect option, try again: "))
#difficulty()
return d
Here a is modified version of your code which I believe does what you are looking for.
def main_menu():
print(10 * "=", "GAME", 10 * "=", '\n')
print("Current Difficulty: /5")
print("Highest Score Reached:", '\n')
while True:
print("1. Choose level of difficulty")
print("2. Start Game")
print("3. Exit the Game", '\n')
try:
option = int(input("Enter an option: "))
if option == 1:
difficulty()
elif option == 2:
start()
elif option == 3:
return
else:
print("Incorrect option, try again!")
except ValueError:
print("Invalid option.")
def difficulty():
try:
d = int(input("Choose level of difficulty: "))
if 1 <= d <= 5:
print(d)
start()
else:
print("Incorrect option, try again.")
except ValueError:
print("Invalid value.")
def start():
print("Starting game...")
if __name__ == "__main__":
main_menu()
Let me know if anything is misunderstood or mistaken.

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

Categories

Resources