Python basic (from learn python the hard the way)

1. How to run the python file?

python ...py

 

2. UTF-8 is a character encoding, just like ASCII.

 

3. round(floating-point number)

 

4. %r print the way you write. It prints whatever you write, even if you have special characters, such as '\n'.

 

5. how to open a file?

from sys import argv

script, filename = argv
txt = open(filename)
print(txt.read())

ah = input(">")
print(ah.read())

  

6. how to edit a file?

from sys import argv
script, filename = argv
target = open(filename, 'w')  # open for writing, truncating the file first
target.truncate()
line1 = input()
line2 = input()
target.write(line1)
target.write("\n")
target.write(line2)
target.close()

  

6. copy a file

from sys import argv
from os.path import exists  # os.path is a module of python and we need to use its exists function

script, from_file, to_file = argv
print("Copying from %s to %s" % (from_file, to_file))
in_file = open(from_file);
indata = in_file.read() #write in one line: indata = open(from_file).read()
print("The input file is %d bytes long" % len(indata))   #return the number of bytes of indata
print("Does the output file exist? %r" % exists(to_file))

out_file = open(to_file, 'w')  #we need ot write the new file
out_file.write(indata)    #directly use indata file to write out_file
out_file.close()
in_file.close()

  

#much more easier one
open(argv[2], 'w').write(open(argv[1]).read())

  

7. functions in python

def print_two(*args):
    a, b = args
    print("haha %r, and %r" % (a, b))

def haha():
    print("mdzz")

print_two('a', 'b')
haha()

  

8. functions and files

from sys import argv

script, input_file = argv

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

def rewind(f):
    f.seek(0)  #seek function is file's function. It can represent the current position at the offset.
    #default is 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)

  

9. some function

#split(str, num) function
#return a list of all the words in the string
#use str as a sperate
#num represent the number of lines
w="123 456 789"
w.split() # result is ['123', '456', '789'], use the default mode
w.split(' ', 1) #result is ['123', '456 789']

#sorted() function
#It can be used to sort a string
w='acb'
w.sorted() #result is ['a', 'b', 'c']

#pop(i) function
#remove the item at the given postion in the list and return it
#if () is empty, we wiil remove and return the last item of the list
w=[1,2,3]
w.pop() #w=[1,2]
w.pop(0) #w=[2]

  

#If we are confused about a module,
#we can use help(module) to learn about it.
help(module)

  

10. if statement

#if-statement
if ... :
    #...
elif ... :
    #...
else :
    #...

  

11. for and list

a = [1, 2, 3] #list
b = [] #a mix list
for i in range(0, 5):
    print("%d" % i)
    b.append(i)
#range(a, b) is a, a+1, ... , b-1
#list.append(obj) add the obj to a list

  

12. while loop

a = input()
while int(a)>10:
    print(a)
    a = input()

  

13. with-as

#with-as statement is a control-flow structure.
#basic structure is
#with expression [as variable]:
#     with-block
#It can used to wrap the excution of a block with method defined by a context manager.
#expression is represented a class. In the class, we must have two functions.
#One is __enter__(), the others is __exit__().
#The variable is equal to the return of __enter__(). If we do not have [as variable], it will return nothing.
#Then we will excute with-block. At the end, we will excute __exit__().
#__exit__函数的返回值用来指示with-block部分发生的异常是否要re-raise,如果返回False,则会re-raise with-block的异常,如果返回True,则就像什么都没发生。
import sys
class test:
    def __enter__(self):   #need one argument
        print("enter")
        return self
    def __exit__(self, type, value, trace):   #need 4 arguments
        print(type, value, trace)
        return True
    def do(self):
    	a=1/0
    	return a
with test() as t:
	t.do()
#result
#enter
#<class 'ZeroDivisionError'> division by zero <traceback object at 0x1029a5188>
#It's mostly used to handle the exception.
#a esier simple
with open(filename, 'w') as f:
	f.read()
	#We do not need to close the file. It can be closed itself.

  

14. assert-statement

#assert statement
#syntax:
# assert expression , [Arguments]
#If expression fails, python uses arguments expression.
def a(b):
	assert b>1, print("wrong!")
b = input('>')
a(b)

 

posted @ 2017-01-17 09:50  KennyRom  阅读(259)  评论(0编辑  收藏  举报