《Python核心編程(第二版)》練習題(自己寫的)

來源:互聯網
上載者:User

如果路過的朋友們發現錯誤或有意見,歡迎指正和提出。當然,對一些題目沒頭緒時,會參考一下前輩們的代碼,在此表示感謝。





第5章 5-4

 
#!/usr/bin/env python#coding:utf-8year = int(raw_input('請輸入年份:'))if (year % 4==0 and year % 100!=0) or (year % 400==0) :    print '%d是閏年' % yearelse :    print '%d不是閏年' % year


 
 
5-5 
 
#!/usr/bin/env python#coding:utf-8dollar = float(raw_input('請輸入美元數目:'))cent = int(dollar * 100)a = cent/25cent = cent%25if cent>0:    b = cent/10cent = cent%10if cent>0:    c = cent/5cent = cent%5if cent >0:    d = cent#先判斷變數是否存在,再進行相應輸出,避免出現NameErrorif locals().has_key('a'):    print '\n%d枚25美分' % aif locals().has_key('b'):    print '\n%d枚10美分' % bif locals().has_key('c'):    print '\n%d枚5美分' % cif locals().has_key('d'):    print '\n%d枚1美分' % d
 
 


 
 
 
5-6 
 
#!/usr/bin/env python#coding:utf-8string = raw_input('請輸入運算式:')if len(string.split('+'))==2 :    temp = string.split('+')    print float(temp[0]) + float(temp[1])if len(string.split('-'))==2 :    temp = string.split('-')    print float(temp[0]) - float(temp[1])if len(string.split('*'))==2 :    temp = string.split('*')    print float(temp[0]) * float(temp[1])if len(string.split('/'))==2 :    temp = string.split('/')    print float(temp[0]) / float(temp[1])if len(string.split('%'))==2 :    temp = string.split('%')    print float(temp[0]) % float(temp[1])if len(string.split('**'))==2 :    temp = string.split('**')    print float(temp[0]) ** float(temp[1])
 
 


5-15
 
#!/usr/bin/env python#coding:utf-8num1 = int(raw_input('請輸入第一個數:'))num2 = int(raw_input('請輸入第二個數:'))if num1 > num2 :    temp = num2else :    temp = num1while temp > 0:    if num1 % temp==0 and num2 % temp == 0 :        yue = temp        break    temp -= 1bei = num1*num2/yueprint yue,'  ',bei


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.