Python学习:基础(5)任意**m进制到n进制**的转换
2016-02-29 16:46
701 查看
[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 answer else: print('input is not integer')
======================================================================================
学会定义函数:def:,返回值(多个返回值实际上是一个tuple),参数检查。求一元二次方程解的代码.
import math def 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') return print(quadratic(2, 3, 1)) print(quadratic(1, 3, -4)) print(quadratic(1, -2, 1)) print(quadratic(5, 1, 3)) print(quadratic('1', 3, -4))
相关文章推荐
- java or spring +jython +python (Error:python.home,Determine if the following attributes are correct:)
- python——文件读写
- python——文件读写
- python下划线变量的含义
- Python 异常处理
- 为树莓派增加时钟模块ds3231
- 很好的python 学习网站
- import,reload,__import__在python中的区别
- 【python】编程语言入门经典100例--15
- 利用Python,四步掌握机器学习
- python多进程不同实现方法的异同点
- 使用pyenv和virtualenv搭建python虚拟环境
- MySQL分库分表python实现分库(7th)
- python群发QQ邮件研究
- 2、发现群组 Python代码
- python中input和raw_input用法及区别
- 【ED距离】使用Python求编辑距离
- Python爬虫(二):整站爬虫与Web挖掘
- Python基础
- Python爬虫开发(一):零基础入门