首页 » 父与子的编程之旅:与小卡特一起学Python » 父与子的编程之旅:与小卡特一起学Python全文在线阅读

《父与子的编程之旅:与小卡特一起学Python》第5章

关灯直达底部

测试题

1. 对于这行代码:

answer = raw_input  

如果用户键入 12answer 会包含一个字符串。这是因为 raw_input 总是会得到一个字符串。

在一个小程序里试试看:

print "enter a number: ",answer = raw_inputprint type(answer)>>> ============== RESTART ==============>>>enter a number: 12<type 'str'>>>>  

所以 raw_input 会提供一个字符串。

记住,在 Python 3 中,rawinput 改名为 input3

2. 要让 raw_input 打印一条提示消息,可以在括号里的引号中加一些文本,如下:

answer = raw_input("Type in a number: ")  

3. 要使用 raw_input 得到一个整数, 可以使用 int 转换从 raw_input 得到的字符串。这个工作可以分两步来完成,如下:

something = raw_inputanswer = int(something)  

或者也可以一步完成,如下:

answer = int(raw_input)  

4. 与上一题类似,只不过要使用 float 而不是 int

动手试一试

1. 交互模式中,这个指令应当如下所示:

>>> first = 'Warren'>>> last = 'Sande'>>> print first + lastWarrenSande  

唉呀!没有空格。可以在你的名字末尾加一个空格。

>>> first = 'Warren '  

或者这样试试看:

>>> print first + ' ' + lastWarren Sande  

还可以使用一个逗号,如下:

>>> first = 'Warren'>>> last = 'Sande'>>> print first, lastWarren Sande  

2. 这个程序应当类似下面的代码:

first = raw_input('enter your first name: ')last = raw_input('enter your last name: ')print 'Hello,', first, last, 'how are you today?'  

3. 这个程序应当类似下面的代码:

length = float(raw_input ('length of the room in feet: '))width = float(raw_input ('width of the room in feet: '))area = length * widthprint 'The area is', area, 'square feet.'  

4. 可以为上面第 3 题的程序增加几行代码:

length = float(raw_input ('length of the room in feet: '))width = float(raw_input ('width of the room in feet: '))cost_per_yard = float(raw_input ('cost per square yard: '))area_feet = length * widtharea_yards = area_feet / 9.0total_cost = area_yards * cost_per_yardprint 'The area is', area_feet, 'square feet.'print 'That is', area_yards, 'square yards.'print 'Which will cost', total_cost  

5. 程序应该类似下面的代码:

quarters = int(raw_input("How many quarters? "))dimes = int(raw_input("How many dimes? "))nickels = int(raw_input("How many nickels? "))pennies = int(raw_input("How many pennies? "))total = 0.25 * quarters + 0.10 * dimes + 0.05 * nickels + 0.01 * penniesprint "You nave a total of: ", total