Python:基础入门
- #python 逻辑运算: and,or,not
- #Python中没有&&,||,!等短路逻辑运算符而是用and,or,not分别替代
- print("================================ 逻辑运算符 ================================")
- a = 1;
- b = 2;
- print("a=",a)
- print("b=",b)
- print("a and b:",a and b)
- print("b and a:",b and a)
- print("a or b:",a or b)
- print("b or a:",b or a)
- print("True and Fasle:",True and False)
- print("False or True:",False or True)
- print("True and 0:",True and 0)
- print("0 and True:", 0 and True)
- print("False and 1:",False and 1)
- print("1 and False:", 1 and False)
- #Python中0可以表示False,非0可以表示True
- print("0 == False:",0 == False)
- print("4 == True:",5 == True)
- print("a == False",a == False)
-
- print("not 0",not 0)
- print("not 4",not 4)
- print("not a",not a)
-
- print("not a and b:",not (a and b))
- print("not a or b:",not (a or b))
-
-
- #Python中 is 和 is not 用来检测两个对象的引用是否相同,== 用来判断值是否相同
- print("a is True",a is True)
- print("a == True",a == True)
-
-
- #Python 流程控制:if elif else,while else
- print("================================ 流程控制语句 ================================")
- #Python if语句
- c = 2
- if c == 0:
- print("True")
- elif c == 2:
- print("False")
- else:
- print("......")
-
-
-
- #Python while语句
- d = 0
- while True:
- d += 1
- print("d:",d)
- if d == 10:
- break
-
-
-
- #Python for语句
- e = ["a","b","c","d"]
- for i in e:
- print(i)
-
-
-
- #Python 异常捕获
- print("================================ 异常捕获语句 ================================")
- f = 1.5
- try:
- i = int(f)
- print("valid integer:",i)
- except ValueError as err:
- print(err)
-
-
- #Python 算术操作符
- print("================================ 算术操作符 ================================")
- g = 6;
- h = 4;
- #Python不支持自增和自减运算符
- print("g=",g)
- print("h=",h)
- print("g+h=",g+h)
- print("g-h=",g-h)
- print("g*h=",g*h)
- print("g/h=",g/h)
- #取整
- print("g//h=",g//h)
- #取余
- print("g%h=",g%h)
- #g的h次幂
- print("g**h=",g**h)
- g += h
- print("g += h",g)
-
- lists = ["a","b","c"]
- #列表使用+=运算符时,+=右边必须是一个iterable
- #错误的用法:lists += 5
- lists += [5]
- #['a', 'b', 'c', 5]
- print(lists)
-
- lists += ["d","e"]
- #['a', 'b', 'c', 'd', 'd', 'e']
- print(lists)
- #一个奇怪的现象
- lists += "hello"
- #['a', 'b', 'c', 5, 'h', 'e', 'l', 'l', 'o']
- #字符串是一个iterable,这回导致字符串中的每个字符都被添加
- print(lists)
-
- #下列两种方法可以讲一个字符串添加到列表
- lists += ["hello"]
- #['a', 'b', 'c', 5, 'd', 'e', 'h', 'e', 'l', 'l', 'o', 'hello']
- print(lists)
- #['a', 'b', 'c', 5, 'd', 'e', 'h', 'e', 'l', 'l', 'o', 'hello', 'Python']
- lists.append("Python")
-
- print(lists)
-
-
-
-
- print("================================ 输入输出函数 ================================")
- #input()输入函数
-
- print("Type Integers!,each followed by Enter;or ^D or ^Z to finish")
-
- total = 0
- count = 0
-
- while True:
- try:
- line = input("Integer:")
- if line:
- number = int(line)
- total += number
- count +=1
- except ValueError as err:
- print(err)
- continue
- except EOFError:
- break
- if count:
- print("count=",count,"total=",total,"mean=",total/count)
-
-
-
- print("================================ 函数的创建与调用 ================================")
- #Python 函数的定义
- def getAge(msg):
- while True:
- try:
- i = int(input(msg))
- return i
- except ValueError as err:
- print(err)
-
- #Python 函数的调用
- age = getAge("enter you age:")
- print("your age is:",age)
-
-
- #Python 调用系统函数
-
- #导入模块
- #建议先导入系统模块,然后导入第三方模块,最后导入自己编写的模块
- import random
- #随机产生一个[1,6]之间的一个整数
- x = random.randint(1,6)
- #随机产生列表中的一项
- y = random.choice(["a","b","c","d"])
-
- print("随机产生一个[1,6]之间的一个整数:",x)
- print("随机产生列表['a','b','c','d']中的一项:",y)
-
-
-
- #打印规定行数和列数的随机数
- def getInt(msg,minimum,default):
- while True:
- try:
- line = input(msg)
- if not line and default is not None:
- return default
- i = int(line)
- if i < minimum:
- print("must be>=",minimum)
- else:
- return i
- except ValueError as err:
- print(err)
-
-
- rows = getInt("rows:",1,None)
- columns = getInt("columns:",1,None)
- minimum = getInt("minimum(or enter for 0):",-1000000,0)
-
- default = 1000
-
- if default < minimum:
- default = 2*minimum
- maximum = getInt("maximum (or enter for"+str(default)+"):",minimum,default)
-
-
- row = 0
-
- while row < rows:
- line = ""
- column = 0
- while column < columns:
- i = random.randint(minimum,maximum)
- s = str(i)
- while len(s) < 10:
- s = " " + s
- line += s
- column += 1
- print(line)
- row += 1
-
-
- print("================================ 标示符与关键字 ================================")
-
- #Python中的_
- #以_开头和结尾的变量和方法在Python中有特殊的含义,所以我们在定义名称时应该避免这样使用
-
- #_的用法一
- #_存放最后一个被评估的表达式的结果
- for _ in ["a","b","c"]:
- print(_)
-
- #_的用法二
- #系统定义 如:__init__
-
- #_的用法三
- #声明私有变量 如__age
-
-
- print("================================ 字符串 ================================")
- #列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?
- #序列的两个主要特点是索引操作符和切片操作符。
- #索引操作符让我们可以从序列中抓取一个特定项目。
- #切片操作符让我们能够获取序列的一个切片,即一部分序列。
-
-
- #字符串的切片操作
- s = "Hello Python"
- #截取整个字符串
- print(s[:])
- print(s[0:len(s)])
-
- #截取前四个字符串
- print(s[:4])
- print(s[0:4])
- print(s[0:-8])
- print(s[-13:-8])
-
-
- #s[start:end:step] step小于0 表示从反方向开始截取
- #每个3个字符提取一个字符
- print(s[::3])
- print(s[0:len(s):3])
-
-
- #字符串的连接 效率对比join()连接 > +连接 > +=连接
-
- #字符串的复制功能*
- print(s*5)
-
-
- print("================================ Python 元组================================")
-
- #元组:元组是有序的序列,支持切片操作,元组定义后不可更改,可以通过下标访问,类似Java中的数组
- #通常用括号将元组括起来
-
- #下面定义一个元组
- hairs = ("black","red","white","brown")
- #可通过下标访问元组的某一项
- #打印white
- print(hairs[2])
-
- #元组的切片操作
- #打印('black', 'red', 'white')
- print(hairs[0:3])
-
-
- print("================================ Python 列表================================")
- #列表:列表是有序的序列,支持切片操作,列表可以更改,可以通过下标访问,类似Java中的ArraysList
- #列表通常用中括号定义
- #定义一个列表
- lists = ["a","b","c","d","c"]
- print(lists[0])
- print(lists[0:3])
- #将元组转化成列表
- print(list(hairs))
- #删除lists中的第一项,
- del lists[0]
- #打印["b","c","d"]
- print(lists)
- #删除lists中的第一项,打印'b'
- print(lists.pop(0))
- #打印["c","d"]
- print(lists)
-
-
- print("================================ Python 字典================================")
- #字典:字典是无序的组合数据类型,以键值对的形式出现,因为字典是无序的,所以不支持索引,也不支持切片,类似Java中的HashMap
-
- #定义一个字典
- dicts = {1:"A",2:"B",3:"C",4:"A"}
-
-
- #由于字典既包含键,又包含值,因此我们可以有多种方式对其进行迭代
-
- #根据key value迭代
- for item in dicts.items():
- print("key:",item[0],"value:",item[1])
-
-
- for key,value in dicts.items():
- print("key:",key,"value:",value)
-
-
- #根据key 迭代
- for key in dicts.keys():
- print("key:",key,"value:",dicts[key])
-
-
- #根据value 迭代
- for value in dicts.values():
- print("value:",value)
-
-
- #集合:集合也是一种无序的组合数据类型,可以进行交集,并集,等运算,类似Java中的Set
-
- #定义一个集合
- sets = {1,2,4,6,7}
-
-
- #字典内涵,集合内涵,列表内涵,可以是一个表达式 同时也是一个循环 还可以带一个可选的条件、
- l1 = [x for x in lists if x == "c"]
- print(l1)
- #l1,l2两种方式是等价的
- l2 = []
- for x in lists:
- if x == "c":
- l2.append(x)
-
- print(l2)
-
-
- d1 = {k:v for k,v in dicts.items() if v == "A"}
- print(d1)
- #d1,d2两种方式是等价的
- d2 = {}
- for k,v in dicts.items():
- if v== "A":
- d2.setdefault(k,v)
-
- print(d2)
相关文章