学习Python

《learn python the hard way》

Posted by Haiming on July 23, 2019

Yes.

Learn Python the hard way.

So this blog is a studying note for me to record things I think important or difficult :) And also a place for me to write down my own thinking.

Let’s Go!

Codes:https://github.com/Timzhouyes/LearnPythonTheHardWay

The Hard way is easier

3 essential skills of coding:

  1. Reading and writing
  2. Attention to detail:such as corner case
  3. Spotting differences

Ex3. Numbers and Math

The order of operations:

  1. Parentheses(圆括号)
  2. Exponents(指数)
  3. Multiplication
  4. Devision
  5. Addition
  6. Subtraction

Ex5. More variables and printing

This exercise taught how to make format in strings.

Just put format like:

print(f"This is for formatting string like {this.variable}")

And also there is format like:

filling_in=False
joke_blank="Here is a blank for people to {}"
print(joke_blank.format(filling_in))

So the method.format() can join 2 strings or variables to one.

And if you put more blanks in a sentence, can just fill the blanks one by one like this:

filling_in=False
joke_blank="Here is a blank for people to {},{}"
print(joke_blank.format(filling_in,filling_in))

Output like this:

Here is a blank for people to False,False

Ex7. More printing

In this section, author gave us a method of print things in one line:

end1="C"
end2="h"
end3="e"
end4="e"
end5="s"
end6="e"

print(end1+end2,end=' ')
print(end3+end4)

The output of this section is:

Ch ee

So we can see all things in one line and be split by “ “ Also can change a little:

print(end1+end2,end=',')
print(end3+end4)

Output:

Ch,ee

Ex10. Escape cases

1563928390978

The mainly thing use is to put a \ before a symbol to input the symbol itself

Ex13. Parameters,Unpacking,Variables

In Python we also can do a “script”, I mean that we can take the .py file like a ‘method’ ,and then give it parameters. Then in the command line, we can just give arguments to a file, then output it.

To achieve this, we first do:

from sys import argv

Here the ‘argv’ is a abbr. of argument variable.

And here is something we need to concern: after the python command, the first argument always the name of file. Here is example.

from sys import argv

script1, first, second, third = argv

print("The script1 is called:", script1)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

My input in the command line is:

python ex13.py first 2nd 3rd\

And output always like this:

The script1 is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd\

Can see that the first argument always going to the name of the file.

Warning: If amount of parameter is wrong, there will be a warning message like:

ValueError: not enough values to unpack (expected 4, got 1)

So check your input again then do it.

Some thoughts:

This function gave the module ability of ‘initialize’, to give some parameters at first before the program really start.

Ex15.Reading files

Reading files consists of 2 steps:

  1. open(filename) to open a file, in the example the filename is ex15_sample.txt
  2. Use read() to read the contains of this file then can use print() to show it.
  3. Use close() to close the file you do any operation.

Here are codes:

from sys import argv

script,filename=argv

txt=open(filename)

print(f"here is the file name:{filename}")
print(txt.read())

print("Enter the name of file you wanna open")
file_again=input(">")
txt_again=open(file_again)
print(txt_again.read())

Some questions

  1. What does txt=open(filename) do in this file?

    It makes something called a file object. It is like insert a VCD to a VCD Player.

Ex16. Reading and Writing Files

Here are some methods of doing operations on files:

  1. close: Closes these files. Like File->Save in editor
  2. read: Reads the contents of a file. Like assign results to a variable
  3. readline: Reads just one line of file
  4. truncate:Empties the file. Watch out when you care of the file
  5. write(‘stuff’): Writes “stuff” to the file.
  6. seek(0):Moves the read/write location to the beginning of file.

Here are examples of the code:

# This file is for Reading and Writing files.

from sys import argv

script,filename=argv

print(f"We are going to erase the{filename}")
print("If you don't want to do it, hit CTRL-C")
print("If you want to do it, hit RETURN")

input("?")

print("Opening file ")
# Notice the "w" in next line.
target=open(filename,"w")

print("Truncating the file. Goodbye!")
target.truncate()

print("Now I am asking you for 3 lines")
line1=input("Line 1")
line2=input("Line 2")
line3=input("Line 3")

print("I am 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("Finally we close it")
target.close()

Output:

We are going to erase theex15_sample.txt
If you don't want to do it, hit CTRL-C
If you want to do it, hit RETURN
?
Opening file
Truncating the file. Goodbye!
Now I am asking you for 3 lines
Line 1Here is Line 1
Line 2HEre is line 2
Line 3here is line 3
I am going to write these to the file.
Finally we close it

In this script I use open(), write() ,and close() together to do operation to a file.

Ex18. Names,Variables,Code,Functions

So in this section finally we go to a chapter which contains the functions in Python.

A standard format is:

def function_name(*args):
    print(f"So your input is {args}")

Important points:

  1. What does the * in *args do?

    It just take all arguments to the function and then put them in args as a list.

Ex23.Strings, Bytes,and Character encodings

Use encode() to encode things into UTF code, then use decode() to change UTF code to the character itself.

DBES mnemonic: Decode Bytes, Encode Strings

Ex44. Inheritance Versus Composition

Three ways for parent and child classes can interact:

  1. Actions on the child imply an action on parent
  2. Actions on the child override the action on the parent
  3. Actions on the child alter the action on parent

1. Child imply on parent:

class Parent(object):
    def implicit(self):
        print("PARENT implicit")
class Child(Parent):
    pass

dad=Parent()
son=Child()

dad.implicit()
son.implicit()

In this part all behaviors of child are from parent.

2. Child override action on parent

class Parent(object):
    def override(self):
        print("PARENT override")

class Child(Parent):
    def override(self):
        print("CHILD override")

dad=Parent()
son=Child()

dad.override()
son.override()

Output:

PARENT override
CHILD override

So we can see that override() function from child is different from the function of parent.

3. Child alter action on parent

class Parent(object):
    def altered(self):
        print("PARENT altered()")


class Child(Parent):
    def altered(self):
        print("CHILD,BEFORE PARENT altered()")
        super(Child, self).altered()
        print("CHILD,AFTER PARENT altered()")

dad=Parent()
son=Child()

dad.altered()
son.altered()

Output:

PARENT altered()
CHILD,BEFORE PARENT altered()
PARENT altered()
CHILD,AFTER PARENT altered()

4. ‘Has a ‘ relationship

class other(object):
    def override(self):
        print("OTHER override")

    def implicit(self):
        print("OTHER implicit")

    def altered(self):
        print("OTHER altered")


class Child(object):
    def __init__(self):
        self.other = other()

    def implicit(self):
        self.other.implicit()

    def override(self):
        print("CHILD override")

    def altered(self):
        print("CHILD BEFORE OTHER altered()")
        self.other.altered()
        print("CHILD,AFTER OTHER altered()")

son=Child()

son.implicit()
son.altered()
son.override()

Output:

OTHER implicit
CHILD BEFORE OTHER altered()
OTHER altered
CHILD,AFTER OTHER altered()
CHILD override

So this part is a ‘has-a’ relationship, class Child() has a class Other()