[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))