1. 程式人生 > >Python 石頭剪刀布,小遊戲

Python 石頭剪刀布,小遊戲

老師佈置了一個石頭剪刀布的作業,要視覺化,哎,還是先用程式碼實現再說視覺化的事吧。。哈哈。。

環境:window7,Python 3.5

程式碼:

#coding=utf-8
import random

exit_flag = False #設定flag用於break跳出兩層迴圈,或者自定義異常也行,try:, except。
dic = {}
dic[0] = '剪刀'
dic[1] = '石頭'
dic[2] = '布'

while True:
    humanStr = input("請輸入[0:剪刀 1:石頭 2:布]  ")
    if humanStr.isdigit() and
(int(humanStr) in [0,1,2]): #如果輸入的是數字,並且在0,1,2中 human = int(humanStr) windows = random.randint(0, 2) print ("你出的是%s,電腦出的是%s" % (dic[human],dic[windows])) if (human == 0 and windows == 2) or (human == 1 and windows == 0) or (human == 2 and windows == 1): print("祝賀你,你贏了!"
) oncemore = input("你想再來一局嗎? y(Y) or n(N) ") elif human == windows: print("平局") oncemore = input("你想再來一局嗎? y(Y) or n(N) ") else: print("不好意思,你輸了") oncemore = input("你想再來一局嗎? y(Y) or n(N) ") while True: if
oncemore == 'y' or oncemore == 'Y': break elif oncemore == 'n' or oncemore == 'N': exit_flag = True break #跳出內層迴圈,並且設定flag else: oncemore = input("你想再來一局嗎? y(Y) or n(N) ") if exit_flag == True: break #跳出層迴圈,結束程式 else: print ("請重新輸入!") pass

這裡寫圖片描述

PS:這裡想要記錄一下python2中input和raw_input的區別,以及python3中的input

對於python2:

input和raw_input都能接受字串, raw_input()將所有輸入作為字串看待,返回字串型別,而input()在對待輸入純數字時,返回數字型別(int,float),對待字串的話,輸入的字串必須使用引號引起來,表明是個字串,返回型別為字串
這裡寫圖片描述

對於python3:

將raw_input()和input()進行了整合,去除了raw_input(),僅保留了input()函式,其接受任意性輸入,將所有的輸入都預設為字串型別處理,並返回字串型別。
這裡寫圖片描述