"Hello World!"似乎是所有程序员开始的第一个工程,然而Python实现它太Easy了,仅仅需要在命令行窗口print ("Hello World!")即可。所以,我们从下面这个实例来学习Python,包括数据类型,包括语法,包括思想,包括代码规范。
实例:给定一个非负十进制数n,如何将其转换成为一个二进制数?
输入:123 输出:1111011
输入:1363 输出:10101010011
输入:12 输出:1100
首先我们看一下二进制,由十进制来类比。
考虑一个十进制数,8327,那么
数字: 8 3 2 7
权值:1000 100 10 1
所以, 值为 8*1000+3*100+2*10+7*1。
同理,考察二进制数,10110110,那么
数字:1 0 1 1 0 1 1 0
权值:128 64 32 16 8 4 2 1
所以,值为128+32+16+4+2=182
通常,我们在面对问题的时候,需要分析问题,而分析问题,通常会从最简单的情况开始。所以,看一下最简单的数字的十进制和对应的二进制:
Decimal Binary
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
从上述例子中,你发现了什么规律了吗?
其中可以发现的规律有:
1、若n是偶数,则二进制数末尾数字是“0”,若n是奇数,则二进制数末尾数字是“1”。
2、如果n的二进制数可以表示为bk … b2 b1 b0,那么如果n是偶数,那么n/2的二进制数可以表示为bk … b2 b1,如果n是奇数,那么(n-1)/2的二进制数可以表示为bk … b2 b1。
如果发现了这个规律,可以很容易写出伪代码:
1. Read the number n given as input.
2. If n is even, output 0. Replace n by n/2.
3. If n is odd, output 1. Replace n by (n-1)/2.
4. If n is 0, stop. Otherwise go to Line 2.
注意,这个顺序是倒序的,也就是说先输出了最后一位。
根据此代码,可以写出版本1的代码:
n = int(input("Enter a positive integer:"))
while n > 0:
print(n % 2)
n = n // 2
然而此版本代码存在什么问题呢?首先,最重要的,是打印出来的顺序是逆序的,并且不是在一行内,这带来较大的困扰,不满足要求。所以,修改一下,产生版本2:
n = int(input("Type a nonnegative integer: "))
suffix = ""
while n > 0:
suffix = str(n % 2) + suffix
n = n // 2
print(suffix)
这个版本的代码在while循环中将产生的数字追加到前面,很好的解决了倒序的问题,但是是否还有别的问题呢?很明显,当输入为0时,输出不是二进制数字0而是空字符。如何解决这个问题呢?请看版本3:
n = int(input("Type a nonnegative integer: "))
if n < 0:
print("Please input a nonnegative integer next time. Bye!")
else:
originalN = n
suffix = ""
while n > 0:
suffix = str(n % 2) + suffix
n = n // 2
# The input n = 0 is dealt with as a special case
if suffix == "":
suffix = "0"
print("The binary equivalent of", originalN, "is", suffix)
最后,为了规范,加入作者和日期,就是最终版本4了:
# Programmer: Python那些事
# Date: April 11, 2017
n = int(input("Type a nonnegative integer: "))
if n < 0:
print("Please input a nonnegative integer next time. Bye!")
else:
originalN = n
suffix = ""
while n > 0:
suffix = str(n % 2) + suffix
n = n // 2
# The input n = 0 is dealt with as a special case
if suffix == "":
suffix = "0"
print("The binary equivalent of", originalN, "is", suffix)
关键不是这个例子,而是分析问题,解决问题的思路,以及层层的优化。从本例中,思路是:理解清楚问题---从小规律入手分析问题--写出伪代码--写Python代码--进行逐步优化。
你发现Python的魅力了吗?今天,你进步了吗?