I am newbie, and I need help, please. I am asking user to guess any item, if it's not correct - keeps asking. However, I am trying to do many ways but cannot get the code right. Sometimes, it's just ask 1 time and stop even if the user input is wrong; or it does not recognize the answer right or wrong and keep asking.
Thank you!
animal = ['bird','dog','cat','fish']
while True:
guess = input('Guess my favorite animal: ')
if guess == animal:
print("You are right")
break
print('Try again!')
Your code won't work because you are comparing user input to a list.
guess == animal
Will be evaluated as:
guess == ['bird','dog','cat','fish'] # Evaluates to "false"
Testing if an element is in a list is simple:
# A set of animals
animals = ['bird','dog','cat','fish']
'bird' in animals # Returns True, because bird is in the list
>>> True
'cow' in animals # Returns False, because cow is not in the list
>>> False
Assuming each 'animal' or element of the list is unique, a set is a more efficient data structure to use.
Your code then becomes:
animal = {'bird','dog','cat','fish'}
while True:
guess = input('Guess my favorite animal: ')
if guess in animal:
print("You are right")
break
print('Try again!')
Related
Beginner here. I am making a simple hangman game that can take up to 6 wrong guesses from the player. As long as they guess right, they can continue playing as many turns as necessary. There is no end behavior, I am just working on getting the input and having the program respond to it properly. My code below:
word_list = ["apple", "hello", "world", "computer"]
def choose_word():
return (random.choice(word_list))
def get_guess():
input("Give me a letter: ")
word = choose_word()
letters_used = list(word)
guess = get_guess()
counter = 0
while counter < 5:
if guess in letters_used:
print("Correct.")
get_guess()
else:
print("wrong")
counter += 1
get_guess()
My train of thought was that by taking the word the computer chose and making it into a list the program could then look at each item in said list and compare it to the input the user gave.
When I run it, it gets input, but it always says wrong, so I am guessing the problem must be in the if statement nested in the while loop.
I have looked at several other hangman games, but I don't see anything similar to what I'm trying to do, or maybe the code is similar but I'm not advanced enough to understand it.
My question is: is there a way to get Python to look at each item inside a list, compare it to a given input, and return a response (be it True/False, etc)?
in is the correct solution, you were just never giving it valid data to check for. You didn't return from get_guess, so it always returns None (thus, guess was always None and None was never in the list). Similarly, you didn't assign to guess on subsequent calls, so even if you had returned a value, guess wouldn't change (it would ask for more guesses, but the input would be discarded and it would always perform the test with the original value). Change the code to (lines with meaningful changes commented):
word_list = ["apple", "hello", "world", "computer"]
def choose_word():
return random.choice(word_list)
def get_guess():
return input("Give me a letter: ") # Must return new guess to caller
word = choose_word()
letters_used = list(word)
guess = get_guess()
counter = 0
while counter < 5:
if guess in letters_used:
print("Correct.")
guess = get_guess() # Must store new guess
else:
print("wrong")
counter += 1
guess = get_guess() # Must store new guess
I am trying to make a sort of quiz game to memorise cocktail specs.
I created a dictionary called "cocktails" and inside of it there are keys as cocktail names (Negroni, Aperol Spritz) and as value there is another dictionary for each cocktail with "spirits" and "dose" keys with lists of values. I coded this and it works but I was wondering if there was a better way to do it since I want to add lots more cocktails.
I am looking for a loop that "loops" through every value inside of the list when the answer is correct instead of me having to type in manually the value everytime with the if/ else statements.
Basically I want to loop through those two automatically if the answer is correct:
cocktails["negroni"]["spirits"][0] and
cocktails["negroni"]["ml"][0]
so the [0] should become 1 and then [2] in both of the lines every time the loop continues.
I hope I explained it clearly. Ps: I'm very new to programming :)
This is the code I'm working with:
code
cocktails = {
"negroni": {
"spirits": ["gin", "vermouth", "campari"],
"ml": [25, 25, 25],
},
"aperol_spritz": {
"spirits": ["aperol", "prosecco", "soda"],
"ml": [50, 50, "top"]
}
}
cocktail = "Negroni"
print(cocktail)
stop_quiz = True
while stop_quiz:
guess = int(input(cocktails["negroni"]["spirits"][0] + ": "))
if guess != cocktails["negroni"]["ml"][0]:
continue
else:
guess = int(input(cocktails["negroni"]["spirits"][1] + ": "))
if guess != cocktails["negroni"]["ml"][1]:
continue
else:
guess = int(input(cocktails["negroni"]["spirits"][2] + ": "))
if guess != cocktails["negroni"]["ml"][2]:
continue
else:
print("You know how to make a " + cocktail + "!")
answer = input("Do you want to play again? ")
if answer == "yes":
continue
elif answer == "no":
print("See you soon!")
stop_quiz = False
There are multiple options to get what you want, I would advice to take a look at classes to get a more object oriented approach. With that said, let's do it without classes!
Note: I also made some suggestions to your code to make it slightly simpler and adhere to the variable naming.
cocktails = {
"negroni": {
"spirits": ["gin", "vermouth", "campari"],
"ml": [25, 25, 25],
},
"aperol_spritz": {
"spirits": ["aperol", "prosecco", "soda"],
"ml": [50, 50, "top"]
}
}
Game:
cocktail = 'negroni'
print(cocktail)
stop_quiz = True
while stop_quiz:
for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
guess = int(input(f"{spirit}: "))
while guess != amount:
print("You are wrong :( , try again!")
guess = int(input(f"{spirit}: "))
print("You know how to make a " + cocktail + "!")
answer = input("Do you want to play again? ")
if answer == "yes":
continue
elif answer == "no":
print("See you soon!")
stop_quiz = False
Explanation
We make use of the following 2 things:
Pythons built in zip
A kind of do while loop.
The zip iterator creates a loop that contains your spirit and answer:
for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
Now you can iterate over all the different spirits, and you already have the right answers to compare with.
In Python there is no such thing as a do while loop by default. But we can simulate the behavior of asking something until we get what we want. We first ask for an input amount, and if this is not what we want we ask again (and again ...).
guess = int(input(f"{spirit}: "))
while guess != amount:
print("You are wrong :( , try again!")
guess = int(input(f"{spirit}: "))
When the player successfully guesses all the spirits amounts you will get the end message and prompted to play again.
Improvements
Now there are a few things that could be changed to improve the code:
the value stop_quiz is True, but it makes more sense to make it False, and check the opposite condition in the while loop. Or you can change the name to for example running.
At the end you prompt a yes and no question, but you continue the yes question if this is True. So why check for it at all? Also there is no else statement, so you really only have to check for the no value.
cocktail = 'negroni' # same as list(cocktails)[0]
print(cocktail)
running = True
while running:
for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
guess = int(input(f"{spirit}: "))
while guess != amount:
print("You are wrong :( , try again!")
guess = int(input(f"{spirit}: "))
print("You know how to make a " + cocktail + "!")
answer = input("Do you want to play again? ")
if answer == 'no':
print("See you soon!")
running = False
I'm trying to make a game like Mastermind in Python but by using numbers [1-9] instead of colours. The game needs to be a little complex however and that is where I am struggling. I want to be able to randomly generate a password of 5 digits between [0-9] and make the user have 10 tries to get it right. If they guess a number correctly, I want to tell them where it is in their list and ask them to keep going as well. So far, I have this:
import random
random_password = [random.randint(0,9) for i in range (5)]
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess != random_password :
print ("Guess again ")
#Here I am trying to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
elif guess
else print ("Sorry, you lose :( ")
if guess == random_password :
print ("Congrats, you win! ")
Any help is appreciated overflow bros, I am lost. I know that I need it to access items from a list. Would using a function like append work?
EDIT: This is my new code. Sorta works however my output is now showing it is wrong even when I guess the number correctly. It wants me to input with '' and , to separate the list but I shouldn't have to have the user do that to make the game function.
import random
random_password = [str (random.randint(0,9)) for i in range (5)]
for counter in range (10):
guess = input(str ("Crack the Mastermind code ") )
if guess != random_password :
print ("Guess again ")
#Here I am tryin to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
for i in random_password:
if(i in guess):
print (i)
if guess == random_password :
print ("Congrats, you win! ")
else :
print ("Sorry, you lose :( the correct answer was.... ")
print (random_password)
One way to do it quickly is to create a small function that will check if any of your string answer (from input) match with any characters of the password list
Also I change the order of your condition statement to make it more clear and efficient.
Finally I change your random_password from LIST to STRING because then you will be able to do guess == random_password properly.
Hope it helps!
PS:
IF you use Python2.X you should change input to raw_input (to get string value) else if you use Python3.X just keep it this way
import random
def any_digits(guess,password):
for character in guess:
if character in password:
return True
return False
random_password = ''.join([str(elem) for elem in [random.randint(0,9) for i in range (5)]])
print(random_password)
print(type(random_password))
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess == random_password :
print ("Congrats you win! ")
elif any_digits(guess, random_password):
print ("Some numbers are correct! ")
else:
print ("Guess again ")
print("No more chances, you lose...")
print("The code was ", random_password)
Very new to python and have been, as an exercise, doing a text-based version of a board game (I'm an avid board gamer).
There are obviously lots of places for the user to input something, and naturally I need to evaluate those inputs and make sure they are valid.
I learned about using a True/False check and for loops from this site (thanks!) and now that I've done them so much I was wondering if there was a better way - they get a little crazy if they are nested and I want to to my best to adhere to those Zen-like Python rules.
Here is what I mean, in a simple example, using generic code so it makes sense (not all of you may know the rules of this board game!)
The goal is to make sure the code loops until a color or "none" is given. I know this accomplishes that, i'm just wondering if there is a more streamlined way that I haven't learned yet.
colors = ["red", "green", "white", "blue", "yellow"]
for color in colors:
print(f"You can choose {color}.")
choice = input("Which color would you choose? (input a color or 'none' : ")
checker = False
while not checker:
if choice not in colors:
choice = input("That's not one of your options. Choose again: ")
elif choice == "none":
print("You don't want a color. That's fine.")
checker = True
else:
print("You chose {color}! Have fun!")
checker = True
You could define a generic function if you find yourself repeating the same things
def prompt_for_valid_input(options):
while True:
print(f"You can choose one of {options}.")
choice = input("Which would you choose? (or 'none' : ")
if choice == "none" and "none" not in options:
print("You didn't pick anything. That's fine.")
return None
elif choice in options:
return choice
else:
print("That's not one of your options. Choose again. ")
colors = ["red", "green", "white", "blue", "yellow"]
color = prompt_for_valid_input(colors)
if color is not None:
print(f"You chose {color}! Have fun!")
numbers = [1, 10, 100]
num = prompt_for_valid_input(numbers)
if num is not None:
print(f"You chose {num}! Have fun!")
So "without a while/for loop", not really. Without a sentinel variable, yes, if the conditions are simple enough.
you can abstract it out to a generic validated input method
def validated_input(prompt,validation_method,error_message):
while True:
result = input(prompt)
if validation_method(result):
return result
print(error_message)
choices = ['red','green','blue','none']
validator = lambda test:test.lower().strip() in choices
prompt = "Enter A Color(one of Red, Green, Blue, or None):"
error_message = "Please enter a valid color or None!"
print(validated_input(prompt,validator,error_message))
its arguable whether this is "better"
Usually how you wrote your code is considered pretty "normal" and straightforward which is good. The issue is that you would want the looping part of your code to repeat till it has met its expectation. So a conditional looping event is necessary. If you really want you can simplify it a little by making a break statement for example:
x = 0
while True:
if x == 12:
break;
else:
x = x + 1
print(x)
This will create a infinite loop until the condition you are looking for is met and then it will break out of the loop. Make sure you have your escape condition though.
im trying to get users to input different strings for Fav_show that can trigger the correct show. i've tried Fav_show = ("game of thrones", "GOT") and Fav_show = ("game of thrones" or "GOT") but my script makes guess != Fav_show if i enter game of thrones/GOT, how would I got about making guess = Fav_show for multiple answers.
Fav_show = ("game of thrones")
guess = ""
guess_count = 0
guess_limit = 0
guess_a_show = False
if raw_input == "whats your favourite tv show":
guess_a_show = input("you have to take a guess, okay? ")
if guess_a_show == "okay":
print("take a guess, you have 5 chances ")
while guess != Fav_show and guess_count < 1:
Sorry I'm new to python, and I've tried looking around for about 30-45 mins, but maybe I'm looking at the wrong places
You could create a list with possible answers of the user:
got_list = ['got', 'Game of Thrones', 'GOT']
Then:
while guess not in got_list and guess_cout < 1
Instead of iterating through the whole list manually and doing the comparison with for x in list... you could also use the in operator:
if x in list return True or even better just return the in comparison straight up return x in list, just keep in mind that for string comparison letter casing does come into play and you should either use 'string'.upper()' or 'string'.lower().