I have an assignment which forces me to ignore certain variables if a condition is fullfilled. Basically I'm asking the user for an input and tell him the Valid choices he has, but after a while that originally valid choice is no longer valid anymore. I thought about doing something like this
while True:
choice = input('You can choose between: ', Choice1, Choice2, Choice3)
if choice == Choice1:
Choice1Counter +=1
break
elif choice == Choice2:
Choice2Counter +=1
break
elif choice == Choice3:
Choice2Counter +=1
break
else:
choice = input('You can choose between: ', Choice1, Choice2, Choice3)
continue
With this I would first of all 'force' a valid choice and if the input is a valid choice I would add 1 to the Counter of that choice. Should the Counter hit its limit I thought about doing something like this
if Choice1Chounter == 4:
#ignore Choice 1 for the rest of the Programm or until Choice1 is reset
This should then basically mean that Choice1 is ignored by the program, which would look a bit like this (in my mind)
choice = Input('You can choose between: ', Choice1, Choice2, Choice3)
With that it should basically "print" out the following when running the Program after Choice1Counter hits ist limit
You can choose between: Choice2 Choice3
I have 82 Valid Inputs and can't really define all 82! combinations of them, so I thought about this, but can't find a command that just ignores a variable for the rest of the Program.
You should not be using separate variables for this, but rather a dictionary, and a list of currently valid keys.
choices = ["Choice1", "Choice2", "Choice3", "Choice4"]
counters = dict((choice, 0) for choice in choices)
while choices: # exit when no choices left
choice = raw_input("Choose from %s > " % " ".join(choices)) # input in Py3
if choice in choices:
counters[choice] += 1
if counters[choice] == 4:
choices.remove(choice)
else:
print("That choice is not valid. Try again")
Related
List item
i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks
Sloved!!
import sys
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:
if difficulty == '1':
print('Easy game mode is set!')
elif difficulty =='2':
print('Hard game mode is set!')
elif difficulty =='quit':
print('Sheeeeeeeeeeeeeeesh')
except:
continue
if difficulty == '1' or difficulty =='2':
break
elif difficulty == 'quit':
sys.exit('byeeeee')
break
#elif difficulty
else:
print('invalid ')
You are storing the user input in uppercase for difficulty variable.
And in if condition verifying in lowercase.
So remove the upper() from
input("Choose difficulty 1 for easy 2 for hard: ").upper()
try: and except: is probably not what you want to use here because you won't get a ValueError and thus the except does not execute. Maybe try something like:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
It breaks the loop when the correct input is given, and keeps looping otherwise.
If you would LIKE to have a ValueError when they enter a wrong input you can use raise like so:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
raise ValueError #notice the additional line here
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)
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:
...
When I run this code it always goes to the else. Even when I choose 1, 2, or 3. How can I achieve a proper if, elif else statement?
def main():
name = input("What is your name?")
print("Hello", name)
choice = int
choice = 0
choice = input("Please choose a number from the following options: \n 1. Paper \n 2. Rock \n 3. Scissors")
print (choice)
if choice == 1:
print ('You chose number 1')
elif choice == 2:
print ('You chose number 2')
elif choice == 3:
print ('You chose number 3')
else:
print ('Invalid Entry Mush')
return
main()
input returns a string. You will need to cast it to an int so that your elif options that check for ints are triggered:
choice = int(input("Please choose a number from the following options: \n 1. Paper \n 2. Rock \n 3. Scissors"))
By the way the two lines before that one are unnecessary.
Or you can put your if statements between quotes: ex: if choice == "1" print("nr 1") elif choice == "2" so on ..
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