Python 基础教程 30分钟快速入门

Python Introduction

print ("My first Python code!")
=================================================================================
Python Lines, Indentation, Comments

multiLine = 'this is ' + \
        'multi ' + \
        'line.'
print(multiLine)
#Statements contained within the [], {}, or () brackets 
#do not need to use the line continuation character

paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
#The triple quotes can be used to span the string across multiple lines.

import sys; x = 'foo'; sys.stdout.write(x + '\n')
#The semicolon ( ; ) allows multiple statements on the single line given.

print 'something' #print("Am a comment")
'''
print("We are in a comment")
print ("We are still in a comment")
'''
=================================================================================
Python Variables

a = 0
b = 2
print(a  + b)
#result
2

a = "0"
b = "2"
print(a  + b)
#result
02

a = "0"
b = 2
print(int(a)  + b)
#result
2

int(variable) - casts variable to integer
long(variable) -casts variable to long
str(variable) - casts variable to string
float(variable) - casts variable to float (number with decimal)
=================================================================================
Python Operators

print (3 + 4)
print (3 - 4)
print (3 * 4)
print (3 / 4)
print (3 % 2) #remainder of x / y
print (3 ** 4) #3 to the fourth power
print (3 // 4) #quotient of x and y, alse use it like this:pow(x, y)

math.trunk(x) x truncated to Integral  
round(x[, n]) x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.  
math.floor(x) the greatest integral float <= x  
math.ceil(x) the least integral float >= x

a = 0
a+=2
print (a)
=================================================================================
Python If Statement

a = 20
if a >= 22:
    print("if")
elif a >= 21:
    print("elif")
else:
    print("else")
=================================================================================
Python Functions

def someFunction():
    print("boo")
someFunction()

def someFunction(a, b):
    print(a+b)
someFunction(12,451)

def someFunction():
    a = 10
someFunction()
print (a)
This will cause an error because our variable, a, is in the local scope of someFunction. 

a = 10
def someFunction():
    print (a)
someFunction()
In this example, we defined a in the global scope. 
This means that we can call it or edit it from anywhere, including inside functions.
=================================================================================
Python For Loop
(break, continue) 

for a in range(1,3):
    print (a)
#result

2

a = 1
while a < 10:
    print (a)
    a+=1

for letter in 'Python':     # First Example
   if letter == 'h':
 pass #The pass statement is a null operation; nothing happens when it executes.
      break
   print 'Current Letter :', letter

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print 'Current fruit :', fruits[index]
print "Good bye!"
#Iterating by Sequence Index
=================================================================================
Python Strings

HELLO
01234
-5-4-3-2-1

myString = ""
print (type(myString))

stringVar.count('x') - counts the number of occurrences of 'x' in stringVar
stringVar.find('x') - returns the position of character 'x'
stringVar.lower() - returns the stringVar in lowercase (this is temporary)
stringVar.upper() - returns the stringVar in uppercase (this is temporary)
stringVar.replace('a', 'b') - replaces all occurrences of a with b in the string
stringVar.strip() - removes leading/trailing white space from string
stringVar.startswith()
stringVar.join() - opposite of split()

str = 'Hello World!'
print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 6th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print len(s)       # 12
print str + str(9) # Hello World!9
print str + "TEST" # Prints concatenated string
print r'a\nb\nc'   # prefixed by an 'r' and passes all the chars through without special treatment of backslashes
  # so r'x\nx' evaluates to the length-4 string 'x\nx'.
print ("-%d, -%s" % (1, 'abc'))

a = "string"
print (a[1:3])
print (a[:-1])
#result
tr
strin
=================================================================================
Python Lists

sampleList = [01,2,3,4,5,6,7,8,a,A,b]
print (sampleList)
print sorted(sampleList)
print sorted(sampleList, reverse=True)
print sorted(sampleList, key=len)
print sorted(sampleList, key=str.lower)
print sampleList
sampleList.sort() #The sort() method changes the underlying list and returns None
print sampleList

strs = ['hello', 'and', 'goodbye']
shouting = [ s.upper() + '!!!' for s in strs if len(s) > 0 ]

sampleList = [1,2,3,4,5,6,7,8]
for a in sampleList:
    print (a)

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd to 4th
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists

.append(value) - appends element to end of the list
.count('x') - counts the number of occurrences of 'x' in the list
.index('x') - returns the index of 'x' in the list
.insert('y','x') - inserts 'x' at location 'y'
.pop() - returns last element then removes it from the list
.remove('x') - finds and removes first 'x' from list
.reverse() - reverses the elements in the list
.sort() - sorts the list alphabetically in ascending order, or numerical in ascending order
=================================================================================
Python Tuples
The one main difference between tuples and lists are that tuples cannot be changed

myTuple = (1,2,3)
print (myTuple)

myTuple = (1,2,3)
myList = list(myTuple)
myList.append(4)
print (myList)
Boom! We have successfully undone what Python was trying to teach us not to do. 
We just casted the tuple into a list, then once it was a list
=================================================================================
Python Dictionaries

myExample = {'someItem': 2, 'otherItem': 20}
print(myExample['otherItem'])

for key in myExample: print key
for key in myExample.keys(): print key
for k, v in dict.items(): print k, '>', v

for key in sorted(myExample.keys()):
    print key, myExample[key]

myExample = {'someItem': 2, 'otherItem': 20,'newItem':400}
for a in myExample:
    print (a, myExample[a])

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one']       # Prints value for 'one' key
print dict[2]           # Prints value for 2 key
print tinydict          # Prints complete dictionary
print tinydict.keys()   # Prints all the keys
print tinydict.values() # Prints all the values
print tinydict.items()  # items() is the dict expressed as (key, value) tuples
=================================================================================
Python Del

var = 6
del var  # var no more!

list = ['a', 'b', 'c', 'd']
del list[0]     ## Delete first element
del list[-2:]   ## Delete last two elements
print list      ## ['b']

dict = {'a':1, 'b':2, 'c':3}
del dict['b']   ## Delete 'b' entry
print dict      ## {'a':1, 'c':3}
=================================================================================
Python Formatting

#Formatting Numbers as Strings
print('The order total comes to %f' % 123.44)
print('The order total comes to %.2f' % 123.444)
#result
The order total comes to 123.440000
The order total comes to 123.44

#Formatting Strings
a ="abcdef"
print('%.3s' % a)
#result
abc
=================================================================================
Python Exceptions

var1 = '1'
try:
    var1 = var1 + 1 # since var1 is a string, it cannot be added to the number 1 
except:
    print('there is an exception')
else:
print('there is no exception')
finally:
print('finally...')
print(var1)

raise RuntimeError('some thing happened...')
=================================================================================
Python Reading Files

#The "codecs" module provides support for reading a unicode file.
import codecs
f = codecs.open('foo.txt', 'rU', 'utf-8')
for line in f:
  # here line is a *unicode* string
  pass


file object = open(file_name [, access_mode][, buffering])
Here is a list of the different modes of opening a file:
--------------------------------------------------------
r Opens a file for reading only. This is the default mode.
rb Opens a file for reading only in binary format. 
The file pointer will be at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. 
The file pointer will be at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. 
The file pointer will be at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. 
If the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. 
If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. 
If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. 
Overwrites the existing file if the file exists. 
If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. 
That is, the file is in the append mode. 
If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. 
The file pointer is at the end of the file if the file exists. 
That is, the file is in the append mode. If the file does not exist, 
it creates a new file for writing.
a+ Opens a file for both appending and reading. 
The file pointer is at the end of the file if the file exists. 
The file opens in the append mode. If the file does not exist, 
it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. 
The file pointer is at the end of the file if the file exists. 
The file opens in the append mode. If the file does not exist, 
it creates a new file for reading and writing.

The file object atrributes and methods
----------------------------------------------
file.closed - Returns true if file is closed, false otherwise.
file.mode - Returns access mode with which file was opened.
file.name - Returns name of the file.
file.softspace - Returns false if space explicitly required with print, true otherwise.
file.close();
file.write(string);
file.read([count]);
file.tell() - tells you the current position within the file
seek(offset[, from]) - changes the current file position.
os.rename(current_file_name, new_file_name)
os.remove(file_name)

file.read(n) - This method reads n number of characters from the file, or if n is blank it reads the entire file.
file.readline(n) - This method reads an entire line from the text file.
readline() - reads only a line

f = open("test.txt", "r") #opens file with name of "test.txt"
f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1))
print(f.read())
f.close()

f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f: #iterates over the lines of the file
    myList.append(line)
f.close()
print(myList)
we are looping through each line of the file we use myList.append(line) 
to add each line to our myList list

os.mkdir("newdir")
os.chdir("newdir")
os.getcwd() - displays the current working directory.
os.rmdir('dirname') - Before removing a directory, all the contents in it should be removed
=================================================================================
Python Writing to Files

#Warning! The Evil "w" in the Open Method
f = open("test.txt","w") #opens file with name of "test.txt"
f.write("I am a test file.")
f.write("Maybe someday, he will promote me to a real file.")
f.write("Man, I long to be a real file")
f.write("and hang out with all my new real file friends.")
f.close()
#we just rewrote the contents that we deleted to the file. 
#it kept writing without using any line breaks

#Writing Lines to a File
f.write("Maybe someday, he will promote me to a real file.\n")

#Appending to a File
f = open("test.txt","a") #opens file with name of "test.txt"
f.write("and can I get some pickles on that")
f.close()
=================================================================================
Python OS Utilities

os module docs
filenames = os.listdir(dir) -- list of filenames in that directory path (not including . and ..). The filenames are just the names in the directory, not their absolute paths.
os.path.join(dir, filename) -- given a filename from the above list, use this to put the dir and filename together to make a path
os.path.abspath(path) -- given a path, return an absolute form, e.g. /home/nick/foo/bar.html
os.path.dirname(path), os.path.basename(path) -- given dir/foo/bar.html, return the dirname "dir/foo" and basename "bar.html"
os.path.exists(path) -- true if it exists
os.mkdir(dir_path) -- makes one dir, os.makedirs(dir_path) makes all the needed dirs in this path
shutil.copy(source-path, dest-path) -- copy a file (dest path directories should exist)
os.system(cmd) -- which runs the command and dumps its output onto your output and returns its error code
(status, output) = commands.getstatusoutput(cmd) -- 
runs the command, 
waits for it to exit, and returns its status int and output text as a tuple. 
The command is run with its standard output and standard error combined into the one output text. 
The status will be non-zero if the command failed.
=================================================================================
Python Function

def foo():
    print('function')
foo()

def foo():
    print('function')
def foo1(a,b):
    print(a+b)
foo()
foo1(1,2)

=================================================================================
Python Classes

#ClassOne.py 
class Calculator(object):
    #define class to simulate a simple calculator
    def __init__ (self):
        #start with zero
        self.current = 0
    def add(self, amount):
        #add number to current
        self.current += amount
    def getCurrent(self):
        return self.current
from ClassOne import * #get classes from ClassOne file
myBuddy = Calculator() # make myBuddy into a Calculator object
myBuddy.add(2) #use myBuddy's new add method derived from the Calculator class
print(myBuddy.getCurrent()) #print myBuddy's current instance variable

class Parent:        # define parent class
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.myMethod()         # child calls overridden method
=================================================================================
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值