cat > ~/.vimrc << EOF " 加载插件 filetype plugin on let g:pydiction_location = '~/.vim/tools/pydiction/complete-dict' let g:pydiction_menu_height = 3 " 设置文件类型 set filetype=python au BufNewFile,BufRead *.py,*.pyw setf python
"配置vimrc set tabstop=2 set shiftwidth=2 set softtabstop=2 set autoindent set smartindent set nobackup set expandtab set number set ruler set nocompatible set syntax=on set encoding=utf-8 set fileformats=unix,dos set showmatch EOF
[sujx@dev python]$ cat ex1.py print("Hello World!\n") print("Hello Agin\n") print("I like typing this.\n") print("This is fun.\n") print("Yay! Printing.\n") print("I'd much rather your 'not'.\n") print('I "said" do not touch this.\n')
[sujx@dev python]$ python ex1.py Hello World!
Hello Agin
I like typing this.
This is fun.
Yay! Printing.
I'd much rather your 'not'. I "said" do not touch this.
注释和#号
1 2 3 4 5 6 7 8 9 10 11 12 13 14
[sujx@dev python]$ cat ex2.py # Acomment, this is so you can read your program later. # Anything after the # is ignored by python.
print("I could have code like.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out code: # print("This won't run.")
print("This will run.")
[sujx@dev python]$ python ex2.py I could have code like. This will run.
[sujx@dev python]$ cat ex3.py print("I will now count my chickens:") print("Hens", 25 + 30 /6) print("Roosters", 100 - 25 * 3 % 4 ) print("Now I will count the eggs:")
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 greate or equal?", 5 >= -2) print("Is it less or equal?", 5 <= -2)
[sujx@dev python]$ python ex3.py I will now count my chickens: Hens 30.0 Roosters 97 Now I will count the eggs: 6.75 Is it true that 3 + 2 < 5 - 7 ? False What is3 + 2? 5 What is5 - 7 -2 Oh, that's why it's False. How about some more. Is it greater? True Is it greate or equal? True Is it less or equal? False
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, "in each car.")
[sujx@dev python]$ python ex4.py There are 100 cars available. There are only 30 drivers available. There will be 70 empty cars today. We can transport 120.0 people today. We have 90 to carpool today. We need to put about 3.0in each car.
print(f"Let's talk about {my_name}. ") print(f"He's {my_height} cm tall.") print(f"He's {my_weight} kg heavy. ") print("Actually that's not too heavy. ") print(f"He's got {my_eyes} eyes and {my_hair} hair.") print(f"His teeth are usually {my_teeth} depending on the coffee.")
# This line is tricky, try to get it exactly right. total = my_age + my_height + my_weight print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
[sujx@dev python]$ python ex5.py Let's talk about su jingxuan. He's 163 cm tall. He's 143 kg heavy. Actually that's not too heavy. He's got Black eyes and Black hair. His teeth are usually White depending on the coffee. If I add 42, 163, and 143 I get 348.
[sujx@dev python]$ cat ex6.py types_of_people = 10 x = f"There are {types_of_people} types of people."
binary = "binary" do_not = "don't" y = f"Those who konw {binary} and those who {do_not}."
print(x) print(y) print(f"I said: {x}") print(f"I also said: '{y}'")
hilarious = False joke_evaluation = "Isn't that joke so funny? {}!"
print(joke_evaluation.format(hilarious))
w = "This is the left side of... " e = "a string with a right side."
print(w + e)
[sujx@dev python]$ python ex6.py There are 10 types of people. Those who konw binary and those who don't. I said: There are 10 types of people. I also said: 'Those who konw binary and those who don't.' Isn't that joke so funny? False! This is the left side of... a string with a right side.
[sujx@dev python]$ cat ex7.py print("Mary had a little lamb.") print("Its fleece was white as {}.".format('snow')) print("And everywhere that Mary went.") print("." * 10) # What'd that do?
print(formatter.format(1, 2, 3, 4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format(True, False, False, True)) print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format( "Try your", "Own text here", "Maybe a poem", "Or a song about fear" ))
[sujx@dev python]$ python ex8.py 1234 one two three four TrueFalseFalseTrue {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} Try your Own text here Maybe a poem Or a song about fear
[sujx@dev python]$ cat ex9.py # 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 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. """)
[sujx@dev python]$ python ex9.py Here are the days: Mon Tue Wed Thu Fri Sat Sun Here are the months: Jan Feb Mar Apr May Jun Jul Aug
There's something going on here. With the three double-quotes. We'll be able to typeas much as we like. Even 4 lines if we want, or5, or6.
[sujx@dev python]$ cat ex11.py print("How old are you?", end='') age = input() print("How tall are you?", end='') height = input() print("How much do you weight?", end='') weight = input()
print(f"So, you're {age} old, {weight} heavy, and {height} tall.")
[sujx@dev python]$ cat ex12.py age = input("How old are you?") height = input("How tall are you?") weight = input("How much do you weight?")
print(f"So, you're {age} old, {weight} heavy, and {height} tall.")
[sujx@dev python]$ python ex11.py How old are you?42 How tall are you?165cm How much do you weight?73kg So, you're 42 old, 73kg heavy, and 165cm tall.
基础
参数、解包和变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[sujx@dev python]$ cat ex13.py from sys import argv # read the WYSS section for how to run this script, first, second, third = argv
print("The script is called: ", script) print("The first variable is: ", first) print("The second variable is: ", second) print("The third variable is:", third)
[sujx@dev python]$ python ex13.py 1st 2nd 3rd The script is called: ex13.py The first variable is: 1st The second variable is: 2nd The third variable is: 3rd
print(f"Hi {user_name}, I'm the {script} script.") print("I'd like to ask you're a few questions.") print(f"Do you like me {user_name}?") likes = input(prompt)
print(f"Where do you live {user_name}") lives = input(prompt)
print("What kind of computer do you have?") computer = input(prompt)
print(f""" Alright, so you said {likes} about liking me. You live in {lives}. Not sure where that is. And you have a {computer} computer. Nice. """)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[sujx@dev python]$ python ex14.py xiaoming Hi xiaoming, I'm the ex14.py script. I'd like to ask you're a few questions. Do you like me xiaoming? > Yes Where do you live xiaoming > NewYork What kind of computer do you have? > Compaz
Alright, so you said Yes about liking me. You live in NewYork. Not sure where that is. And you have a Compaz computer. Nice.
[sujx@dev python]$ python ex15.py ex15_sample.txt Here's your file ex15_sample.txt: This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here. Type the filename again: > ex15_sample.txt This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here.
print(f"We're going to erase {filename}.") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.") input("?") print("Opening the file...") target = open(filename, 'w')
print("Truncating the file. Goodbye!") target.truncate()
print("Now I'm going to ask you for three lines.")
[sujx@dev python]$ python ex16.py test.txt We're going to erase test.txt. If you don't want that, hit CTRL-C (^C). If you do want that, hit RETURN. ? Opening the file... Truncating the file. Goodbye! Now I'm going to ask you for three lines. line 1: 白日依山尽 line 2: 黄河入海流 line 3: 欲穷千里目 line 4: 更上一层楼 I'm going to write these to the file. And finally, we close it. [sujx@dev python]$ cat test.txt 白日依山尽 黄河入海流 欲穷千里目 更上一层楼
[sujx@dev python]$ python ex17.py test.txt target.txt Copying from test.txt to target.txt... The output file is 24 bytes long. Dose the output file exist? True Ready, hti RETURN to continue, CTRL-C to abort.
defcheese_and_crackers(cheese_count, boxes_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_crackers} boxes of crackers!") print("Man that's enough for a party!") print("Get a blanket.\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
[sujx@dev python]$ python ex19.py We can just give the function numbers directly: You have 20 cheeses! You have 30 boxes of crackers! Man that's enough for a party! Get a blanket.
OR, we can use variables from our script: You have 10 cheeses! You have 50 boxes of crackers! Man that's enough for a party! Get a blanket.
We can even do math inside too: You have 30 cheeses! You have 11 boxes of crackers! Man that's enough for a party! Get a blanket.
And we can combine the two, variables and math: You have 110 cheeses! You have 1050 boxes of crackers! Man that's enough for a party! Get a blanket.
# A puzzle for the extra credit, type is in anyway. print("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print("That become:", what, "Can you do it by hand?")
执行
1 2 3 4 5 6 7 8 9 10 11 12 13
python ex21.py Let's do some math with just functions! Addning 30 + 5 SUBTRACTING 78 - 4 MULTIPLYING 90 * 2 DIVDING 100 / 2 Age:35, Height:74, Weight:180, IQ:50.0 Here is a puzzle. DIVDING 50.0 / 2 MULTIPLYING 180 * 25.0 SUBTRACTING 74 - 4500.0 Addning 35 + -4426.0 That become: -4391.0 Can you do it by hand?
print("Let's practice everything.") print('You\'d need to know \'bout escapes with \\ that do:') print('\n newlines and \t tabs.')
poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition \n\t\twhere there is non. """
# remember that this is another way to format a string print("With a starting point of: {}".format(start_point)) # It's just like with an f"" string. print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
start_point = start_point / 10
print("We can also do that this way:") formula = secret_formula(start_point) # This is an easy way to apply a list to a format string. print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
defbreak_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words
defsort_words(words): """Sorts the words.""" returnsorted(words)
defprint_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print(word)
defprint_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print(word)
defsort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words)
defprint_first_adn_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words)
defprint_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)
if people < cats: print("Too many cats! The world is doomed!") if people > cats: print("Not many cats! The world is saved!")
if people < dogs: print("The world is drooled on!") if people > dogs: print("The world is dry.")
dogs += 5
if people >= dogs: print("People are greater than or equal to dogs.") if people <= dogs: print("People are less than or equal to dogs.")
if people == dogs: print("People are dogs.")
执行
1 2 3 4 5
Too many cats! The world is doomed! The world is dry. People are greater than or equal to dogs. People are less than or equal to dogs. People are dogs.
else语句
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
people = 20 cats = 30 dogs = 15
if people < cats: print("Too many cats! The world is doomed!") elif people > cats: print("Not many cats! The world is saved!") else: print("Eveybody have a cat!")
if people < dogs: print("The world is drooled on!") elif people > dogs: print("The world is dry.") else: print("People are dogs.")
print(""" You enter a dark room with two doors. Do you go through door #1 or door #2 ? """)
door = input("> ")
if door == "1" : print("There's a giant beat here eating a cheese cake.") print("What do you do?") print("1. Take the cake.") print("2. Scream at bear.")
bear = input("> ")
if bear == "1": print("The bear eat your face off. Good Job!") elif bear == "2": print("The bear eats your legs off. Good Job!") else: print(f"Well, doing {bear} is probably better.") print("Bear run away.")
elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.")
insanity = input("> ")
if insanity == "1"or insanity == "2": print("Your body survives powered by a mind of jello.\nGood Job!") else: print("The insanity rots your eyes into a pool of muck.\nGood Job!")
else: print("You stumble around and fail on a knife and die.\nGood Job!")
# This first kind of for-loop goes through a list for number in the_count: print(f"This is count {number}")
# same as above for fruit in fruits: print(f"A fruit of type: {fruit}")
# Also we can go through mixed lists too # Notice we have to use {} since we don't know what's in it for i in change: print(f"I got {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 inrange(0, 6): print(f"Adding {i} to the list.") # append is a function that lists understand elements.append(i)
# now we can print them out too for i in elements: print(f"Element was: {i}")
This is count 1 This is count 2 This is count 3 This is count 4 This is count 5 A fruit of type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got pennies I got dimes I got 3 I got quarters Adding 0 to the list. Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list. Element was: 0 Element was: 1 Element was: 2 Element was: 3 Element was: 4 Element was: 5
while循环
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
i = 0 numbers = []
while i< 6: print(f"At the top i is {i}") numbers.append(i)
i += 1 print("Number now:", numbers) print(f"At the bottom i is {i}")
At the top i is 0 Number now: [0] At the bottom i is 1 The numbers: 0 At the top i is 1 Number now: [0, 1] At the bottom i is 2 The numbers: 0 1 At the top i is 2 Number now: [0, 1, 2] At the bottom i is 3 The numbers: 0 1 2 At the top i is 3 Number now: [0, 1, 2, 3] At the bottom i is 4 The numbers: 0 1 2 3 At the top i is 4 Number now: [0, 1, 2, 3, 4] At the bottom i is 5 The numbers: 0 1 2 3 4 At the top i is 5 Number now: [0, 1, 2, 3, 4, 5] At the bottom i is 6 The numbers: 0 1 2 3 4 5
defgold_room(): print("This room is full of gold. How much do you take?") choice = input("> ") if"0"in choice or"1"in choice: how_much = int(choice) 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 are greedy bastard!")
defbear_room(): print("There is a bear here.") print("The bear has a 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
whileTrue: choice = input("> ")
if choice == "take honey": dead("The bear looks at you then slaps your face off.") elif choice == "taunt bear"andnot bear_moved: print("The bear has moved from the door.") print("You can go through it now.") bear_moved = True elif choice == "taunt bear"and bear_moved: dead("The bear gets pissed off and chews your leg off.") elif choice == "open door"and bear_moved: gold_room() else: print("I got no idea what that means.")
defcthulhu_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?")
choice = input("> ")
if"flee"in choice: start() elif"head"in choice: dead("Well that was tasty!") else: cthulhu_room()
defdead(why): print(why, "Good Job!") exit(0)
defstart(): print("You are in a dark room.") print("There is a door to your right and left.") print("Which one do you take?")
choice = input("> ")
if choice == "left": bear_room() elif choice == "right": cthulhu_room() else: dead("You stumble around the room until you starve.")
[sujx@zhangjiakou python]$ python ex38.py Wait there are not10 things in that list. Let's fix that. Adding: Boy There are 7 items now. Adding: Girl There are 8 items now. Adding: Banana There are 9 items now. Adding: Corn There are 10 items now. There we go: ['Apples', 'Orange', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn'] Let's do some things with stuff. Orange Corn Corn Banana Girl ApplesOrangeCrowsTelephoneLightSugarBoy Telephone#Light
# create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }
# create a basic set of states and some cities in them cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonvile' }
# add some more cities cities['NY'] = 'New York' cities['OR'] = 'PortLand'
# print out some cities print('-' * 10) print("NY State hae:", cities['NY']) print("OR State has: ",cities['OR'])
# print out some states print('-' * 10) print("Michigan's abbreviation is: ", states['Michigan']) print("Florida's abbreviation is: ", states['Florida'])
# do it by using the state then cities dict print('-' * 10) print("Michigan has: ", cities[states['Michigan']]) print("Florida has: ", cities[states['Florida']])
# print every state abbreviation print("-" * 10) for state, abbrev inlist(cities.items()): print(f"{state} is abbreviated {abbrev}")
# print every cities in state print("-" * 10) for abbrev, city inlist(cities.items()): print(f"{abbrev} has city {city}")
# now do both at the same time print("-" * 10) for state, abbrev inlist(states.items()): print(f"{state} state is abbreviated {abbrev}") print(f"and has city {cities[abbrev]}")
print("-" * 10) # safely get a abbreviation by state that might not be there state = states.get("Texas")
---------- NY State hae: New York OR State has: PortLand ---------- Michigan's abbreviation is: MI Florida's abbreviation is: FL ---------- Michigan has: Detroit Florida has: Jacksonvile ---------- CA is abbreviated San Francisco MI is abbreviated Detroit FL is abbreviated Jacksonvile NY is abbreviated New York OR is abbreviated PortLand ---------- CA has city San Francisco MI has city Detroit FL has city Jacksonvile NY has city New York OR has city PortLand ---------- Oregon state is abbreviated OR and has city PortLand Florida state is abbreviated FL and has city Jacksonvile California state is abbreviated CA and has city San Francisco New York state is abbreviated NY and has city New York Michigan state is abbreviated MI and has city Detroit ---------- Sorry,no Texas The city for the state 'TX'is: Does not Exist. [('CA', 'San Francisco'), ('MI', 'Detroit'), ('FL', 'Jacksonvile'), ('NY', 'New York'), ('OR', 'PortLand'), ('TX', 'Austin')] [('Oregon', 'OR'), ('Florida', 'FL'), ('California', 'CA'), ('New York', 'NY'), ('Michigan', 'MI'), ('Texas', 'TX')] ---------- Oregon state is abbreviated OR and has city PortLand Florida state is abbreviated FL and has city Jacksonvile California state is abbreviated CA and has city San Francisco New York state is abbreviated NY and has city New York Michigan state is abbreviated MI and has city Detroit Texas state is abbreviated TX and has city Austin
提高
模块、类和对象
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSong(object): def__init__(self, lyrics): self.lyrics = lyrics defsing_me_a_song(self): for line inself.lyrics: print(line)
happy_body = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"]) bulls_on_parade = Song(["They rally around the family" "With pockets full of shells"])
while current_scene !=last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name)
classDeath(Scene): quips = [ "You died. You kinda suck at this.", "Your mon would be pround...if she were smarter.", "Such a luser.", "I have a small puppy that's better at this.", "You're worse than your Dad's jokes." ] defenter(self): print(Death.quips[randint(0, len(self.quips)-1)]) exit(1)
classCentralCorridor(Scene): defenter(self): print(dedent(""" The Kaju have invaded your ship and destroyed your entire crew. """)) action = input(">> ")
if action == "shoot!": print(dedent(""" The Kaju eats you. """)) return'death' elif action == "dodge!": print(dedent(""" You wakup shortly after only to die as the Gothon stomps on your head and eats you. """)) return'death' elif action == "tell a joke": print(dedent(""" Gothon stops, tries not to laugh,then busts out laughing and can't move. """)) return'laser_weapon_armory' else: print("DOES NOT COMPUTE!") return'central_corridor'
classLaserWeaponArmory(Scene): defenter(self): print(dedent(""" There's a keypad lock on the box and you need the code to get the bomb out. If you get the code wrong 10 times then the lock closes forever and you can't get the bomb. The code is 3 digits. """)) code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}" guess = input("[keypad]>> ") guesses = 0 print(f"{code}")
while guess != code and guesses < 10: print("BzzzeDDD!") guesses += 1 guess = input("[keypad]>> ")
if guess == code: print(dedent(""" You grab the neutron bomb and run as fast as you can to the bridge. """)) return'the_bridge' else: print(dedent(""" The lock buzzes one last time and Gothons blow up the ship and you die. """)) return'death' classTheBridge(Scene): defenter(self): print(dedent(""" You brust onto the bridge.And There are 5 Gothons who are trying to kill you. """)) action = input(">> ") if action == "throw the bomb": print(dedent(""" You die konwing they will probably blow up when ti goes off. """)) return'death' elif action == "slowly place the bomb": print(dedent(""" Now that the bomb is placed you run to the escape pod to get off this tin can. """)) return'escape_pod' else: print("DOES NOT COMPUTE!") return"the_bridge" classEscapePod(Scene): defenter(self): print(dedent(""" There's 5 pods, which one do you take? """))
ifint(guess) != good_pod: print(dedent(""" You jump into pod {guess}. The pod escapes into the void of space.You die. """)) return'death' else: print(dedent(""" You win! """)) return'finished'
classFinished(Scene): defenter(self): print("You won! Good Job!") return'finished'