Python学习:基础(5)任意**m进制到n进制**的转换

来源:互联网 发布:党纪党规知敬畏 编辑:程序博客网 时间:2024/04/27 19:07

[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将会出错,如何判断一个字符串是否是数?这里需要用到正则表达式,以后再处理.

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