Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

Game of Chance in Python 3.x?

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

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...