python练习题-20170916

周末开始第一次尝试对着书写代码练习题

《笨办法学python》--作者Zed A.Shaw,翻译Wang Dingwei

ex1.pyprint(‘hello world‘)---------------------------------------ex2.py
#A comment, this is so you can read your program later.#Anything after the # is ignored by python.

print(‘i could have code like this‘) # and the comment after is ignored.#you can also use a comment to ‘disable‘ or comment out pieve of code.#print "this won‘t run"

print(‘this will run‘)------------------------------------------------------------------------ex3.py

print(‘i will now count my chickens‘)
print(‘hens‘,25+30/6)print(‘rooster‘,100-25*3%4)print(‘now i will count my eggs:‘)print(3+2+1-5+4%2-1/4+6)print(‘is it ture that 3+2<5-7?‘)print(3+2<5-7)print(‘what is 3+2?‘,3+2)print(‘what is 5-7?‘,5-7)print("oh that‘s why it‘s False.")print(‘how about some more?‘)print(‘is it greater?‘,5>2)print(‘is it great or equal?‘,5>=2)print(‘is it less or equal?‘,5<=2)--------------------------------------------------------------ex4.py
cars=100space_in_a_car=4.0drivers=30passangers=90cars_not_driven=cars-driverscars_driven=driverscarpool_capacity=cars_driven*space_in_a_caraverage_passagers_per_car=passangers / cars_driven#变量之间要用,隔开,不能用空格print(‘there are‘,cars,‘cars available.‘)print(‘there are only‘,drivers,‘drivers avalilable.‘)print(‘there will be‘,cars_not_driven,‘emtpy cars today.‘)print(‘we can transport‘,carpool_capacity,‘people today.‘)print(‘we have‘,passangers,‘to carpool today.‘)print(‘we need to put about‘,average_passagers_per_car,‘in each car.‘)--------------------------------------------------------------------------------ex5.py
my_name = ‘zed a. shaw‘my_age = 35 #not a liemy_height = 74  #inchesmy_weight = 180 #lbsmy_eyes = ‘blue‘my_teeth = ‘white‘my_hair = ‘brown‘#%str表示格式化字符串print("let‘s talk about %s." %my_name)print("he‘s %d inches tall." %my_height)print("he‘s %d pounds heavy." %my_weight)print("actually it is not too heavy.")print("he‘s got %s eyes and %s hair." %(my_eyes,my_hair))print("his teeth are usually %s depending on the coffee." %my_teeth)#this line is tricky,try to get it exactly right.print(‘if i add %d,%d and %d i get %d.‘ %(my_age,my_height,my_weight,my_age+my_height+my_weight))------------------------------------------------------------------------------------------------------ex6.py
#%d表示转化成10进制整数x = "there are %d types pf people." % 10binary = "binary"do_not = "don‘t"#%s表示转化成字符串y = "those who knows %s and those who %s." %(binary,do_not)

print(x)print(y)#%r表示?print("i said: %r." %x)print("i also said: ‘%s‘." %y)

hilarious = Falsejoke_evaluation = "isn‘t that joke so funny?! %r"print(joke_evaluation % hilarious)

w = "this is the left side of ..."e = "a string with a right side."

print(w+e)------------------------------------------------------------------------------ex7.py
print("mary had a little lamb")print("its fleece was white as %s." %‘snow‘)print("and everywhere that mary went")print("."*10) #what‘s that do?

end1 ="c"end2 ="h"end3 ="e"end4 ="e"end5 ="s"end6 ="e"end7 ="B"end8 ="u"end9 ="r"end10 ="g"end11 ="e"end12 ="r"

#watch that comma at the end. try removing it to what happensprint(end1 + end2 + end3 + end4 + end5 + end6)print(end7 + end8 + end9 + end10 + end11 + end12)----------------------------------------------------------------------------------ex8.py
formatter = "%r %r %r %r"

print (formatter % (1,2,3,4))print (formatter % ("one","two","three","four"))print (formatter % (True,False,False,True))print (formatter % (formatter,formatter,formatter,formatter))print (formatter % (    "i had this thing.",    "that you could type up right.",    "but it didn‘t sing.",    "so i said goodnight"))#print后面要紧跟(),括号内不同字符串之间要,隔开#括号内字符串要用"",其他数据类型不用""#formatter是个变量,表示字符串------------------------------------------------------------------ex9.py
#here‘s some new strange stuff,remeber type it excatly.

days = "mon tue wed thu fri sat sun"mouths = "jan\nfeb\nmar\napr\nmay\njun\njul\naug"

print("here are the days:",days)print("here are the mouths:",mouths)

print("""there‘s something going on here.with the three double-quotes.we‘ll be able to type as much as we like.even 4 lines if we want,or 5,or 6.""")----------------------------------------------------------ex10.py
tabby_cat = "\t i‘m tabbed in."persian_cat = "i‘m split\non a line."backslash_cat = "i‘m \\ a \\ cat."

fat_cat = """i‘ll do a list:\t* cat food\t* fishies\t* catnip \n \t* grass"""

print(tabby_cat)print(persian_cat)print(backslash_cat)

#\t转义为tab#\n转义为下一行#\\转义为\#\r转义为回车#\f转义为换页------------------------------------------ex11.py
print("how old are you?"),age = input()print("how tall are you?"),height = input()print("how much do you weigh?"),weigh = input()

print("so, you‘re %r old, %r tall and %r heavy." %(age,height,weigh))

#python3里input代替raw_input--------------------------------------------------------------------------ex12.py
y = input("name?")age = input("how old are you?")height =input("how tall are you?")weigh =input("how much do you weigh?")print("so,you‘re %r old,%r tall and %r heavy." %(age,height,weigh))

#python -m pydoc open/file/os/sys/input-------------------------------------------------------------------------ex13.py
from sys import argv

script, first, second, third = argv

print("the script is called:",script)print("your first variable is:",first)print("your second variable is:",second)print("your third variable is:",third)------------------------------------------------ex14.py
from sys import argv

script,user_name = argvprompt = ‘>‘

print("hi %s,i‘m the %s script." %(user_name,script))print("i‘d like to ask you a few question.")print("do you like me %s" %(user_name))likes = input(prompt)

print("where do you live? %s" %(user_name))lives = input(prompt)

print("what kind of computer do you have?")computer = input(prompt)

print ("""alright, so you said %r about liking me.you live in %r.not sure where that is.and you have a %r computer.nice."""%(likes,lives,computer))

#python3中,print的内容必须全部在()内#sys=system#sys.argv是一个字符串列表,也是一个命令行参数列表(使用命令行传递给程序参数的列表)#从命令行输入python 程序名称.py 内容,内容被作为参数传递给程序,储存在sys.argv中-----------------------------------------------------------------------------ex15.py
from sys import argv

script,filename = argv

txt = open(filename)

print("here‘s your file %r:" %filename)print(txt.read())#read是open命令的一个函数print("type the filename again:")file_again = input(">")     #将输入的内容赋值给file_again

txt_again = open(file_again)    #使用open函数打开输入的文件,赋值给txt_again

print(txt_again.read())     #输出读取到文件的内容----------------------------------------------------------------------------ex16.py
from sys import argv

script,filename = argv

print("we‘re going to erase %r." %filename)print("if you don‘t want do that,hit ctrl-c(^c)")print("if you do want that,hit return")

input("?")

#对文件使用open命令,要赋值给一个变量,通过变量进行参数操作,操作方法就是变量名.参数print("open the file...")target = open(filename,"w")#open命令里面的w参数是指文件若存在,首先要清空,然后(重新)创建

print("truncating the file,goodbye")target.truncate()       #truncate是清空文件内全部内容

print("now i‘m going to ask you for three lines")

line1 = input("line 1:")        #向文件内输入内容line2 = input("line 2:")line3 = input("line 3:")

print("i‘m going to write there to the file")

line = str(line1+‘\n‘+line2+‘\n‘+line3)#尝试新方法:新建一个变量line,将输入的line1、line2与line3赋值给line,中间写入‘\n‘换行符

target.write(line)#write后面的参数指输入的内容变量# target.write(line1)# target.write("\n")# target.write(line2)# target.write("\n")# target.write(line3)# target.write("\n")

print("and finally,we close it")target.close()------------------------------------------------------------------------------------ex17.py
from sys import argvfrom os.path import exists

script,from_file,to_file = argv

print("copying from %s to %s" %(from_file,to_file))#we could do these two on one lines too,how?

input1 = open(from_file)     #打开from_file赋值给input变量indata = input1.read()       #读取from_file的内容赋值给indata,就是需要copy的内容

print("the input file is %d bytes long" %len(indata))       #输出copy的长度print("does the output file exist? %r" %exists(to_file))    #输出目标文件是否存在print("ready,hit return to continue,ctrl-c to abort.")input = ()#输入内容

output =open(to_file,‘w‘)       #新建to_file文件赋值给output变量output.write(indata)            #将需要copy的内容写入to_file文件

print("alright,all done")

output.close()input1.close()----------------------------------------------------------------------------------------ex18.py
#命名、变量、代码、函数

#this one is likes your scripts with argv#*argument表示动态变量,可以不受数量限制def print_two(*args):    arg1,arg2 = args    print("arg1:%r,arg2:%r" %(arg1,arg2))

#ok,this *args is actuallu pointless,we can just do this.def print_two_again(arg1,arg2):    print("arg1:%r,arg2:%r" %(arg1,arg2))

#this just take one argument.def print_one(arg1):    print("arg1:%r" %arg1)

#this one take none argument.def print_none():    print("i got nothing")

print_two("zed","shaw")print_two_again("zed","shaw")print_one("first")print_none()------------------------------------------------------------------ex19.py
#函数和变量def cheese_and_crackers(cheese_count,box_of_crackers):    print("you have %d cheeses" %cheese_count)    print("you have %d crackers" %box_of_crackers)    print("man that is enough for party.")    print("get a blanket. \n")

print("we can just give the function numbers dirctly.")cheese_and_crackers(20,30)

print("oh,we can use variables from the script:")amount_of_cheese = 10amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese,amount_of_crackers)

print("we can even do math insides too:")cheese_and_crackers(10+20,5+6)

print("we can also combine the two,variables and math:")cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)---------------------------------------------------------------------

2017-09-17    20:42:39
时间: 2024-08-08 21:56:09

python练习题-20170916的相关文章

Python练习题 024:求位数及逆序打印

[Python练习题 024] 给一个不多于5位的正整数,要求:一.求它是几位数,二.逆序打印出各位数字. ---------------------------------------------- 这题如果不用递归,实在太简单了!!!代码上: str = input('请输入一个不多于5位的正整数:') print('这个数字是%s位数,逆序为%s.' % (len(str), str[::-1])) 输出结果如下: 请输入一个不多于5位的正整数:45931这个数字是5位数,逆序为13954

python练习题:循环打印嵌套列表

好久没写博文了,添加一个练习题,选自<head_first_python>~~ python列表:以中括号开始和结束"[]":列表项以逗号","分隔开,使用赋值操作符"="赋予一个标识符.如: movies=["the holy",1975,"terry jones",91,["graham",["michael","john",&qu

Python练习题 028:求3*3矩阵对角线数字之和

[Python练习题 028] 求一个3*3矩阵对角线元素之和 ----------------------------------------------------- 这题解倒是解出来了,但总觉得代码太啰嗦.矩阵这东西,应该有个很现成的方法可以直接计算才对-- 啰嗦代码如下: str = input('请输入9个数字,用空格隔开,以形成3*3矩阵:') n = [int(i) for i in str.split(' ')] #获取9个数字 mx = [] #存储矩阵 for i in ra

Python练习题 027:对10个数字进行排序

[Python练习题 027] 对10个数字进行排序 --------------------------------------------- 这题没什么好说的,用 str.split(' ') 获取输入的10个数字,然后用 lst.sort() 就完成排序了.代码如下: s = input('请输入10个数字,以空格隔开:') n = [int(x) for x in s.split(' ')] n.sort() print(n) 输出结果如下: 请输入10个数字,以空格隔开:3 23 4

Python练习题 023:比后面的人大2岁

[Python练习题 023] 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁.问第4个人岁数,他说比第3个人大2岁.问第三个人,又说比第2人大两岁.问第2个人,说比第一个人大两岁.最后 问第一个人,他说是10岁.请问第五个人多大? ----------------------------------------------------- 这题真是--用心算就能算出来好吗?好吧,应该又是要训练递归函数,最近这几题总是跟递归纠缠不清.不过,似乎慢慢理解了递归函数的写法了.本题代码如下:

Python练习题 003:完全平方数

[Python练习题 003]一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? ------------------------------------------------- 所谓的“完全平方数”,就是开完根号仍然是整数. 数学渣是这么思考的:假设这个数 i 在10000以内.第一步:x = sqrt(i+100).如果 x == floor(x),则证明 x 是个整数.第二步道理也相同,但要记得把 x**2 把根号还原回来,再加上 168,然后再来

Python练习题 016:猴子吃桃

[Python练习题 016] 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个.第二天早上又将剩下的桃子吃掉一半,又多吃了一个.以后每天早上都吃了前一天剩下的一半零一个.到第10天早上想再吃时,见只剩下一个桃子了.求第一天共摘了多少. -------------------------------------------------- 这题得倒着推.第10天还没吃,就剩1个,说明第9天吃完一半再吃1个还剩1个,假设第9天还没吃之前有桃子p个,可得:p * 1/2 -

Python练习题 009:水仙花数

[Python练习题 009] 打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身.例如:153是一个“水仙花数”,因为153=1的三次方+5的三次方+3的三次方. ---------------------------------------------------------------------- 这题也是送分题,只要能把任意三位数的百位.十位.个位拆解出来就好办了.思路:将任意3位数除以100再向下取整,即可得到百位数.将这个3位数减去(百位数*10

Python练习题 025:判断回文数

[Python练习题 025] 一个5位数,判断它是不是回文数.即12321是回文数,个位与万位相同,十位与千位相同. ----------------------------------------------- 做题做到现在,这种题目已经很轻车熟路了.希望下一题能增加点难度啊~~~ x = input('请输入一个5位数:') if x[0] == x[4] and x[1] == x[3]: print('%s是个回文数' % x) else: print('%s不是回文数' % x) 输