1. hello
#! /usr/local/bin/python
# -*- coding: utf-8 -*-
s1=input("Input your name:")
print("your name, %s" %s1) #cannot be: print("your name:"+s1)
》
Input your name:123
your name, 123
2. 字符串和数字
a=2
b="test"
c=str(a)+b
d="1111"
e=a+int(d)
print("c is %s,e is %i" %(c,e))
》
c is 2test,e is 1113
3. list
word=['a','b','c','d','e','f','g']
a=word[2]
print("a is:%s" %a)
print("a is:"+a)
b=word[1:3]
print("b is")
print(b) # cannot be: print("b is"+b))
c=word[:2] #the right one not included
print(c)
d=word[0:]
print(d)
e=word[:2]+word[2:]
print(e)
f=word[-1]
print(f)
g=word[-4:-2]
print(g)
》
a is:c
a is:c
b is
['b', 'c']
['a', 'b']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
g
['d', 'e']
4. dictionary
x={'a':'aaa','b':'bbb','c':'ccc'}
print(x['a'])
for key in x:
print((key, x[key]))
#print("key is %s,value is %s" %(key,x[key]))
》
aaa
('a', 'aaa')
('c', 'ccc')
('b', 'bbb')
5. 字符串
word="abcdefg"
a=word[2]
print("a is:%s" %a)
print("a is:"+a)
b=word[1:3]
print("b is")
print(b) # cannot be: print("b is"+b))
c=word[:2] #the right one not included
print(c)
d=word[0:]
print(d)
e=word[:2]+word[2:]
print(e)
f=word[-1]
print(f)
g=word[-4:-2]
print(g)
l=len(word)
print(l)
》
a is:c
a is:c
b is
bc
ab
abcdefg
abcdefg
g
de
7
6. 条件和循环语句
x=int(input("please input an integer"))
if x<0:
x=0
print("Negative changed to zero")
elif x==0:
print("zero")
else:
print("more")
a=['cat','hello','ketty']
for x in a:
print(x, len(x))
7. 函数
def add(a, b=2): #2相当于默认值
return a+b
r=add(1)
print(r)
r=add(1,3)
print(r)
def sum(a,b):
return a+b
func=sum
print(func(1,2))
8. 异常
s=raw_input("input your age:") # raw_input 在控制台输入的字符串不用带引号,input 则需要带引号输入
if s=='0':
print(s)
raise Exception("cannot be zero") #表示引出异常,后面的不再执行
try:
i=int(s)
except Exception as err:
print(err)
finally:
print("Goodbye")
》
9, 文件处理
spath="E:/12345.txt"
f=open(spath,"w")
f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r")
for line in f:
print(line)
f.close()
》
First line 1.
First line 2.
10. 类和继承
class Base:
def __init__(self):
self.data=[]
def add(self,x):
self.data.append(x)
def addtwice(self,x):
self.add(x)
self.add(x)
class Child(Base):
def plus(self,a,b):
return a+b
oChild=Child()
oChild.add("str1")
print(oChild.data)
print(oChild.plus(2, 3))
》
['str1']
5