jackjindtnt / KI

Ki
0 stars 0 forks source link

Python #9

Open jackjindtnt opened 7 years ago

jackjindtnt commented 7 years ago

----- set env -----

!/usr/bin/env python

-------- Lesson 1 : hello world ------------ print "Hello World!" print "Hello Again" print "I like typing this." print "This is fun." print 'Yay! Printing.' print "I'd much rather you 'not'." print 'I "said" do not touch this.'

--------- Lesson 2 : Number and Math ----------- 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 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

----------------- LESSON 3 : Variables and Names ---------------------- 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, "in each car."

jackjindtnt commented 7 years ago

------------- LESSON 4 : MORE VARIABLES ------------

my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown'

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 that's 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)

--------------- LESSON 5 : STRING AND TEXTS ---------------------------------------- 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 funny?! %r"

print joke_evaluation % hilarious

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

print w + e

--------------------------- LESSON 6: MORE PRINTING --------------------- print "Mary had a little lamb." print "Its fleece was white as %s." % 'snow' print "And everywhere that Mary went." print "." * 10 # 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 removing it to see what happens

print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 + end12

--------------------- LESSON 7 : PRINTING ---------------------- 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. """

jackjindtnt commented 7 years ago

--------------- LESSON : READING FILE-------------------------------- from sys import argv

script, filename = 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()

----------------- LESSON : PARAMETER --------------------

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

------------------- LESSON : ASKING ----------------------------- 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)

------------------------ LESSON : READING AND WRITING FILE --------------------- close -- Closes the file. Like File->Save.. in your editor. read -- Reads the contents of the file. You can assign the result to a variable. readline -- Reads just one line of a text file. truncate -- Empties the file. Watch out if you care about the file. write('stuff') -- Writes "stuff" to the file.


from sys import argv

script, filename = argv

print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN."

raw_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."

line1 = raw_input("line 1: ") line2 = 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()

------------------------ LESSON : MORE FILE ----------------------------------- 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, how?

in_file = open(from_file) indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file) print "Ready, hit RETURN to continue, CTRL-C to abort." raw_input()

out_file = open(to_file, 'w') out_file.write(indata)

print "Alright, all done."

out_file.close() in_file.close()

jackjindtnt commented 7 years ago

------------------ LESSON : NAME , VARIABLES , FUNCTION , CODE ----------------------------

this one is like your scripts 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 "I got nothin'."

print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none()


First we tell Python we want to make a function using def for "define". On the same line as def we give the function a name. In this case we just called it "print_two" but it could also be "peanuts". It doesn't matter, except that your function should have a short name that says what it does. Then we tell it we want *args (asterisk args) which is a lot like your argv parameter but for functions. This has to go inside () parentheses to work. Then we end this line with a : colon, and start indenting. After the colon all the lines that are indented four spaces will become attached to this name, print_two. Our first indented line is one that unpacks the arguments the same as with your scripts. To demonstrate how it works we print these arguments out, just like we would in a script.

------------------------ LESSON : FUNCTION AND VARIABLE ------------------------

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 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

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)

--------------------------- LESSON : FUNCTION AND FILES -------------------------- 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 "Now let's rewind, kind of like a tape."

rewind(current_file)

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)

---------------------------- LESSON : FUNCTION CAN RETURN ST -------------------------------- 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 functions!"

age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

A puzzle for the extra credit, type it in anyway.

print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"


We are now doing our own math functions for add, subtract, multiply, and divide. The important thing to notice is the last line where we say return a + b (in add). What this does is the following:

Our function is called with two arguments: a and b. We print out what our function is doing, in this case "ADDING." Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them." Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.

jackjindtnt commented 7 years ago

------------------------ LESSON : PRACTICE ---------------------------

print "Let's practice everything." print 'You\'d need to know \'bout escapes with \ that do \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 and requires an explanation \n\t\twhere there is none. """

print "--------------" print poem 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 "We can also do that this way:" print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

jackjindtnt commented 7 years ago

---------------- LESSON : PRACTICE MORE ------------------------------------- def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words

def sort_words(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 after popping it off.""" word = words.pop(-1) print word

def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words)

def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_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)

jackjindtnt commented 7 years ago

---------------------- LESSON : IF ---------------------------------------- people = 20 cats = 30 dogs = 15

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."

---------------------------- LESSON : IF - ELSE --------------------------------------

In the last exercise you worked out some if-statement and then tried to guess what they are and how they work. Before you learn more I'll explain what everything is by answering the questions you had from Study Drills. You did the Study Drills right?

What do you think the if does to the code under it? An if-statement creates what is called a "branch" in the code. It's kind of like those choose your own adventure books where you are asked to turn to one page if you make one choice, and another if you go a different direction. The if-statement tells your script, "If this boolean expression is True, then run the code under it, otherwise skip it." Why does the code under the if need to be indented four spaces? A colon at the end of a line is how you tell Python you are going to create a new "block" of code, and then indenting four spaces tells Python what lines of code are in that block. This is exactly the same thing you did when you made functions in the first half of the book. What happens if it isn't indented? If it isn't indented, you will most likely create a Python error. Python expects you to indent something after you end a line with a : (colon). Can you put other boolean expressions from Exercise 27 in the if-statement? Try it. Yes you can, and they can be as complex as you like, although really complex things generally are bad style. What happens if you change the initial values for people, cats, and dogs? Because you are comparing numbers, if you change the numbers, different if-statements will evaluate to True and the blocks of code under them will run. Go back and put different numbers in and see if you can figure out in your head which blocks of code will run. Compare my answers to your answers, and make sure you really understand the concept of a "block" of code. This is important for when you do the next exercise where you write all the parts of if-statements that you can use.


people = 30 cars = 40 trucks = 15

if cars > people: print "We should take the cars." elif cars < people: print "We should not take the cars." else: print "We can't decide."

if trucks > cars: print "That's too many trucks." elif trucks < cars: print "Maybe we could take the trucks." else: print "We still can't decide."

if people > trucks: print "Alright, let's just take the trucks." else: print "Fine, let's stay home then."

-------------------------------- LESSON : IF ------------------------------------------------- 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 at Cthulhu's retina." print "1. Blueberries." print "2. Yellow jacket 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!"

------------------------- LESSON : FOR - LOOP ------------------------------------------ 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 what's in it

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

append 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

------------------------------- LESSON : WHILE ------------------------------------ Here's the problem with while-loops: Sometimes they do not stop. This is great if your intention is to just keep looping until the end of the universe. Otherwise you almost always want your loops to end eventually.

To avoid these problems, there are some rules to follow:

Make sure that you use while-loops sparingly. Usually a for-loop is better. Review your while statements and make sure that the boolean test will become False at some point. When in doubt, print out your test variable at the top and bottom of the while-loop to see what it's doing.


i = 0 numbers = []

while i < 6: 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

----------------------------- LESSON : BRANCH AND FUNCTION ------------------------------

from sys import exit

def gold_room(): print "This room is full of gold. How much do you take?"

choice = raw_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 greedy bastard!")

def bear_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

while True:
    choice = raw_input("> ")

    if choice == "take honey":
        dead("The bear looks at you then slaps your face off.")
    elif choice == "taunt bear" and not bear_moved:
        print "The bear has moved from the door. 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."

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?"

choice = raw_input("> ")

if "flee" in choice:
    start()
elif "head" in choice:
    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?"

choice = raw_input("> ")

if choice == "left":
    bear_room()
elif choice == "right":
    cthulhu_room()
else:
    dead("You stumble around the room until you starve.")

start()

jackjindtnt commented 7 years ago

------------------------ LESSON : DEBUG ---------------------------- Rules for If-Statements

Every if-statement must have an else. If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors. Never nest if-statements more than two deep and always try to do them one deep. Treat if-statements like paragraphs, where each if-elif-else grouping is like a set of sentences. Put blank lines before and after. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable. If you follow these simple rules, you will start writing better code than most programmers. Go back to the last exercise and see if I followed all of these rules. If not, fix my mistakes.

Rules for Loops

Use a while-loop only to loop forever, and that means probably never. This only applies to Python; other languages are different. Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.