习题一 第一个程序
print "Hello World!" print "Hello Evilxr" print "I like typing this." print "This is fun." print "Yay! Printing." print "I'd much tather you 'not'." print 'I "said" do not touch this.'
习题二 注释
# A comment.This is so you can read your prigram later. # Anython 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 a piece of code: # print "This won't run." print "This is will run."
习题三 数字和数字计算
print "I will now count my chickens:" print "Hens",25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true 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 greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
习题四 变量和命名
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "ineach car."
习题五 更多的变量和打印
my_name = 'Evilxr' my_age = 19 # is a lie my_height = 173 # is a lie my_weight = 126 # not a lie my_eyes = 'Black' my_teeth = 'White' my_hair = 'Black' print "Let's talk about %s." % my_name print "He's %d inchea tall." % my_height print "He's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair) #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)
习题六 字符串和文本
x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." %(binary,do_not) print x print y print "I said: %r." % x print "I also said: '%s'." % y hilarious = False joke_evaluation = "Isn't that joke so sunny?! %r" print joke_evaluation % hilarious w = "This is the left side of.." e = "a string with a right side." print w + e
习题七 更多打印
print "TP had a little lamb." print "Its fleece was white as %s." % 'snow' print "And everywhere that Mary went." print "." * 12 # what'd 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 temauing it to see what happens print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 + end12
习题八 打印,打印
formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % ("ont", "tow", "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." )
习题九 打印,打印,打印
#coding:utf-8 #习题九 打印,打印,打印 #Here's some new strange stuff, remember type it exactly. days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print "Here are the days: ", days print "Here are the months: ", months print """ There's somthing going on here. With the three double-quotes. We'll be able to type as muck as we like. Even 4 lines if we want, or 5, or 6. """
习题10 那是什么
#coding:utf-8 #习题10 那是什么 tabby_cat = "\tI'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 print fat_cat
习题11 提问
#coding:utf-8 # 习题11 提问 print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." %( age, height, weight)
习题十二 提示别人
#coding:utf-8 # 习题十二 提示别人 age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weithd? ") print "So, you're %r old, %r tall and %r heaby." % ( age, height, weight)
习题13 参数 解包 变量
# coding:utf-8 # 习题13 参数 解包 变量 from sys import argv script, first, second, third = argv print "The scirpt is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third
习题14 提示和传递
# coding:utf-8 # 习题14 提示和传递 from sys import argv script, user_name = argv prompt = '> ' print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name likes = raw_input(prompt) print "Where do you live %s?" % user_name lives = raw_input(prompt) print "What kind of computer do you have?" computer = raw_input(prompt) print """ Alright, so you sadi %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer)
习题15 读取文件
# coding:utf-8 # 习题15 读取文件 from sys import argv # 引入参数变量 script, filename = argv # 使用argv获取文件名 txt = open(filename) # 打开文件 print "Here's your file %r:" % filename # 输出文件名 print txt.read() # 打印文件内容 print "Type the filename again:" file_again = raw_input("> ") # 获取用户输入的文件名 txt_again = open(file_again) # 打开文件 print txt_again.read() # 打印文件内容
习题十六 读写文件
# coding:utf-8 # 习题十六 读写文件 # 说明——>该脚本可以新建一个内容为三行的文件 from sys import argv # 引入参数变量 script, filename = argv # 使用argv获取文件名 print "We're going to erase %r." % filename # 打印将创建的文件名 print "If you don't want that, hit CTRL-C(^C)" # 打印退出文件方法 raw_input("?") # print "Opening the file..." target = open(filename, 'w') print "Truncation the file. Goodby!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line1 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." 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()
习题17:更多文件操作
#coding:utf-8 #习题17:更多文件操作 #程序目的:实现文件Copy. from sys import argv from 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 line too, how? input = open(from_file) indata = input.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(to_file) raw_input() output = open(to_file, 'w') output.write(indata) print "Alright, all done." output.close() input.close()
习题18:命名 变量 代码 函数
#coding:utf-8 #习题18:命名 变量 代码 函数 # This one is lije your scritps with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # This just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # This one takes no arguments def print_none(): print "Hi.Evilxr! This time your need eat." print_two("Evilxr", "Luckly") print_two_again("Evilxr","Luckly") print_one("First!") print_none()
习题19:函数和变量
# coding:utf8 # 习题19:函数和变量 # Code by-->Evilxr # 2014-8-30 # 新建cheese_and_crackers函数,带有两个参数 def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enouth for a party!" print "Get a blandet. \n" print "We can just give the function numbers directly:" # 调用函数并传值 cheese_and_crackers(20, 30) print "OR, we can use variables from our script:" # 新建两个变量并赋初值 amount_of_cheese = 10 amount_of_crackers = 50 # 第二次调用函数并传值 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print "We can even do math inside too:" # 第三次调用函数并传值 cheese_and_crackers(10 + 20, 5 + 6) print "And we can combine the two, variables and math:" # 第四次调用函数并传值 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
习题20:函数和文件
# coding:utf-8 # 习题20:函数和文件 # Code by --> Evilxr # 2014-8-31 from sys import argv script, input_file = argv def print_all(f): #创建读文件函数 print f.read() def rewind(f): #创建函数 f.seek(0) def print_a_line(line_count, f): #该函数可以打印文件的一行内容 print line_count, f.readline() current_file = open(input_file) #创建变量并赋初值 print "First let's print the whole file:\n" print_all(current_file) #调用print_all函数并传递值 print "Now let's rewind, kind of like a tape." rewind(current_file) #调用rewind函数并传递值 print "Let's print three lines:" # 打印文件内容,并显示行号 current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
习题21:函数可以返回的东西
# coding:utf8 # 习题21:函数可以返回的东西 # Date:2014-9-3 def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def multiply(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % (a, b) return a /b print "Let's do some math with just function!" age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(400,3) print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) # A puzzle for the extra credit, type in anymay. print "Here is a puzzle." what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print "That becomes: ", what, "Evilxr, Can you do it by hand?"
习题24:更多练习
# coding:utf8 # 习题24:更多练习 # Date:2014-9-5 print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tables.' Evilxr = """ \tThe lovely world whit logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\twhere there is none. Code by:Evilxr """ print "--------------" print Evilxr print "--------------" five = 10 - 2 + 3 -6 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) print "With a starting point of: %d" % start_point print "We'd have %d beans, %d jars, and %d crates." % (beans, jars ,crates) start_point = start_point / 10 print "I can also do that this way:" print "I'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
习题25:更多练习
# coding:utf8 # 习题25:更多练习 # Date:2014-9-9 def break_words(stuff): """This is function will break up words for us.""" words = stuff.split(' ') return words def sort_word(words): """Sorts the words.""" return sorted(words) def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word def print_last_word(words): """Prints the last word agter popping it off""" word = words.pop(-1) print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = breas_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words)
习题31:作出决定
# coding:utf8 # 习题31:作出决定 # Date: 2014-9-14 print "You enter a dark room with two doors.Do you go through door #1 or door $2?" door = raw_input("> ") if door == "1": print "There's a giant bear here eating a cheese cake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." bear = raw_input("> ") if bear == "1": print "The bear eats your face off. Good job!" elif bear == "2": print "The bear eats your legs off. Good job!" else: print "Well, doing %s is probably better. Bear runs away." % bear elif door == "2": print "You stare into the endless abyss a Cthlhu's retina." print "1. Blueberries." print "2. Yellow jaceet clothespins." print "3. Understanding revolvers yelling melodies." insanity = raw_input("> ") if insanity == "1" or insanity == "2": print "Your body survives powered by a mind of jello. Good job!" else: print "The insanity rots your eyes into a pool of muck. Good job!" else: print "You stumble around and fall on a knife and die. Good job!"
习题32: 循环和列表
# coding:utf8 # 习题32: 循环和列表 # Date: 2014-9-27 the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range(0, 6): print "Adding %d to the list." % i # appens is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print "Element was: %d" % i
习题33: Whil循环
# coding:utf8 # 习题33: Whil循环 # Date: 2014-9-17 i = 0 numbers = [] x = raw_input("Plase input a number") x = int(x) while i < x: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now:", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num
习题35:分支和函数
# coding:utf8 # 习题35:分支和函数 # Date: 2014-9-18 # Label: 109 from sys import exit def gold_room(): print "This room is full of gold. How much do you take?" next = raw_input("> ") if "0" in next or "i" in next: how_much = int(next) else: dead("Man, learn to type a number.") if how_much < 50: print "Nice, you're not greedy, you win!" exit(0) else: dead("You greedy bastard!") def bear_room(): print "There is a bear here." print "The bear has bunch of honey." print "The fat bear is in front of another door" print "How are you going to move the bear?" bear_moved = False while True: next = raw_input(">" ) if next == "Take honey": dead("The bear looke at you then slaps your face off.") elif next == "taunt bear" and not bear_moved: print "The bear has moved from the door. You can go through it now." bear_moved = True elif next == "taunt bear" and bear_moved: dead("The bear gets pissed off and chews your leg off.") elif next == "open door" and bear_moved: gold_room() else: print "I got no idea what than means." def cthulhu_room(): print "Here you see the great evil Cthulhu." print "He, it, whatever stares at you and you go insane." print "Do you flee for your life or eat your head?" next = raw_input(">" ) if "flee" in next: start() elif "head" in next: dead("Well that was tasty!") else: cthulhu_room() def dead(why): print why, "Good job!" exit(0) def start(): print "You are in a dark room." print "There is a door to your right and left." print "Which one do you take?" next = raw_input(">" ) if next == "left": bear_room() elif next == "right": cthulhu_room() else: dead("You stumble around the room until you starve.") start()
习题39:列表的操作
# coding:utf8 # 习题39:列表的操作 # Date:2014-9-19 ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that." stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding:", next_one stuff.append(next_one) print "There's %d items now." % len(stuff) print "The we go: ", stuff print "Let's do some things with stuff." print stuff[1] print stuff[-1] # whoa! fancy print stuff.pop() print ' '.join(stuff) # what? coll! print '#'.join(stuff[3:5]) # super stellar!
若非特别声明,文章均为Evilxr的个人笔记,转载请注明出处。