Python學習:基礎(5)任意**m進位到n進位**的轉換__Python

來源:互聯網
上載者:User
[0]內建的那些函數,可以通過help或者https://docs.python.org/3/library/進行查閱. [1]對進位的轉換,10進位整數到2,8,16,bin(),oct(),hex()就可以轉換到相應的進位了. [2]各個進位到10進位的轉換,int(obxxxxx),int(ox…..)或者int(‘xxxxxxxxxx’,2),int(‘xxxxxxxx’,8) 以下代碼作為練習求解任意m進位到n進位的轉換,作為一種良好的習慣,我們應該檢查所有可能的輸入,m,n必須是整數,要處理的數也應該是整數(但是不一定是正數),m如果不是數,調用int將會出錯,如何判斷一個字串是否是數?這裡需要用到Regex,以後再處理.
m = int(input('please input the orginal number system'))n = int(input('please input the objective number system'))m_str = input('the orginal integer ')if(float(m_str)==int(float(m_str))):        m_number = int(m_str,m)#get the numeric value of m        symbol = ''        if(m_number<0):#figure out the final symbol                m_number = abs(m_number)#get positive value                symbol = '-'        if(n == 10):# m convert to 10                print(symbol+str(m_number))        else:#10 convert to n                ans = ''                while(m_number):                        ans = str(m_number%n) + ans#doing the mod                        m_number = m_number//n#warning!!: using // not /                print(symbol+ans)#print the answerelse:        print('input is not integer')

====================================================================================== 學會定義函數:def:,傳回值(多個傳回值實際上是一個tuple),參數檢查。求一元二次方程解的代碼.

import mathdef quadratic(a, b, c):    if(not(isinstance(a,(int,float))and isinstance(b,(int,float)) and isinstance(c,(int,float)))):#check the argument type        print('the a,b,c is typerror')        return    if(b*b>=4*a*c):        r = math.sqrt(b*b-4*a*c)        return (-b+r)/(2*a),(-b-r)/(2*a)    else:        print('there is not real root')        returnprint(quadratic(2, 3, 1))print(quadratic(1, 3, -4))print(quadratic(1, -2, 1))print(quadratic(5, 1, 3))print(quadratic('1', 3, -4))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.