用《“笨办法”学Python3》时敲的代码

还没看完..这目前是前35习题的。

  1 '''
  2 print("Hello World!")
  3 print("Hello Again")
  4 
  5 print("I like typing this.")
  6 print("This is fun.")
  7 print("Yay!Printing")
  8 print("I'd much rather you 'not'")
  9 print('I "said" do not touch this')
 10 '''
 11 '''
 12 print("I will now count my chickens:")
 13 print("Hens",25+30/6)
 14 print("Roosters",100.0-25*3%4)
 15 
 16 print("Now I will count the eggs:")
 17 print("3+2+1-5+4%2-1/4+6")
 18 print("Is it true that 3+2<5-7?")
 19 
 20 print(3+2<5-7)
 21 
 22 print("What is 3+2?",3+2)
 23 print("What is 5-7?",5-7)
 24 
 25 print("Oh,that's why it's False.")
 26 print("How about some more.")
 27 
 28 print("Is it greater?",5>-2)
 29 print("Is it greater or equal?",5>=-2)
 30 print("Is it less or equal?",5<=-2)
 31 '''
 32 '''
 33 测试
 34 #coding=utf-8
 35 '''
 36 '''
 37 cars=100
 38 space_in_a_car=4
 39 drivers=30
 40 passengers=90
 41 cars_not_driven=cars-drivers
 42 cars_driven=drivers
 43 carpool_capacity=cars_driven*space_in_a_car
 44 average_passengers_per_car=passengers/cars_driven
 45 
 46 print("There are",cars,"cars available.")
 47 print("There are only",drivers,"drivers are available.")
 48 print("There will be",cars_not_driven,"empty cars today.")
 49 print("We can transport",carpool_capacity,"people today.")
 50 print("We have",passengers,"to carpool today.")
 51 print("We need to put about",average_passengers_per_car,"in each car.")
 52 '''
 53 '''
 54 my_name = 'Zed A. Shaw'
 55 my_age = 35 #not a lie [my_name]
 56 my_height = 74 #inches
 57 my_weight = 180 #lbs
 58 my_eyes = 'Blue'
 59 my_teeth = 'White'
 60 my_hair = 'Brown'
 61 
 62 print(f"Let's talk about {my_name}.")
 63 print(f"He's {my_height} inches tall.")
 64 print(f"He's {my_weight} pounds heavy.")
 65 print("Actually that's not too heavy.")
 66 print(f"He's got {my_eyes} eyes and {my_hair} hair.")
 67 print(f"Gis teeth are usually {my_teeth} depending on the coffee.")
 68 
 69 #This line is tricky,try to get it exact
 70 total = my_age+my_height+my_weight
 71 print(f"If I add {my_age},{my_height} and {my_weight} I get {total} .")
 72 '''
 73 #如何将浮点数四舍五入  round(number)
 74 '''
 75 a = 1.99
 76 print(f"1.99 is {a},四舍五入为{round(a)}")
 77 '''
 78 '''
 79 types_of_people = 10
 80 x= f"There are {types_of_people} types of people."
 81 
 82 binary = "binary"
 83 do_not = "don't"
 84 y = f"Those who know {binary} and those who {do_not} ."
 85 
 86 print(x)
 87 print(y)
 88 print(f"I said {x}")
 89 print(f"I also said {y}")
 90 
 91 hilarious = True
 92 joke_evaluation = "Isn't that joke so funny?! {}"
 93 
 94 print(joke_evaluation.format(hilarious))
 95 
 96 w = "This is the left side of ..."
 97 e = "a string with a right side."
 98 
 99 print(w+e)
100 '''
101 '''
102 print("Mary had a little lamb ")
103 print("Its fleece was white as {}.".format('snow'))
104 print("And everywhere that Mary went.")
105 print("." * 10) #What'd that do?
106 
107 end1 = "C"
108 end2 = "h"
109 end3 = "e"
110 end4 = "e"
111 end5 = "s"
112 end6 = "e"
113 end7 = "B"
114 end8 = "u"
115 end9 = "r"
116 end10 = "g"
117 end11 = "e"
118 end12 = "r"
119 
120 #Watch that comma at the end .try removing it to see what happens
121 print(end1 + end2 + end3 + end4 + end5 + end6,end = ' ')
122 print(end7 + end8 + end9 + end10 + end11 + end12)
123 '''
124 '''
125 formatter = "{} {} {} {}"
126 print(formatter.format(1,2,3,4))
127 print(formatter.format("one","two","three","four"))
128 print(formatter.format(True,False,False,True))
129 print(formatter.format(formatter,formatter,formatter,formatter))
130 print(formatter.format(
131     "Try your",
132     "Own text here",
133     "Maybe a poem",
134     "Or a song about fear"
135 ))
136 '''
137 '''
138 #Here's some new strange stuff,remember type it exactly.
139 
140 days = "Mon Tue Wed Thu Fri Sat Sun"
141 months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
142 
143 print("Here are the days: ",days)
144 print("Here are the months: ",months)
145 
146 print("""
147 There's something going on here.
148 with the three double-quotes.
149 We'll be able to type as much as we like.
150 Even 4 lines if we want, or 5, or 6.
151 """)
152 '''
153 '''
154 tabby_cat = "\tI'm tabbed in."
155 persian_cat = "I'm split\non a line."
156 backslash_cat = "I'm \\ a \\ cat."
157 
158 fat_cat = """
159 I'll do a list:
160 \t* Cat food
161 \t* Fishies
162 \t* Catnip\n\t* Grass
163 """
164 
165 print(tabby_cat)
166 print(persian_cat)
167 print(backslash_cat)
168 print(fat_cat)
169 '''
170 '''
171 #print("How old are you?",end=' ')
172 age = input("How old are you?")
173 #print("How tall are you?",end=' ')
174 height = input("How tall are you?")
175 #print("How much do you weigh?",end=' ')
176 weight = input("How much do you weigh?")
177 
178 #age = age*6
179 print(f"So you're {age} old,{height} tall,{weight} heavy")
180 '''
181 '''
182 from sys import argv
183 script,first,second,third = argv
184 
185 print("The script is called:",script)
186 print("The first variable is:",first)
187 print("Your second variable is:",second)
188 print("Your third variable is:",third)
189 '''
190 '''
191 from sys import argv
192 
193 script,user_name = argv
194 prompt = '>'
195 
196 print(f"Hi {user_name},I'm the {script} script.")
197 print("I'd like to ask you a few questions.")
198 print(f"Do you like me {user_name}?")
199 likes = input(prompt)
200 
201 print(f"Where do you live {user_name}?")
202 lives = input(prompt)
203 
204 print("What kind of computer do you have?")
205 computer = input(prompt)
206 
207 print(f"""
208 Alright,so you said {likes} about liking me.
209 You live in {lives}.Not sure where that is.
210 And you have a {computer} computer.Nice.
211 """)
212 '''
213 '''
214 from sys import argv
215 
216 script,filename = argv
217 
218 txt = open(filename)
219 
220 print(f"Here's your file {filename}:")
221 print(txt.read())
222 
223 print("Type the filename again:")
224 file_again = input("> ")
225 
226 txt_again = open(file_again)
227 
228 print(txt_again.read())
229 txt.close()
230 txt_again.close()
231 '''
232 '''
233 from sys import argv
234 
235 script,filename = argv
236 
237 print(f"We're going to erase {filename}.")
238 print("If you don't want that,hit CTRL-C (^C).")
239 print("If you do want that,hit RETURN.")
240 
241 input("?")
242 
243 print("Opening the file...")
244 target = open(filename,'w')
245 
246 print("Truncating the file.Goodbye!")
247 target.truncate()
248 
249 print("Now I'm going to ask you for three details")
250 line1 = input("line 1: ")
251 line2 = input("line 2: ")
252 line3 = input("line 3: ")
253 
254 print("I'm going to write these to the file.")
255 
256 target.write(line1)
257 target.write("\n")
258 target.write(line2)
259 target.write("\n")
260 target.write(line3)
261 target.write("\n")
262 
263 print("And finally,we close it.")
264 target.close()
265 
266 target = open(filename,'r')
267 print(target.read())
268 print("That's all.")
269 '''
270 '''
271 from sys import argv
272 from os.path import exists
273 
274 script,from_file,to_file = argv
275 
276 print(f"Copying from {from_file} to {to_file}")
277 in_file = open(from_file)
278 indata = in_file.read()
279 
280 print(f"The input file is {len(indata)} bytes long")
281 print(f"Does the output file exist?{exists(to_file)}")
282 print("Ready,hit RETURN to continue,CTRL-C to abort.")
283 input()
284 
285 out_file =open(to_file,'w')
286 out_file.write(indata)
287 
288 print("Alright,all done.")
289 
290 out_file.close()
291 in_file.close()
292 '''
293 '''
294 #18--------------------------------
295 def print_two(*args):
296     arg1,arg2 = args
297     print(f"arg1:{arg1},arg2:{arg2}")
298 
299 def print_two_again(arg1,arg2):
300     print(f"arg1:{arg1},arg2:{arg2}")
301 
302 def print_one(arg1):
303     print(f"arg1:{arg1}")
304 
305 def print_none():
306     print("I got nothin'.")
307 
308 print_two("Zed","Shaw")
309 print_two_again("Zed","Shaw")
310 print_one("First!")
311 print_none()
312 #19--------------------------------
313 '''
314 '''
315 def cheese_and_crackers(cheese_count,boxes_of_crackers):
316     print(f"You have {cheese_count} cheese.")
317     print(f"You have {boxes_of_crackers} boxes of crackers.")
318     print("Man that's enough for a party.")
319     print("Get a blanket.\n")
320 
321 print("We can just give the function numbers directly:")
322 cheese_and_crackers(20,30)
323 
324 print("OR,we can use variables from our script:")
325 amount_of_cheese = 10
326 amount_of_crackers = 50
327 
328 cheese_and_crackers(amount_of_cheese,amount_of_crackers)
329 
330 print("We can even do math inside too:")
331 cheese_and_crackers(10+20,5+6)
332 
333 print("And we can combine the two,variables and math:")
334 cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
335 '''
336 '''
337 #20--------------------------------
338 from sys import argv
339 
340 script,input_file = argv
341 
342 def print_all(f):
343     print(f.read())
344 def rewind(f):
345     f.seek(0)
346 def print_a_line(line_count,f):
347     print(line_count,f.readline())
348 
349 current_file = open(input_file)
350 print("First let's print the whole file :\n")
351 print_all(current_file)
352 print("Now let's rewind,kind of like a tape.")
353 rewind(current_file)
354 
355 print("Let's print three lines:")
356 
357 current_line = 1
358 print_a_line(current_line,current_file)
359 
360 current_line = current_line + 1
361 print_a_line(current_line,current_file)
362 
363 current_line = current_line + 1
364 print_a_line(current_line,current_file)
365 '''
366 '''
367 #21--------------------------------
368 def add(a,b):
369     print(f"ADDING {a} + {b}")
370     return a+b
371 
372 def subtract(a,b):
373     print(f"SUBTRACTING {a} - {b}")
374     return a-b
375 
376 def multiply(a,b):
377     print(f"MULTIPLYING {a} * {b}")
378     return a*b
379 
380 def divide(a,b):
381    print(f"DIVIDING {a} / {b}")
382    return a/b
383 
384 print("Let's do some math with just functions!")
385 
386 age = add(30,5)
387 height = subtract(78,4)
388 weight = multiply(90,2)
389 iq = divide(100,2)
390 
391 print(f"Age:{age},Height:{height},Weight:{weight},IQ:{iq}")
392 
393 #A puzzle for the extra credit,type it in anyway
394 print("Here is a puzzle.")
395 what = add(age,subtract(height,multiply(weight,divide(iq,2))))
396 print("That becomes:",what,"Can you do it by hand?")k
397 '''
398 #23--------------------------------
399 '''
400 import sys
401 script,encoding,error = sys.argv
402 
403 def main(language_file,encoding,errors):
404     line = language_file.readline()
405 
406     if line:
407         print_line(line,encoding,errors)
408         return main(language_file,encoding,errors)
409 
410 def print_line(line,encoding,errors):
411     next_lang = line.strip()
412     raw_bytes = next_lang.encode(encoding,errors = errors)
413     cooked_string = raw_bytes.decode(encoding,errors =errors)
414 
415     print(raw_bytes,"<===>",cooked_string)
416 
417 languages = open("languages.txt",encoding = "utf-8")
418 
419 main(languages,encoding,error)
420 '''
421 '''
422 print("Let's practice everything.")
423 print('You\'d need to know \'bout escapes with \\ that do:')
424 print('\n new lines and \t tabs.')
425 
426 poem = """
427 \t The lovely World
428 with logic so firmly planted
429 cannot discern \n the needs of lovely
430 nor comprehend passion from intuition
431 and requires an explanation
432 \n\twhere there is none.
433 """
434 """
435 print("---------------")
436 print(poem)
437 print("---------------")
438 
439 five = 10 - 2 + 3 - 6
440 print(f"This should be five:{five}")
441 
442 def secret_formula(started):
443     jelly_beans = started * 500
444     jars = jelly_beans / 1000
445     crates = jars /100
446     return jelly_beans,jars,crates
447 
448 start_point = 10000
449 beans,jars,crates = secret_formula(start_point)
450 
451 # remember that this is another way to format a cooked_string
452 print("With starting point of :{}".format(start_point))
453 #it's just like with an f""string
454 print(f"We'd have {beans} beans,{jars} jars,and {crates} crates.")
455 
456 start_point = start_point /10
457 
458 print("We can also do that this way:")
459 formula = secret_formula(start_point)
460 #This is an easy way to apply a list to a format string
461 print("We'd have {} beans,{} jars,and {} crates.".format(*formula))
462 '''
463 '''
464 def break_words(stuff):
465     """This function will break up words for us."""
466     words = stuff.split(' ')
467     return words
468 
469 def sort_words(words):
470     """Sorts the words."""
471     return sorted(words)
472 
473 def print_first_word(words):
474     """Prints the first word after popping it off"""
475     word = words.pop(0)
476     print(word)
477 
478 def print_last_word(words):
479     """Prints the last word after popping it off."""
480     word = words.pop(-1)
481     print(word)
482 
483 def sort_sentence(sentence):
484     """Takes in a full sentence and returns the sorted words"""
485     words = break_words(sentence)
486     return sort_words(words)
487 
488 def print_first_and_last(sentence):
489     """Prints the first and last words of the sentence"""
490     words = break_words(sentence)
491     print_first_word(words)
492     print_last_word(words)
493 
494 def print_first_and_last_sorted(sentence):
495     """Sorts the words then prints the first and last one."""
496     words = sort_sentence(sentence)
497     print_first_word(words)
498     print_last_word(words)
499 '''
500 '''
501 print("How old are you?", end=' ')
502 age = input()
503 print("How tall are you?", end=' ')
504 height = input()
505 print("How much do you weigh?", end=' ')
506 weight = input()
507 
508 print(f"So, you're {age} old, {height} tall and {weight} heavy.")
509 '''
510 '''
511 from sys import argv
512 script, filename = argv
513 
514 txt = open(filename)
515 
516 print("Here's your file {filename}:")
517 print(txt.read())
518 
519 print("Type the filename again:")
520 file_again = input("> ")
521 txt_again = open(file_again)
522 print(txt_again.read())
523 '''
524 '''
525 print("Let\'s practice everything.")
526 print('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
527 
528 poem = """
529 \tThe lovely world
530 with logic so firmly planted
531 cannot discern \n the needs of love
532 nor comprehend passion from intuition
533 and requires an explanation
534 \n\t\twhere there is none.
535 """
536 
537 print("--------------")
538 print(poem)
539 print("--------------")
540 
541 
542 five = 10 - 2 + 3 - 6
543 print(f"This should be five: {five}")
544 
545 def secret_formula(started):
546     jelly_beans = started * 500
547     jars = jelly_beans / 1000
548     crates = jars / 100
549     return jelly_beans, jars, crates
550 
551 
552 start_point = 10000
553 beans, jars,crates = secret_formula(start_point)
554 
555 # remember that this is another way to format a string
556 print("With a starting point of: {}".format(start_point))
557 # it's just like with an f"" string
558 print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
559 
560 start_point = start_point / 10
561 
562 print("We can also do that this way:")
563 formula = secret_formula(start_point)
564 # this is an easy way to apply a list to a format string
565 print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
566 
567 people = 20
568 cats = 30
569 dogs = 15
570 
571 if people < cats:
572     print ("Too many cats! The world is doomed!")
573 
574 if people < cats:
575     print("Not many cats! The world is saved!")
576 
577 if people < dogs:
578     print("The world is drooled on!")
579 
580 if people > dogs:
581     print("The world is dry!")
582 
583 
584 dogs += 5
585 
586 if people >= dogs:
587     print("People are greater than or equal to dogs.")
588 
589 if people <= dogs:
590     print("People are less than or equal to dogs.")
591 
592 
593 if people == dogs:
594     print("People are dogs.")
595 '''
596 '''
597 people = 20
598 cats = 30
599 dogs = 15
600 
601 if people < cats:
602     print("Too many cats!The world is doomed!")
603 if people > cats:
604     print("Not many cats!The world is saved!")
605 if people < dogs:
606     print("The world is drooled on!")
607 if people > dogs:
608     print("The world is dry!")
609 
610 dogs += 5
611 if people >= dogs:
612     print("People are greater than or equal to dogs.")
613 if people <= dogs:
614     print("People are less than or equal to dogs.")
615 
616 if people == dogs:
617     print("People are dogs.")
618 '''
619 '''
620 people = 15
621 cars = 40
622 trucks = 15
623 
624 if cars> people:
625     print("We should take the cars.")
626 elif cars<people:
627     print("We should not take the cars.")
628 else:
629     print("We can't decide.")
630 
631 if trucks > cars:
632     print("That's too many trucks.")
633 elif trucks < cars:
634     print("Maybe we could take the trucks.")
635 else:
636     print("We still can't decide.")
637 
638 if people > trucks or people == trucks:
639     print("Alright,let's just take the trucks.")
640 else:
641     print("Fine, let's stay home then.")
642 '''
643 '''
644 print("""You enter a dark room with two doors.
645 Do you go through door #1 or door #2?""")
646 
647 door = input(">")
648 
649 if door == "1":
650     print("There's a giant bear here eating a cheese cake.")
651     print("What do you do ?")
652     print("1.Take a cake.")
653     print("2.Scream at the bear.")
654 
655     bear = input(">")
656 
657     if bear == "1":
658         print("The bear eats your face off.Good job!")
659     elif bear =="2":
660         print("The bear eats your legs off.Good job!")
661     else :
662         print(f"Well doing {bear} is probably better.")
663         print("Bear runs away.")
664 
665 
666 elif door == "2":
667     print("You stare into the endless abyss at Cthulhu's retina.")
668     print("1.Blueberries.")
669     print("2.Yellow jacket clothespins.")
670     print("3.Understand revovlvers telling melodies.")
671 
672     insanity = input(">")
673 
674     if insanity == "1" or insanity == "2":
675         print("Your body survives powered by a mind of jello.")
676         print("Good job!")
677     else :
678         print("The insanity rots your eyes into a pool of muck.")
679         print("Good job!")
680 yyh
681 else:
682     print("You stumble around and fall on a knife and die.Good job!")
683 '''
684 '''
685 the_count = [1,2,3,4,5]
686 fruits = ['apples','oranges','pears','apricots']
687 change = [1,'pennies',2,'dimes',3,'quarters']
688 
689 #This first kind of for-loop goes through a list
690 for number in the_count:
691     print(f"This is count {number}")
692 #same as above
693 for fruit in fruits:
694     print(f"A fruit of type :{fruit}")
695 #also we can go through mixed lists too
696 #notice we have to use {} since we don't know what's in it
697 for i in change:
698     print(f"I got {i}")
699 
700 #We can also build lists,first start with an empty one
701 elements=[]
702 #then use the range function to do 0 to 5 counts
703 
704 for i in fruits:
705     print(f"Adding {i} to the list.")
706     #append is a function that lists Understand
707     elements.append(i)
708 
709 #now we can print them too
710 
711 for i in elements:
712     print(f"elements was :{i}")
713 '''
714 '''
715 i=0
716 numbers = []
717 k=9
718 
719 while i<k:
720     print(f"At the top is {i}")
721     numbers.append(i)
722 
723     i=i+2
724     print("numbers now :",numbers)
725     print(f"At the bottom i is {i}")
726 
727 print("The numbers: ")
728 for num in numbers:
729     print(num)
730 
731 
732 animals = ['bear','tiger','penguin','zebra']
733 bear = animals[0]
734 i=0
735 
736 for animal in animals:
737     print(f"在位置{i}上的是第{i+1}只动物,是一只{animal}。")
738     i=i+1
739 
740 
741 from sys import exit
742 
743 def gold_room():
744     print("This room is full of gold. How much do you take?")
745 
746     choice = input("> ")
747     if "0" in choice or "1" in choice:
748         how_nuch = int (choice)
749     else:
750         dead("Man,learn to type a number.")
751 
752     if how_nuch < 50:
753         print("Nice,you're not greedy,you win!")
754         exit(0)
755     else:
756         dead("You greedy bastard!")
757 
758 def bear_room():
759     print("There is a bear here.")
760     print("The bear has a bunch of honey.")
761     print("The fat bear is in front of another door.")
762     print("How are you going to move the bear?")
763     bear_moved = False
764 
765     while True:
766         choice = input("> ")
767         if choice == "take honey":
768             dead("The bear looks at you then slaps your face off.")
769         elif choice == "taunt bear" and not bear_moved:
770             print("The bear has moved from the door.")
771             print("You can go through it now.")
772             bear_moved = True
773         elif choice == "taunt bear" and bear_moved:
774             dead("The bear gets pissed off and chews your leg off.")
775         elif choice == "open door" and bear_moved:
776             gold_room()
777         else:
778             print("I got no idea what that means.")
779 
780 def cthulhu_room():
781     print("Here you see the great evil Cthulhu.")
782     print("He , it, whatever stares at you and you go insane.")
783     print("Do you flee for your life or eat your head.")
784 
785     choice = input("> ")
786 
787     if "flee" in choice:
788         start()
789     elif "head" in choice:
790         dead("Well that was tasty!")
791     else:
792         cthulhu_room()
793 
794 def dead(why):
795     print(why,"Good job!")
796     exit(0)
797 
798 def start():
799     print("You are in dark room.")
800     print("There is a door to your right to left.")
801     print("Which one do you take?")
802 
803     choice = input("> ")
804 
805     if  choice == "left":
806         bear_room()
807     elif choice == "right":
808         cthulhu_room()
809     else:
810         dead("You stumble around the room until you starve.")
811 
812 start()
813 
814 
815 '''
View Code

猜你喜欢

转载自www.cnblogs.com/greenaway07/p/10665223.html