二、Python基础
1.变量名
数字,字母,下划线:aaa1;aa_b1
不能以数字开头:1aa
变量名不能是python内部的关键字
2.getpass
import getpass username=raw_input('username:') passwd=getpass.getpass('password:') #使得密码不可见
3.基本if条件语句
if 条件: 内容 else: 内容 ------------------------------------------------------------------- if 条件1: ... elif 条件2: ... elif 条件3: ... else: ... ------------------------------------------------------------------ True False 1>2 n1>n2 n1=n2 name=="name1" or name=="name2" name!=name3 name=="name4" and name=="name5"
4.while循环语句
while 条件: 代码块
例子1:while True: print ("1") 例子2: #循环输出1,2,3,4,5,6..... import time i=1 status=True while status: print (i) if i==10: status=False i=i+1 time.sleep(1) print (end)
--------------------------------------------------------------------------------------------------
5.break
#break:跳出所有循环,并且break下面的代码i=i+1 time.sleep(1)不再执行 #循环输出1,2,3,4,5,6..... import time i=1 status=True while status: print (i) if i==10: break i=i+1 time.sleep(1) print (end)
----------------------------------------------------------------
6.continue
例子1: #continue:跳出本次循环,继续下次循环 #输出12345689 import time i=1 while True: if i ==7: i+=1 continue print (i) if i==10: break time.sleep(1) #i=i+1 i+=1
--------------------------------------------------------------------
例子2:1-100求和 #1-100求和 i=1 sum=0 while True: print (i) sum=sum+i if i ==100: break i+=1 print sum
--------------------------------------------------------------
例子3:输出1-100的奇数: #输出1-100奇数 i=1 while True: if i%2==1: print i if i ==100: break i+=1
------------------------------------------------------------------------------------
例子4:输出1-100中的奇数并列表输出: i=0 l=[] while i<=100: i=i+1 if i%2==0: continue else: l.append(i) ptint l
------------------------------------------------------------------------------------
7.python运算符 =:赋值运算 +=:加法赋值运算符 例子:i=1 i+=1 print i (2) i+=1相当于i=i+1 -=:减法赋值运算--i-=a相当于i=i-a *=:乘法赋值运算:同上 \=:同上
------------------------------------------------------------------------------------
8.逻辑运算符:
and 布尔与 or布尔或 not布尔非
\=:同上
------------------------------------------------------------------------------------
9.成员运算符:
in not in
------------------------------------------------------------------------------------
10.查看对象的类,或对象的内部方法#!/usr/bin/python
# -*- coding: UTF-8 -*-
temp="chushujin"
print dir(temp)
help(type(temp))
------------------------------------------------------------------------------------
11.基本数据类型常用功能
1.int整型
a.
# n1=123
# n2=456
# print n1+n2
# print n1.__add__(n2)
b.
获取可表示二进制最短位数
n1=4 00000100
ret=n1.bit_length()
print ret
------------------------------------------------------------------------------------
12.元组和列表 元组和列表几乎相同 不同点:元组不能修改,列表可添加修改其中内容 ###################元组########################: name_tuple=('chu','shu','jin') #索引 print (name_tuple[0]) #len print (name_tuple[len(name_tuple)-1]) #切片 print (name_tuple[0:2:1]) #for for i in name_tuple: print i #获取指定元素出现的次数 print (name_tuple.count('chu')) #获取指定元素的位置 print (name_tuple.index('shu')) ################################################## #enumerate自动生成一列,默认从0自增1 li=['电脑','鼠标垫','u盘','游艇'] for k,item in enumerate(li): print k,item inp=input("请输入:") imp=raw_input("qingshuru:") print (type(inp)) print (type(imp)) imp_num=int(imp) print li[inp] print li[imp_num] ----------------------------------- 0 电脑 1 鼠标垫 2 u盘 3 游艇 请输入:0 qingshuru:-1 <type 'int'> <type 'str'> 电脑 游艇
------------------------------------------------------------------------------------
13.字典
########################字典############## user_info={ "name":"chushujin", "age":"18", "gender":"M" } #索引 print (user_info['name']) #没有切片 #循环---默认输出都是key for i in user_info: print i #获取所有的键 print (user_info.keys()) #获取所有的值 print (user_info.values()) #获取所有的键值对 print (user_info.items()) #循环所有的键 for i in user_info.keys(): print i #循环所有的值 for i in user_info.values(): print i #获取所有的键值对 for k,v in user_info.items(): print k,v #get:根据key获取值,如果key不存在,可指定一个默认值 val=user_info.get('name') print val val = user_info.get('sex') print val val = user_info.get('sex','not sucess') print val #删除字典 test={ "a1":1, "a2":2 } del test["a1"] print test #删除字典 test={ "a1":1, "a2":2 } del test["a1"] print test #update 1.user_info.update({'k5','123'}) 2.d['k1']='123' print user_info test={ "a1":1, "a2":2 } user_info.update(test) print user_info print user_info test={ "a1":1, "a2":2 } user_info.update(test) print user_info
------------------------------------------------------------------------------------
14.range,xrange
#range,xrange for i in xrange(1,10000): print i for i in range(10,0,-1): print i #获取列表的索引 li=['ai','bi'] li_len=len(li) for i in range(0,li_len): print (i,li[i])
------------------------------------------------------------------------------------
15.startswith和endwith方法:
a.startswith()方法:方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。 语法:str.startswith(str, beg=0,end=len(string)); 例子: str = "this is string example....wow!!!"; print str.startswith( 'this' );----------------------------true print str.startswith( 'is', 2, 4 );----------------------------true print str.startswith( 'this', 2, 4 );----------------------------false b.endswith()方法: 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置 语法:str.endswith(suffix[, start[, end]]) 例子: str = "this is string example....wow!!!"; suffix = "wow!!!"; print str.endswith(suffix);-------------------true print str.endswith(suffix,20);-------------------true suffix = "is"; print str.endswith(suffix, 2, 4);-------------------true print str.endswith(suffix, 2, 6);-------------------false
------------------------------------------------------------------------------------
16.replace()方法
replace()方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次 语法:str.replace(old, new[, max]) 例子: str = "this is string example....wow!!! this is really string"; print str.replace("is", "was"); print str.replace("is", "was", 3); ---------------------------- 输出: thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string
------------------------------------------------------------------------------------
17.strip()方法:
'''该方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。''' str = "0000000000000000000000123aaa00000000000000000" print str.strip("0") str2=" runoob " print str2.strip() str3="12345678987654321" print str3.strip("12")
-----------------------------------
123aaa
runoob
3456789876543
------------------------------------------------------------------------------------
练习题:
#有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。 #即: {'k1': 大于66的所有值, 'k2': 小于66的所有值} li=[11,22,33,44,55,66,77,88,99,90] dic={ "k1":[], "k2":[] } for i in li: if i<=66: dic["k1"].append(i) else: dic["k2"].append(i) print (dic)
--------------------------------------------------------
'''查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。 li = ["alec", " aric", "Alex", "Tony", "rain"] tu = ("alec", " aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}''' li = ["alec", " aric", "Alex", "Tony", "rain"] tu = ("alec", " aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': ' Aric', "k3": "Alex", "k4": "Tony"} ####################################### print li for i in range(len(li)): li[i]=li[i].replace(" ","") print li ####################################### print tu tu=list(tu) print tu for i in range(len(tu)): tu[i]=tu[i].replace(" ","") print tu tu=tuple(tu) print tu ####################################### print dic print len(dic) for i in dic: dic[i]=dic[i].replace(" ","") print dic ######################################## for i in li: #print i if (i.startswith("a") or i.startswith("A")) and i.endswith("c"): print i ######################################## for i in tu: if (i.startswith("a") or i.startswith("A")) and i.endswith("c"): print i ######################################### for i in dic: #print dic[i] if (dic[i].startswith("a") or dic[i].startswith("A")) and dic[i].endswith("c"): print dic[i] ------------------------------------------------ li=["手机","电脑","鼠标","游艇"] #print str(li).decode("string_escape") for i,j in enumerate(li): print i+1,j num=input("请输入商品编码:") print num #print len(li) if num>0 and num<=len(li): good = li[num - 1] print good else: print "商品不存在"