Python基础
程序员文章站
2022-05-11 19:21:01
...
1.提示用户输入
input('Enter an integer:')
2.条件判断语句
number = 23 guess = int(input('Enter an integer')) if guess == number: print('ok') print('o,year') elif guess > number: print('guess>number') else: print('guess<nuber')
3.for循环
for i in range(1,5,2): print(i) else: print('else');
4.while循环
run = True while(run): print('loop') run = False else: print("else")
5.break
while及for循环的else子句也不会被执行
while True: str = input('Enter:') if str == 'quit': break print('str length is ', len(str))
6.continue:跳过当前循环的剩余语句
while True: str = input('Enter:') if str == 'quit': break if len(str) < 3: continue print('str length is ok')
7.定义方法
必须放在被调用代码之前
def sayHello(): print('Hello World')
8.在方法内修改方法外的变量,可在方法内用global先声明该变量
def sayHello(i): global x print('Hello World',x) x = 10 print('Hello World',x) x=20 sayHello(3) print('thie value is',x)
9.为形参设默认值
def showMsg(msg, time = 1): print(msg * time) showMsg('hello') showMsg('hello', 6)
10.关键参数
def testParam(a, b = 1, c = 2): print('a is',a,'and b is', b, 'and c is', c) testParam(10) testParam(a=1,c=20) testParam(c=30, b=20, a=10)
11.return
如何没有return语句,默认暗含return Null
12.DocStrings
def testParam(a, b = 1, c = 2): "ddddddddddddddddd" print('a is',a,'and b is', b, 'and c is', c) print(testParam.__doc__)
13.使用模块
import sys for i in sys.argv: print(i) print(sys.path)
14.del用来删除变量
a = 2 print(a) del(a) #print(a)
15.List的使用
fruitList = ['apple', 'barana', 'tao'] print(len(fruitList)) for item in fruitList: print(item) fruitList.append('li') fruitList.sort() for item in fruitList: print(item) item0 = fruitList[0] del fruitList[0] print(fruitList) printfruitList [1:])
16.元组的使用
num=('one', 'two', 'three') print(len(num)) print(num) newNum=('1','2',num) print(len(num)) print(newNum[2][2]) secNum=(1,) print(len(secNum))
17. 字典
num={1:'one',2:'two',3:'three',4:'four',5:'five'} print(num[1]) num[6]='six' print(num) del num[1] for key,value in num.items(): print(key,":" + value) if 4 in num: print('yes')
18.类
class Person: age = 0 def __init__(self, name): self.name = name Person.age += 1 def say(self): print('my name is', self.name) if Person.age == 0: print('my age is 0') elif Person.age == 1: print('my age is 1') else: print('else') p=Person("peng") p.say()