Heads or Tails in Python - python

The if and elif conditions aren't working and I am not even getting an error. The code is intended to match the users input to what the computer selects and then make a call, if the user won or lost.
import random
def flip():
return random.choice(["Heads", "Tails"])
Users_Selection = (input("Choose: Heads or Tails?"))
print("Flipping the coin. Please wait!")
print ("It a", flip())
if flip()=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif flip()=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")
All help is genuinely appreciated!

Everytime you call flip, it generates a new random output so you must store the value of flip in a variable.
c = flip()
print("It's a ", c)
if c=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif c=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")

Related

how to make it that it does not repeat?

I know that a "not repeat with random from a list" is probably seen as a info you can find, but as someone who does not have a lot of knowledge of python yet, i cannot seem to understand those answers or they do not work for my problem. So I hope any of you are able to help.
as my first small project I am building a truth or dare program, and now I am at the point that I want to make it that the questions cannot be asked twice, and that if the truth questions are all done it prints that announcement, and I want the same for my dare questions.
here is my program so far, sorry if it is messy:
import random
import time
truth = ["If you could be invisible, what is the first thing you would do?",
"What is a secret you kept from your parents?",
"What is the most embarrassing music you listen to?",
"What is one thing you wish you could change about yourself?",
"Who is your secret crush?"]
dare = ["Do a free-style rap for the next minute",
"Let another person post a status on your behalf.",
"Hand over your phone to another player who can send a single text saying anything they want to anyone they want.",
"Let the other players go through your phone for one minute.",
"Smell another player's armpit."]
print("Hello, and welcome to my truth or dare show, just type truth or type dare to get a question!")
lives = 3
while lives > 0:
choice = input("truth or dare?: ").lower()
time.sleep(0.5)
if choice == "truth":
print(random.choice(truth))
time.sleep(0.5)
while True:
answer_truth = input("want to answer? type yes or no: ").lower()
if answer_truth == "yes":
input("> ").lower()
print("good answer")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif answer_truth == "no":
print("you lost a life!")
time.sleep(1)
lives -= 1
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
elif choice == "dare":
print(random.choice(dare))
time.sleep(0.5)
while True:
do_dare = input(f"did you do the dare? type yes or no: ").lower()
if do_dare == "yes":
print("well done!")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif do_dare == "no":
print("you lost a life!")
lives -= 1
time.sleep(0.5)
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
else:
print("that is not an option")
time.sleep(0.5)
print("GAME OVER!")
This should work:
choice = random.choice(truth)
time.sleep(0.5)
# inside the loop
truth.remove(choice)
if len(truth) == 0:
print("all questions are done")
do the same for dare
You probably want a construct like this:
from random import shuffle
ls = ["a", "b", "c"]
shuffle(ls)
lives = 3
while lives > 0 and ls:
current_question = ls.pop()
... # Rest of your code
So you want to select a random option, but then no longer have it in the set that you select random things from in the future.
If you imagine it physically, you have a jar list that has papers item's in it and you want to take them out at random. Obviously, any that you take out can not be taken out again.
We can accomplish this by removing the item from the list after it's 'picked'
To answer your question about having it let them know there are no more truths or no more dares, we can simply add a conditional to the whole truth segment and one to the whole dare segment as well, then further, if both run out, end the game.
while lives > 0 and (len(truth)>0 or len(dare>0)):
# Rest of the program
if choice == "truth":
if len(truth) > 0:
# Code
else:
print("there are no more truths (existential crisis), maybe try a dare instead")
elif choice == "dare":
if len(dare)>0:
# Code
else:
print("there are no more dares *sigh of releif*, maybe try a truth instead")

What am I doing wrong in this game? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to take up my first scripting language: python. I'm currently making a little game where you guess a predetermined number from 1-100. It also tells you if the right answer is bigger or smaller. Currently my code always returns that the right number is smaller, while it is not.
edit: thanks a lot for helping me!
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
print(rightnumber)
gok = int(input("type your guess here and press enter"))
def compareguess():
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
compareguess()
def guessAgain():
int(input("try again. type your guess and press enter."))
compareguess()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
You can pass gok as a parameter to avoid global variables.
The problem is:
When you take the input again: int(input("try again. type your guess and press enter.")), you don't assign the value to anything. So gok remains the same and it is always bigger or smaller
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
gok = int(input("type your guess here and press enter"))
def compareguess(gok):
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
compareguess(gok)
def guessAgain():
gok=int(input("try again. type your guess and press enter."))
compareguess(gok)
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
Also, don't use recursion. Instead, use a while loop. A shortened code without recursion:
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
while True:
gok = int(input("type your guess here and press enter"))
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
break
else:
print("wrong! the right number is bigger.")
The problem is with the scope of the parameters. The first guess is stored globaly in gok. Whether it is smaller or bigger, compareguess will print a correct message.
But when you call guessAgain you don't save the new guess anywhere, so the value of gok is still the old one. Even if you would save it, the scope wouldn't be correct so you won't see the new value in compareguess.
So a possible solution would be to pass gok as a parameter to compareguess (I also added rightnumber as a parameter).
def compareguess(gok, rightnumber):
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
And would now run -
while rightnumber != gok:
gok=int(input("try again. type your guess and press enter."))
compareguess(gok, rightnumber)
try this code
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
print(rightnumber)
gok = int(input("type your guess here and press enter"))
def compareguess(gok):
if gok == rightnumber:
print("WOW! you guessed right!")
elif gok > rightnumber:
print("wrong! the right number is smaller :)")
else:
print("wrong! the right number is bigger.")
compareguess(gok)
def guessAgain():
gok = int(input("try again. type your guess and press enter."))
compareguess(gok)
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
your compareguess functiuon
def compareguess():
if gok < rightnumber:
print("wrong! the right number is smaller :) ")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger. ")
your guessAgain function
def guessAgain():
global gok
gok = int(input("try again. type your guess and press enter."))
compareguess()
if rightnumber == gok:
print("that was it! you won!")
else:
guessAgain()
You could use this.
It keeps asking until you type the correct number.
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = random.randint(1, 100)
print(rightnumber)
def guess():
gok = int(input("type your guess here and press enter: "))
if gok > rightnumber:
print("wrong! the right number is smaller :)")
guess()
elif gok == rightnumber:
print("WOW! you guessed right!")
print("that was it! you won!")
else:
print("wrong! the right number is bigger.")
guess()
guess()

How do I correctly use isinstance() in my random number guessing game or is another function needed?

I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break

not restarting for program and input integer not working

I'm trying to develop a program wherein at the finish of the game the user will input "Yes" to make the game restart, while if the user inputed "Not" the game will end. For my tries, I can't seem to figure out how to make the program work. I'm quite unsure if a double while True is possible. Also, it seems like when I enter an integer the game suddenly doesn't work but when I input an invalidoutpit the message "Error, the inputed value is invalid, try again" seems to work fine. In need of help, Thank You!!
import random
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
while True:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
else:
guess1=int(guess[0])
guess2=int(guess[1])
guess3=int(guess[2])
guess4=int(guess[3])
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
answer=input("Would you like to play again? (Yes or No) ")
if answer==Yes:
print ('Yay')
continue
else:
print ('Goodbye!')
break
Wrap your game in a function eg:
import sys
def game():
#game code goes here#
Then at the end, call the function to restart the game.
if answer=='Yes': # You forgot to add single/double inverted comma's around Yes
print ('Yay')
game() # calls function game(), hence restarts the game
else:
print ('Goodbye!')
sys.exit(0) # end game
try this
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
gueses=[]
while len(gueses)<=3:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
gueses.append(guess)
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
guess1=gueses[0]
guess2=gueses[1]
guess3=gueses[2]
guess4=gueses[3]
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
if P1=="x" and P2=="x" and P3=="x" and P4=="x":
print("you won")
else:
print("YOUE LOSE")
print("TRUE ANSWERS", A1,A2,A3,A4)
print("YOUR ANSWER", gueses)
game()
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print ('Yay')
game()
else:
print ('Goodbye!')
The previous answers are good starts, but lacking some other important issues. I would, as the others stated, start by wrapping your game code in a function and having it called recursively. There are other issues in the guess=int(input("\nTry and Guess the Numbers :). ")). This takes one integer as the input, not an array of integers. The simplest solution is to turn this into 4 separate prompts, one for each guess. I would also narrow the scope of your error test. I've included working code, but I would read through it and make sure you understand the logic and call flow.
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
if P1=="O" or P2=="O" or P3=="O" or P4=="O":
print("Here is your Clue :) :")
print(P1,P2,P3,P4)
try:
guess1=int(input("\nGuess 1 :). "))
guess2=int(input("\nGuess 2 :). "))
guess3=int(input("\nGuess 3 :). "))
guess4=int(input("\nGuess 4 :). "))
except ValueError:
print("Invalid Input")
continue
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
break
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print('Yay')
game()
else:
print('Goodbye!')
game()

Python Int object not callable

Please help! I don't understand the error here. Why do I get an error saying: "'int' object is not callable" when I type a number other than 0, 1 or 2? Instead, it's suppose to print "You have entered an incorrect number, please try again" and go back to asking the question.
Second Question: Also how can I change the code in a way that even if I type letter characters, it won't give me the Value Error and continue re-asking the question? Thank you!
def player_action():
player_action = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
if player_action == 0:
print ("Thank You, you chose to stay")
if player_action == 1:
print ("Thank You, you chose to go up")
if player_action == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
player_action()
player_action()
You should change the variable name as #Pedro Lobito suggest, use a while loop as #Craig suggested, and you can also include the try...except statement, but not the way #polarisfox64 done it as he had placed it in the wrong location.
Here's the complete version for your reference:
def player_action():
while True:
try:
user_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
except ValueError:
print('not a number')
continue
if user_input == 0:
print ("Thank You, you chose to stay")
if user_input == 1:
print ("Thank You, you chose to go up")
if user_input == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
continue
break
player_action()
The first answer to your question has been answered by Pedro, but as for the second answer, a try except statement should solve this:
EDIT: Yeah sorry, I messed it up a little... There are better answers but I thought I should take the time to fix this
def player_action():
try:
player_action_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
except ValueError:
print("Non valid value") # or somehting akin
player_action()
if player_action_input == 0:
print ("Thank You, you chose to stay")
elif player_action_input == 1:
print ("Thank You, you chose to go up")
elif player_action_input == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
player_action()
player_action()
Just change the variable name player_action to a diff name of the function, i.e.:
def player_action():
user_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
if user_input == 0:
print ("Thank You, you chose to stay")
elif user_input == 1:
print ("Thank You, you chose to go up")
elif user_input == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
player_action()
player_action()

Categories