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().
Related
This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9. I am still trying to master thought & flow as well as loops, and I hit a roadblock:
import random
Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
def number_game():
if guess == random_num:
print(f"You guessed right, the number is confirmed to be {random_num}.")
else:
print(f"You guessed the wrong number. Try again.\n")
number_game()
I called the function and ran the code... everything appears to be working except I really can't figure out how to keep the game going in a loop until the player gets the right number out of 1-9...and end it when I need to. I tried searching all my resources and am quite stuck on this beginner practice coding. Any help is appreciated.
What I wrote and tried is above... googling and stackoverflow just confused me more.
Honestly, there are many ways to do what you want. But using your code as base, this is one possible solution.
import random
Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
def number_game():
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
if guess == random_num:
print(f"You guessed right, the number is confirmed to be {random_num}.")
return True
else:
print(f"You guessed the wrong number. Try again.\n")
return False
while True:
guessed_right = number_game()
if guessed_right:
quit()
else:
number_game()
while True:
number_game()
Replace the last line of your script with this!
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)
This question already has an answer here:
Python "if" statement not working
(1 answer)
Closed 4 years ago.
I'm learning Python for fun at the moment, and it went all well until now. I'm trying to extend the "Guess the Word"-Game, for example being able to let the Player choose a Word by himself (when 2 People play, 1 chooses the Word, the other guesses) I bet that my Mistake is obvious to me as soon as you point it out, but I'm gonna ask anyway. Well, here is the Code. I put in the entire Program, even tough only the top part should matter. I just put in the rest because it isn't much and maybe you guys can understand it better then.
print("Do you wish to set the Word yourself, or let the program choose?")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == 1:
Keyword = input("Type in the Word you want to use!")
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter!")
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')
My problem is, I wanna add the Function to be able to choose if you want to set a Word yourself, or use the word the Program has, defined as "Keyword". But no matter what I input, it always starts with "Guess a Letter" instead of skipping down to where the program sets the Keyword. Thank you in advance for your answers! :)
There's 2 issues with your code.
You put the entire block of code into the else statement. This means that if the if user_input == 1: block ever executed, you would only ask your user for a word and then the program would end because the else statement would be skipped.
You are using if user_input == 1: as your check and this will never be true because user inputs are always read in as strings. A string 1 will never equal the integer 1. This is why your program always skips to the else statement. You need to do if int(user_input) == 1:
Whenever you collect a user's input using the input function, it is a string, not int. this means you will have to either parse the value into an int or evaluate it with a string.
option 1: parsing to int:
user_input = int(input("1 for own Input - 0 for Program-Input"))
option 2: evaluating with string:
if user_input == "1":
input returns a string not a integer so it can never be equal to 1 instead it will be equal to "1".
Plus the code for the user guessing only runs when the program chooses the word so it needs to be unindented.
As a side note your code currently registered capital letters as being different from lower case, you can fix this by putting a .lower() after each input which will turn all capital letters into lowercase.
print("Do you wish to set the Word yourself, or let the program choose?: ")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == "1":
Keyword = input("Type in the Word you want to use: ").lower()
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter: ").lower()
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')
def main():
#word = input("Word to guess for player 2:")
word = ['h','e','l','l','o']
word2 = "hello"
#make a list of _ the same length as the word
display =[]
for i in range (0,len(word)):
display.append("_")
chances = int(input("Number of chances to guess word:"))
if len(word)== 11:
print ("Your word is too long. It has to be 10 charecters or less")
else:
word = word
if chances < len(word):
answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word)))
if answer == "no":
chances= int(input("Number of chances:"))
else:
chances = chances
("Ok then lets continue with the game")
print ("Player 2, you have {0} chances to guess the word.". format (chances))
won = False
underscore = False
while chances > 0 and won == False and underscore == False:
guess = input("Enter your guess: ")
gC=False
for i in range (0,len(word)):
if guess == word[i]:
gC=True
display[i]=guess
if not gC:
chances = chances - 1
display2 = ""
for i in display:
display2 = display2 + i + " "
For some reason the code doesn't work when I state my while loop as the game continues to go on until the user runs out of guess'. Does anybody have any suggestions as to how I can fix this?
You never set won to True when the user wins the game by guessing all the letters.
This is not an answer to your original question, instead more of a code-review, but maybe you'll find it useful.
word = list('hello') # replaces manual splitting of string into letters
display = [ '_' ] * len(word) # replaces build-up using for-loop
chances = input("Number ... ") # already returns int if the user enters an int
# but will evaluate any valid python expression the
# user enters; this is a security risk as what
# ever is done this way will be done using your
# permissions
chances = int(raw_input("Number ...")) # probably what you wanted
...
else:
word = word # does nothing. remove this line and the "else:" above
chances -= 1 # replaces 'chances = chances - 1' and does the same
display2 = ' '.join(display) # replaces the for-loop to build display2
Furthermore I suggest to use better names. Variables like display2 or gC aren't very helpful in this context. In professional programming you always have to keep in mind that you are writing your code (also or even mainly) for the next developer who has to maintain it. So make it readable and understandable. Choose names like displayString or guessedCorrectly instead.