周末开始第一次尝试对着书写代码练习题
《笨办法学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