1. 程式人生 > >python學習小Demo

python學習小Demo

練習一 :拆數字遊戲

#coding=utf-8
import random

game_count=0
all_counts=[]
while True:
    game_count+=1
    guess_count =0
    answer=random.randint(0,99)
    while True:
        guess=int(input("猜個數字(0-99):"))
        guess_count +=1
        if guess ==answer:
            print ("恭喜你拆對了")
            print
("你一共拆了"+str(guess_count)+"次") all_counts.append(guess_count) break elif guess>answer: print ("拆得太大了") else: print("拆得太小了") #必須用raw_input,如果用input,輸入時需要打雙引號才能識別,識別不了string onemore=raw_input("再來一次可好(Y/N)?") if onemore !="Y"
and onemore !="y": print onemore print ("捨不得你,下次再來哈") print ("您的成績如下:") print (all_counts) print ("平均拆中次數"+str(sum(all_counts)/float(len(all_counts)))) break else: print("馬上再來")

練習二:數單詞

原始檔:ancesor.txt

janet winnie
winnie poul
sam dida
helen janet
helen jack
jack salon
salon rose
rose tom
jack nicole
sam flitter
janet sam
sam sisi

#codin=utf-8
import re

fb=open("D:/resource/ancesor.txt","r")
article=fb.read()
#此行可以設定flitter
new_article=article
#將資料換行劃分,然後用空格連線起來(“ ”。join()),然後去首尾空格,然後分解
words=" ".join(new_article.split("\n")).strip().split(" ")
#建立一個字典
word_counts={}
#實現單詞的全部變大寫
for word in words:
    if word.upper() in word_counts:
        word_counts[word.upper()]=word_counts[word.upper()]+1
    else:
        word_counts[word.upper()]=1
key_list=list(word_counts.keys())
key_list.sort()
for key in key_list:
    #對計數大於0的進行列印
    if word_counts[key]>0:
        print("{}:{}".format(key,word_counts[key]))