用 while , if 再加上 random 函數就可以完成一個猜拳遊戲
#Rock , Paper , Scissors
import random
gameList=("Rock","Paper","Scissors") #產生一個剪刀 石頭 布 陣列,此陣例不會再異動任何值,所以採用 set
gameChoice=random.choice(gameList) #從 gameList 中隨機排選一個
#gameChoice=gameList[random.randint(0,2)] 也可用此方法完成
validChoice = 1 #先定義一個變數,利用它來判斷使用者的輸入是否正確
while (validChoice): # while 迴圈開始,
userChoice=input("Please enter one of following: Rock ,Paper, Scissors") #讓使用者出拳
if (userChoice in gameList): #判斷使用者的出拳是否正確,正確則異動 validChoice 的值,跳離 while
validChoice= 0
else:
print("You must enter a valid choice") # 使用者若無依規定出拳,給予提示訊息
print("I choose:" + gameChoice + ", You choose:" + userChoice ) # 輸出電腦與使用者的出拳
if (gameChoice==userChoice): # 判斷輸贏
print("Tie")
elif ((gameChoice=="Rock" and userChoice=="Paper") or
(gameChoice=="Paper" and userChoice=="Scissors") or
(gameChoice=="Scissors" and userChoice=="Rock")):
print("You win!")
else:
print("You Lose")