Learn Python The Hard Way(0--26)

This book's job is to teach you the three most essential skills that a beginning programmer needs to know: reading and writing, attention to detail, and spotting differences

Exercise 0: The Setup

If someone tells you to stop at a specific exercise in this book or to skip certain ones, you should ignore that person. Anyone trying to hide knowledge from you, or worse, make you get it from them instead of through your own efforts, is trying to make you depend on them for your skills. Don't listen to them and do the exercises anyway so that you learn how to educate yourself.

Exercise 1: A Good First Program

How do I get my country's language characters into my file?
Make sure you type this at the top of your file: # -- coding: utf-8 --.

some methods useful

Here's how you memorize things:

Tell yourself you will do it. Don't try to find tricks or easy ways out of it, just sit down and do it.
Write what you want to memorize on some index cards. Put one half of what you need to learn on one side, then another half on the other side.
Every day for about 15-30 minutes, drill yourself on the index cards, trying to recall each one. Put any cards you don't get right into a different pile, just drill those cards until you get bored, then try the whole deck and see if you improve.
Before you go to bed, drill just the cards you got wrong for about 5 minutes, then go to sleep.

some references useful
Unix Bash References
The shell you've been using is called Bash. It's not the greatest shell but it's everywhere and has a lot of features so it's a good start. Here's a short list of links about Bash you should go read:

Bash Cheat Sheet
http://cli.learncodethehardway.org/bash_cheat_sheet.pdf created by Raphael and CC licensed.
Reference Manual
http://www.gnu.org/software/bash/manual/bashref.html

Exercise 2: Comments and Pound Characters

# 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 a piece of code :
# print "This won't run."
print "This will run."
print "hi # there"

Exercise 3: Numbers and Math

+ plus
- minus
/ slash
* asterisk
% percent
< less-than
> greater-than
<= less-than-equal
>= greater-than-equal

Exercise 4: 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 avaliable."
print "There are only", drivers, "drivers avaliable."
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."

Exercise 5: More Variables and Printing

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)

String Formatting Operations

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

Here's an example, using a date:

>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

function learning
round(number[, ndigits]

Exercise 6: Strings and Text

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

What is the difference between %r and %s?
Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

unsolved : Explain why adding the two strings w and e with + makes a longer string.

Exercise 7: 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?
# that will print "." 10 times

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,      
# the comma is to show that the print is not end. And there will be a blank between the two strings
print end7 + end8 + end9 + end10 + end11 + end12

Couldn't you just not use the comma , and turn the last two lines into one single-line print?
Yes, you could very easily, but then it'd be longer than 80 characters, which in Python is bad style.

Exercise 8: Printing, Printing

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

Why does %r sometimes print things with single-quotes when I wrote them with double-quotes?
Python is going to print the strings in the most efficient way it can, not replicate exactly the way you wrote them. This is perfectly fine since %r is used for debugging and inspection, so it's not necessary that it be pretty.

Exercise 9: Printing, Printing, Printing

# Here's some new strange stuff, rember type it exactly

days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

# some differences among those follow sentences
print "Here are the days:", days
print "Here are the days: %r" % days
print "Here are the months:", months
print "Here are the months: %r" % months
print "Here are the months: %s" % months
print """
There's something going on here.
With the three double-quotes.
We'll be able to tyoe as much as we like.
Even 4 lines if we want, or 5, or 6.
"""

Exercise 10: What Was That?

high1 = "I am 6'2\" tall."  # escape double-quote inside string
high2 = 'I am 6\'2" tall.'  # escape single-quote inside string

tabby_cat = "\tI'm tabbled 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
ESCAPE              WHAT IT DOES.
\\                  Backslash (\)
\'                  Single-quote (')
\"                  Double-quote (")
\a                  ASCII bell (BEL)
\b                  ASCII backspace (BS)
\f                  ASCII formfeed (FF)
\n                  ASCII linefeed (LF)
\N{name}            Character named name in the Unicode database (Unicode only)
\r                  Carriage Return (CR)
\t                  Horizontal Tab (TAB)
\uxxxx              Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx          Character with 32-bit hex value xxxxxxxx (Unicode only)
\v                  ASCII vertical tab (VT)
\ooo                Character with octal value ooo
\xhh                Character with hex value hh

Exercise 11: Asking Questions

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)

#what we should see
$ python ex11.py
How old are you? 38
How tall are you? 6'2"
How much do you weigh? 180lbs
So, you're '38' old, '6\'2"' tall and '180lbs' heavy.

Related to escape sequences, try to find out why the last line has '6'2"' with that ' sequence. See how the single-quote needs to be escaped because otherwise it would end the string? YEP if you use %s to print, then you will see the result something like this

So, you're 20 old, 1'7" tall and 120 heavy.

function learning
raw_input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features.

We put a , (comma) at the end of each print line. This is so print doesn't end the line with a newline character and go to the next line.

Exercise 12: Prompting People

age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)

Study Drills
In Terminal where you normally run python to run your scripts, type pydoc raw_input. Read what it says. If you're on Windows try python -m pydoc raw_input instead.
Get out of pydoc by typing q to quit.
Look online for what the pydoc command does.
NOT FINISH
Use pydoc to also read about open, file, os, and sys. It's alright if you do not understand those; just read through and take notes about interesting things.

Exercise 13: Parameters, Unpacking, Variables

#This is how you add features to your script from the Python feature set. 
#The argv is the "argument variable".
#and This variable holds the arguments you pass to your Python script when you run it.

from sys import argv # we call these "features" that we import modules, like the sys module


#This line "unpacks" argv so that,rather than holding all the arguments, 
#it gets assigned to four variable you can work with
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

name = raw_input('YOUR NAME-->')
#The difference has to do with where the user is required to give input. 
#If they give your script inputs on the command line, then you use argv. 
#If you want them to input using the keyboard while the script is running, then use raw_input().

Exercise 14: Prompting and Passing

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 said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)


# We make a variable prompt that is set to the prompt we want, 
# and we give that to raw_input instead of typing it over and over.
# Now if we want to make the prompt something else, 
# we just change it in this one spot and rerun the script.
from sys import argv

script, user_name, user_words = argv
prompt = "->"

print "Hi %s, I'm %s, welcome to my world." % (user_name, script)
print "And I heard you say '%s', Isn't it?" % user_words
answer1 = raw_input(prompt)
print "So you say %r" % answer1
print "%s, I am tired now, may I just have a break?" % user_name
answer2 = raw_input(prompt)
print """
Acturally, I don't care your opinion, 
cause I'm not that smart, 
my master don't know too much to improve my brain, 
so %s, GOOD BYE!
""" % user_name

Exercise 15: Reading Files

#The solution is to use argv or raw_input 
#to ask the user what file to open (In this case, I create two files, ex15_sample.txt and ex15_sample01.txt)
#instead of "hard coding" the file's name.

from sys import argv        # import module argv

script, filename = argv     
# unpack argv, argv gets assigned to 2 variables

txt = open(filename)       
# function open, return file object and give it to txt. 
#You just open a file.

print "Here's your file %r:" % filename
print txt.read() 
# a function on txt named read. and print the file txt point to.
# give a file a command by using the dot, 
# the name of the command, and parameters.

txt.close() #It's important to close files when you are done with them

print "Type the filename again:"
file_again = raw_input("> ")    
# prompt with users, and ask which file he/she wants to open.

txt_again = open(file_again)
# func open, return file object and give it to txt_again

print txt_again.read()
# a function on txt named read. and print the file txt point to.

txt_again.close()

open(name[, mode[, buffering]])

Study Drills
Start python to start the python shell, and use open from the prompt just like in this program. Notice how you can open files and run read on them from within python? SOMETHING like that:

[alex@EX Learn-Python]$ py
Python 2.7.10 (default, Sep  7 2015, 13:51:49) 
[GCC 5.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> txt = open('ex15_sample.txt')
>>> print txt.read()
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

Why is there no error when we open the file twice?
Python will not restrict you from opening a file more than once and sometimes this is necessary.

Exercise 16: Reading and Writing Files

ALL sorts of commands (methods/functions) you can give to files.

  • 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 CRTL-C(^C)."
print "If you do want, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

# The file  will be truncated when opened for writing.
# SO you don't really need the target.truntcate().
#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")

# There's too much repetition in this file. 
# Use strings, formats, and escapes to print out line1, line2, and line3 
# with just one target.write() command instead of six.
line = "%s\n%s\n%s\n" % (line1, line2, line3)
target.write(line)

print "And finally, we close it."
target.close()

What modifiers to the file modes can I use?
The most important one to know for now is the + modifier, so you can do 'w+', 'r+', and 'a+'. This will open the file in both read and write mode, and depending on the character use position the file in different ways.

Exercise 17: More Files

Now let's do a few more things with files. We'll write a Python script to copy one file to another.

from sys import argv
from os.path import exists  
# exists returns True if a file exists, 
# based on its name in a string as an argument.
# It returns False if not.

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()
indata = open(from_file).read() # You don't need to do in_file.close()
#  It should already be closed by Python once that one line runs.

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

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

# we could do these two on one line, how?
#out_file = open(to_file, 'w')
#out_file.write(indata)
open(to_file, 'w').write(indata)

print "Alright, all done."

#out_file.close()
#in_file.close()

Exercise 18: Names, Variables, Code, Functions

# this one is like your scripts with argv
def print_two(*args):       # *args aka asterisk args  : aka colon
    arg1, arg2 = args       # unpacks the arguments
    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()

What's allowed for a function name?
The same as variable names. Anything that doesn't start with a number, and is letters, numbers, and underscores will work.
What does the * in *args do?
That tells Python to take all the arguments to the function and then put them in args as a list. It's like argv that you've been using, but for functions. It's not normally used too often unless specifically needed.

Exercise 19: Functions and Variables

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)

This shows all the different ways we're able to give our function cheese_and_crackers the values it needs to print them. We can give it straight numbers. We can give it variables. We can give it math. We can even combine math and variables.

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)

print "I can ask the user for the numbers of cheese and crackers:"
cheese_and_crackers(int(raw_input("the first argument-->")), int(raw_input("the second argument-->")))

Exercise 20: Functions and Files

from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)  # move to the start of the file

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 += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

Research online what the seek function for file does. Try pydoc file and see if you can figure it out from there. Then try pydoc file.seek to see what seek does.

file.seek

file.seek = seek(...)
    seek(offset[, whence]) -> None.  Move to new file position.
    
    Argument offset is a byte count.  Optional argument whence defaults to
    0 (offset from start of file, offset should be >= 0); other values are 1
    (move relative to current position, positive or negative), and 2 (move
    relative to end of file, usually negative, although many platforms allow
    seeking beyond the end of a file).  If the file is opened in text mode,
    only offsets returned by tell() are legal.  Use of other offsets causes
    undefined behavior.
    Note that not all file objects are seekable.

What is f in the print_all and other functions?
The f is a variable just like you had in other functions in Exercise 18, except this time it's a file. A file in Python is kind of like an old tape drive on a mainframe, or maybe a DVD player. It has a "read head," and you can "seek" this read head around the file to positions, then work with it there. Each time you do f.seek(0) you're moving to the start of the file. Each time you do f.readline() you're reading a line from the file, and moving the read head to right after the \n that ends that line.

How does readline() know where each line is?
Inside readline() is code that scans each byte of the file until it finds a \n character, then stops reading the file to return what it found so far. The file f is responsible for maintaining the current position in the file after each readline() call, so that it will keep reading each line.

Why are there empty lines between the lines in the file?
The readline() function returns the \n that's in the file at the end of that line. Add a , at the end of your print function calls to avoid adding double \n to every line.

Exercise 21: Functions Can Return Something

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))))
what_2 = multiply(iq, divide(multiply(age, weight), height))
what_3 = add(24, subtract(divide(34, 100), 1023))
print "That becomes: ", what, "Can you do it by hand?"
print "That becomes: ", what_2, "Can you do it by hand?"
print "That becomes: ", what_3, "Can you do it by hand?"

Exercise 22: What Do You Know So Far?

I'm going to have you do a review of what you have learned so far.

First, go back through every exercise you have done so far and write down every word and symbol (another name for "character") that you have used. Make sure your list of symbols is complete.

print
import
round
raw_input
from sys import argv
from os.path import exists
open(filename)
file.read()
file.close()
file.write()
def
file.readline()
file.seek()

Next to each word or symbol, write its name and what it does. If you can't find a name for a symbol in this book, then look for it online. If you do not know what a word or symbol does, then read about it again and try using it in some code.

You may run into a few things you can't find out or know, so just keep those on the list and be ready to look them up when you find them.

Once you have your list, spend a few days rewriting the list and double-checking that it's correct. This may get boring but push through and really nail it down.

Once you have memorized the list and what they do, then step it up by writing out tables of symbols, their names, and what they do from memory. If you hit some you can't recall from memory, go back and memorize them again.

Exercise 23: Read Some Code

The goal isn't to get you to understand code, but to teach you the following three skills:

  1. Finding Python source code for things you need.
  2. Reading through the code and looking for files.
  3. Trying to understand code you find.

Here's what you do:

  1. Go to bitbucket.org, github.com, or gitorious.org with your favorite web browser and search for "python."
  2. Pick a random project and click on it.
  3. Click on the Source tab and browse through the list of files and directories until you find a .py file.
  4. Start at the top and read through the code, taking notes on what you think it does.
  5. If any symbols or strange words seem to interest you, write them down to research later.

I read 4 simple codes

  1. array_generator

"""
HOW IT WORKS:
$ python array_generator.py
    Enter the array name:
    >  name
    Enter your string:
    >  array filled with the splitted string 
  Result:
    Array name
    name = ['array', 'filled', 'with', 'the', 'splitted', 'string']
"""

name = raw_input("\nEnter the name of your array.\n>")
items = raw_input("\nEnter your strings.\n>")
array = items.split()
print "\n\nArray name: ", name
print name, " = ", array
"""
WHAT I Have Learned

string.split = split(s, sep=None, maxsplit=-1)
    split(s [,sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string s, using sep as the
    delimiter string.  If maxsplit is given, splits at no more than
    maxsplit places (resulting in at most maxsplit+1 words).  If sep
    is not specified or is None, any whitespace string is a separator.
    
    (split and splitfields are synonymous)
"""
  1. dnsmap.py
"""
Based on WebMap: https://github.com/4rsh/python/blob/master/webmap.py
DNSMap - Developed by Arsh Leak.
$ wget https://github.com/4rsh/
"""

# Colours
D  = "\033[0m";  
W  = "\033[01;37m";  
O  = "\033[01;33m"; 
SUCESS = "\033[01;32m";
FAIL = "\033[01;31m";

import socket
import sys
import os
os.system("clear")
print O+ "+----------------------------------------------------------------------------+"
print "|                                      DNSMap                                |"
print "+----------------------------------------------------------------------------+"
print "|                            Development by Arsh Leak.                       |"
print "|                         $ Wget > http://github.com/4rsh                    |"
print "+----------------------------------------------------------------------------+"
print W+""
domain = raw_input("Set domain: ") # www.domain.com
 
try:
    ip = socket.gethostbyname( domain )
 
except socket.gaierror:         # NOT VERY UNDERSTAND
    print FAIL+'Invalid Domain.\n\n\n\n\n\n\n'
    sys.exit()
print SUCESS+"+-------------------------+"
print SUCESS+"| DNS   : " +ip+ "     |"
print SUCESS+"+-------------------------+"
"""
What I have learnd
socket.gethostbyname = gethostbyname(...)
    gethostbyname(host) -> address
    
    Return the IP address (a string of the form '255.255.255.255') for a host.
"""
  1. goodluck.py
# coding: utf-8

"""
Good Luck or Not. — Developed by Arsh Leak.
$ wget https://github.com/4rsh/
"""
import random
import time
import os
os.system("clear")  # clear the terminal screen

sorte   =   ["yes", "nope"]

print "Good luck... or not.\n\n"
time.sleep(5.5)
if (random.choice(sorte)) == sorte[0]:
    print "You're in luck!"
else:
    print "You're outta luck."

# Enjoy, Arsh Leak.

"""
WHAT I have Learned
random.choice = choice(self, seq) method of random.Random instance
    Choose a random element from a non-empty sequence.

time.sleep = sleep(...)
    sleep(seconds)

    Delay execution for a given number of seconds. The argument may be
    a floating point number for subsecond precision.
"""
  1. know.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Know your PC — The machine settings.
Developed by Arsh Leak (https://github.com/4rsh/)
"""

import os
os.system("clear")
print " _____                                     _____ _____ "
print "|  |  |___ ___ _ _ _    _ _ ___ _ _ ___   |  _  |     |"
print "|    <    | . | | | |  | | | . | | |  _|  |   __|   --|"
print "|__|__|_|_|___|_____|  |_  |___|___|_|    |__|  |_____|"
print "                       |___| Developed by Arsh Leak     "
print "KNOW YOUR PC:\n"
print "[ the network node hostname: ]"
os.system("uname -n\n")
print "\n[ kernal name: ]"
os.system("uname -s")
print "\n[ kernel version: ]"
os.system("uname -v")
os.system("uname -r")
print "\n[ OS: ]"
os.system("uname -o")
print "\n[ machine hardware name: ]"
os.system("uname -m")
print "\n[ processador: ]"
os.system("uname -p")
print "\n[ hardware plataform: ]"

"""
WHAT I have Learned

os.system("uname -i")
os.system = system(...)
    system(command) -> exit_status
    
    Execute the command (a string) in a subshell.
"""

Exercise 24: More Practice

print "Let's practice everything."
print 'You\'d need to know \' bout escape 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   # return 3 values


start_point = 10000
beans, jars, crates = secret_formula(start_point)   
# unpack 3 values, if you delete the 'crates', you will get an error
# ValueError: too many values to unpack
# apparently, if you give more than 3 values to unpack, you will get another error
# ValueError: need more than 3 values to unpack


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)       
# unpack 3 values, if you delete a '%d', then you will get an error
# TypeError: not all arguments converted during string formatting

Why do you you call the variable jelly_beans but the name beans later?
That's part of how a function works. Remember that inside the function the variable is temporary. When you return it then it can be assigned to a variable for later. I'm just making a new variable named beans to hold the return value.

Exercise 25: Even More Practice

def break_words(stuff):         # stuff is string
    """This function will break up words for us."""
    words = stuff.split(' ')    # words is list of strings
    # string.split = split(s, sep=None, maxsplit=-1)
    #    split(s [,sep [,maxsplit]]) -> list of strings
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)        # return a sorted list
    # sorted(...)
    #    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

def print_first_word(words):    # words is a list
    """Prints the first word after popping it off."""
    word = words.pop(0)        
    #list.pop = pop(...)
    #   L.pop([index]) -> item -- remove and return item at index (default last).
    #   Raises IndexError if list is empty or index is out of range.
    print word

def print_last_word(words):     # words is a list
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print word

def sort_sentence(sentence):    # sentence is a string

    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)   # words is a list of the string
    return sort_words(words)        # return a sorted list

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 int the sentence then print the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

Your output should look like mine, and after the > character (called the prompt) you can type Python code in and it will run immediately. Using this I want you to type each of these lines of Python code into python and see what it does:

import ex25
sentence = "All good things come to those who wait."
words = ex25.break_words(sentence)
words
sorted_words = ex25.sort_words(words)
sorted_words
ex25.print_first_word(words)
ex25.print_last_word(words)
words
ex25.print_first_word(sorted_words)
ex25.print_last_word(sorted_words)
sorted_words
sorted_words = ex25.sort_sentence(sentence)
sorted_words
ex25.print_first_and_last(sentence)
ex25.print_first_and_last_sorted(sentence)

Try doing this: help(ex25) and also help(ex25.break_words). Notice how you get help for your module, and how the help is those odd """ strings you put after each function in ex25? Those special strings are called documentation comments and we'll be seeing more of them.
Typing ex25. is annoying. A shortcut is to do your import like this: from ex25 import * which is like saying, "Import everything from ex25." Programmers like saying things backward. Start a new session and see how all your functions are right there.

Exercise 26: Congratulations, Take a Test!

easy one.

转载于:https://www.cnblogs.com/ice-mj/p/4896536.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值