我正在尝试用Python创建一个 Heads or Tails 程序。我是一个新手,我刚刚进入Python。我试图实现的是让程序选择 Heads 或 Tails 而我不知道它(是的,import random
等)并且我想猜测时只有一次尝试。这是我迄今取得的成就,但它并不是我所期待的。有什么想法吗?我已经尝试实现我在Python网站上找到的不同随机参数,但它们不起作用(例如整数randint
)...谢谢!
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = "Heads" # For Debugging purposes to check if the program works
notCorrectAnswer = "Tails" # To eliminate the possibility of not being either tails or heads in case of mistaken answer
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"
答案 0 :(得分:4)
你应该尝试:
import random
ch = random.choice(["Heads","Tails"])
将变量ch
放入“Heads”或“Tails”。尝试从中做点什么。
答案 1 :(得分:0)
要让整个事情继续下去,直到被用户退出,并包括@ Baruchel的答案:
import random
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
cont = 1 #To force the game to run for one round without user input
while(cont == 1): #cont is used to take user choice, whether to run it again or not
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = random.choice(["Heads","Tails"])
if ourAnswer == "Heads":
notCorrectAnswer = "Tails"
else:
notCorrectAnswer = "Heads"
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"
cont = input("Do you want to continue? Press 1 if yes, press 0 if no.: ") #Take user choice on whether to run it again or not
while (cont != 0 and cont != 1): # If user puts in a different number (neither 1 or 0), make them enter until they put a right choice
cont = input("Please try again. Press 1 if yes, press 0 if no.: ")