我想要构建一个正面和反面游戏,但是当我分配正面 -0 和反面 -1 的值时 那么即使我选择尾部并且随机函数结果出现,但它与我的不匹配。 就像如果我选择正面那么如果随机函数也选择正面那么它应该是耶你赢了但它来了相反。
import random
choice = input("Would You like to play Heads or Tails game? ").lower()
if choice == "yes":
head_or_tails = input("Choose Heads or Tails -- ").lower()
random_number = random.randint(1,2)
print(random_number)
if random_number == 1:
if head_or_tails == "heads":
print("Yay! You won , It's Heads")
if head_or_tails == 'tails':
print("Sorry the Computer won, It's Tails, Better Luck Next Time")
if random_number == 2:
if head_or_tails == "tails":
print("Yay! You won, It's Tails")
if head_or_tails == 'heads':
print("Sorry the Computer won, It's Heads, Better Luck Next Time")
if choice == "no":
print("It's Okay You can play Next Time" )
代码中的问题来自于如何为
random_number
分配值并将其与用户的选择进行比较。
这是您更正后的代码:
choice = input("Would You like to play Heads or Tails game? ").lower()
if choice == "yes":
head_or_tails = input("Choose Heads or Tails -- ").lower()
random_number = random.randint(1, 2)
if random_number == 1:
coin_result = "heads"
else:
coin_result = "tails"
print(f"The coin flip result is: {coin_result.capitalize()}")
if head_or_tails == coin_result:
print("Yay! You won!")
else:
print("Sorry, you lost. Better luck next time.")
elif choice == "no":
print("It's okay, you can play next time.")
else:
print("Please enter a valid response.")
random.randint(1, 2)
生成一个随机整数,可以是 1 或 2。根据您的 random_number
值,您可以将 heads
或 tails
分配给变量 coin_result
。