How to test that variable is not equal to multiple things? - python

This is the piece of code I have:
choice = ""
while choice != "1" and choice != "2" and choice != "3":
choice = raw_input("pick 1, 2 or 3")
if choice == "1":
print "1 it is!"
elif choice == "2":
print "2 it is!"
elif choice == "3":
print "3 it is!"
else:
print "You should choose 1, 2 or 3"
While it works, I feel that it's really clumsy, specifically the while clause. What if I have more acceptable choices? Is there a better way to make the clause?

The while bit could be refactored a little to make it a little bit cleaner by checking if the element is within a list of choices like so
while choice not in [1, 2, 3]:
This is checking if the value of choice is not an element in that list

You can push the logic into the loop, and replace
while choice != "1" and choice != "2" and choice != "3":
with
while True:
and then the initial line choice = "" is unnecessary. Then, in each branch, once you're done what you want to do you can break.

I think something like that would be better
possilities = {"1":"1 it is!", "2":"2 it is!", "3":"3 it is!"}
choice = ""
while True:
choice = raw_input("pick 1, 2 or 3")
if choice in possilities:
print possilities[choice]
break
else:
print "You should use 1, 2 or 3"

You can use a dictionary to map 1 to the code you want to execute when 1 is the value, and so on... That way you get rid of the ifs and your code can support other values in the future by simply updating the dictionary. As for the condition in the while, you just check if the key is in the dictionary.

I'd suggest having a function which just loops until a valid option is chosen, then returns the chosen value.
This means the rest of your code is not intended inside the while, keeping everything nice and flat ("Flat is better than nested")
def get_choice(options):
"""Given a list of options, makes the user select one.
The options must be strings, or they will never match (because raw_input returns a string)
>>> yn_choices = ['y', 'n']
>>> a = get_choice(options = yn_choices)
"""
prompt_string = "Pick " + ", ".join(options)
while True:
choice = raw_input(prompt_string)
if choice in options:
return choice
else:
print "Invalid choice"
# Prompt user for selection
choice = get_choice(["1", "2", "3"])
# Do stuff with choice...
if choice == "1":
print "1 it is!"
elif choice == "2":
print "2 it is!"
elif choice == "3":
print "3 it is!"
else:
print "You should choose 1, 2 or 3"

I think you can use a set which contains all of your possible choices and use "in" expression to judgefor the while part.
As for the if-else part, print (choice, " it is!") will be ok.

while str(choice) not in "123"
.....

Related

Simple elif statement

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 ..

How to print something specific if something random is chosen?

I have a program that prints things randomly from lists. How do I make the program print something for the choice it made.
For example:
choices=["X","Y"]
print random.choice(choices)
if random.choice == "X":
print "XX"
elif random.choice == "Y":
print "YY"
In your code, you printed the choice you made to the screen, and then compared the random.choice function to the possible choices. You need to instead store the choice made, and then compare that to the choices.
import random
choices = ["X","Y"]
choice = random.choice(choices)
print choice
if choice == "X":
print "XX"
elif choice == "Y":
print "YY"

Trying to make a conditional checking shorter [duplicate]

This is the piece of code I have:
choice = ""
while choice != "1" and choice != "2" and choice != "3":
choice = raw_input("pick 1, 2 or 3")
if choice == "1":
print "1 it is!"
elif choice == "2":
print "2 it is!"
elif choice == "3":
print "3 it is!"
else:
print "You should choose 1, 2 or 3"
While it works, I feel that it's really clumsy, specifically the while clause. What if I have more acceptable choices? Is there a better way to make the clause?
The while bit could be refactored a little to make it a little bit cleaner by checking if the element is within a list of choices like so
while choice not in [1, 2, 3]:
This is checking if the value of choice is not an element in that list
You can push the logic into the loop, and replace
while choice != "1" and choice != "2" and choice != "3":
with
while True:
and then the initial line choice = "" is unnecessary. Then, in each branch, once you're done what you want to do you can break.
I think something like that would be better
possilities = {"1":"1 it is!", "2":"2 it is!", "3":"3 it is!"}
choice = ""
while True:
choice = raw_input("pick 1, 2 or 3")
if choice in possilities:
print possilities[choice]
break
else:
print "You should use 1, 2 or 3"
You can use a dictionary to map 1 to the code you want to execute when 1 is the value, and so on... That way you get rid of the ifs and your code can support other values in the future by simply updating the dictionary. As for the condition in the while, you just check if the key is in the dictionary.
I'd suggest having a function which just loops until a valid option is chosen, then returns the chosen value.
This means the rest of your code is not intended inside the while, keeping everything nice and flat ("Flat is better than nested")
def get_choice(options):
"""Given a list of options, makes the user select one.
The options must be strings, or they will never match (because raw_input returns a string)
>>> yn_choices = ['y', 'n']
>>> a = get_choice(options = yn_choices)
"""
prompt_string = "Pick " + ", ".join(options)
while True:
choice = raw_input(prompt_string)
if choice in options:
return choice
else:
print "Invalid choice"
# Prompt user for selection
choice = get_choice(["1", "2", "3"])
# Do stuff with choice...
if choice == "1":
print "1 it is!"
elif choice == "2":
print "2 it is!"
elif choice == "3":
print "3 it is!"
else:
print "You should choose 1, 2 or 3"
I think you can use a set which contains all of your possible choices and use "in" expression to judgefor the while part.
As for the if-else part, print (choice, " it is!") will be ok.
while str(choice) not in "123"
.....

If true, ignore variable from now on in Python

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")

Trying to use raw_input from another function

from sys import exit
def start():
print "You woke up in a dungeon"
print "There is three weapon in front of you"
print "A sword, a staff and dagger"
print "Which one do you choose"
choice = raw_input("")
if choice == "dagger":
print "A rogue huh?"
elif choice == "staff":
print "A wizard how interesting..."
elif choice == "sword":
print "A warrior."
else:
print "..."
dungeon_path()
def dungeon_path():
if choice == "dagger":
print "Which way you choose rogue"
start()
I wanna print the last line if I choosed dagger in first function but I can't seem to get it work I tried to give choice a value and then used "if" but it didn't work that way either so what do I do...
You could pass the choice variable as an argument to the dungeon_path function:
...
print "..."
dungeon_path(choice)
def dungeon_path(choice):
if choice == "dagger":
print "Which way you choose rogue"

Categories

Resources