How to print something specific if something random is chosen? - python

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"

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)

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

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

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"

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

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

Categories

Resources