Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this problem in my python code which is a coinflip game, the problem is that when It asks, "Heads or Tails?" and I just say 1 or Heads(same for 2 and Tails) without quotation marks and with quotation marks, it does not give me an answer that I am looking for.

I've Tried using quotation marks in my answer which didn't seem to work either.

import random

money = 100

#Write your game of chance functions here
def coin_flip(choice, bet):
   choice = input("Heads or Tails?")
   coinnum = random.randint(1, 2)
   if coinnum == 1:
      return 1
   elif coinnum == 2:
      return 2
   win = bet*2
   if choice == "Heads" or "1":
       return 1
   elif choice == "Tails" or "2":
      return 2
   if choice == coinnum:
      print("Well done! You have won " + str(win) + " Dollars!")
   elif choice != coinnum:
      print("Sorry, you lost " + str(bet) + " Dollars!")

coin_flip("Heads", 100)

The expected output was either "Well done! You have won 200 Dollars!" or "Sorry, you lost 100 Dollars!"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

The first thing to note here is that your usage of return seems to be wrong. Please look up tutorials about how to write a function and how to use return.

I think this is what you were trying to do:

import random

money = 100

#Write your game of chance functions here
def coin_flip(choice, bet):
   choice = input("Heads or Tails? ")
   coinnum = random.randint(1, 2)
   win = bet*2

   if choice == "Heads" or choice == "1":
      choicenum = 1
   elif choice == "Tails" or choice == "2":
      choicenum = 2
   else:
      raise ValueError("Invalid choice: " + choice)

   if choicenum == coinnum:
      print("Well done! You have won " + str(win) + " Dollars!")
   else:
      print("Sorry, you lost " + str(bet) + " Dollars!")

coin_flip("Heads", 100)

Now, lets go through the mistakes I found in your code:

  • return was totally out of place, I wasn't sure what you were intending here.
  • if choice == "Heads" or "1" is invalid, "1" always evaluates to true. Correct is: if choice == "Heads" or choice == "1":
  • elif choice != coinnum: is unnecessary, if it doesn't run into if choice == coinnum: a simple else: would suffice.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...