python语句

时间:2023-03-09 10:06:02
python语句

print语句

print函数中使用逗号输出多个表达式,打印的结果之间使用空格隔开。

>>> print('name:','zyj','age:','')
name: zyj age: 24
>>> print(1,2,3)
1 2 3

import语句

import somemodule
from somemodule import somefunction
from somemodule import somefunction, anotherfunction, yetanotherfunction
from somemodule import *
import somemodule as newmodulename
from somemodule import somefunction as newfunctionname from module1 import open as open1
from module2 import open as open2

赋值语句

1、多个赋值操作同时进行

>>> x,y,z = 1,2,3
>>> print(x,y,z)
1 2 3
>>> x,y = y,x
>>> y,z = z,y
>>> print(x,y,z)
2 3 1

2、序列解包:将多个值得序列解开,然后放到变量的序列中.注:必须进行等长元素赋值,否则会报错。

>>> values = 1,2,3
>>> print(values)
(1, 2, 3)
>>> x,y,z = values
>>> print(x)
1
>>> lst = [1,2,3]
>>> a,b,c = lst
>>> print(a,b,c)
1 2 3
>>> str = 'hello'
>>> a,b,c,d,e = str
>>> print(a,b,c,d,e)
h e l l o

3、使用*的特性可以将其他参数都收集在一个变量中的实现,通过此方式返回的均为列表。

>>>
>>> a,b,*rest = [1,2,3,4]
>>> print(a,b,rest)
1 2 [3, 4]
>>> *rest,a =(1,2)
>>> print(rest,a)
[1] 2
>>> d = {'name':'zyj','score':''}
>>> d1 = d.keys()
>>> print(d1)
dict_keys(['name', 'score'])
>>> *rest,c = d1
>>> print(rest,c)
['name'] score

4、链式赋值:是将同一值赋值给多个变量的捷径

当赋值对象为不可变元素,则赋值相同的对象给不同的变量,其id是相同的,即内存只有一份对象,只是引用计数增加而已。

当赋值对象为可变元素,则赋值相同的对象给不同的变量,其id是不同的,即内存中有两份对象。

>>> x = y = 'hello'
>>> print(x,y)
hello hello
>>> y = 'hello'
>>> x = y
>>> print(id(x),id(y))
46708992 46708992
>>> a = 'hello'
>>> b = 'hello'
>>> print(id(a),id(b))
46708992 46708992
>>> c = d = [1,2,3,4]
>>> print(id(c),id(d))
42278584 42278584
>>> g = [1,2]
>>> f = g
>>> print(id(g),id(f))
46620464 46620464
>>> e = [1,2,3,4]
>>> f = [1,2,3,4]
>>> print(id(e),id(f))
46618504 46626056
>>>

5、增量赋值:如 x+=1 等同于x = x+1,对于* / %等标准运算符都适用

>>> x = 2
>>> x+=1
>>> print(x)
3
>>> x //=3
>>> print(x)
1
>>> str1 = 'hello, '
>>> str1 += 'world! '
>>> str1 *= 2
>>> print(str1)
hello, world! hello, world!

条件与条件语句

布尔表达式:
False None 0 "" () [] {} 会被解释器视为false,其他的一切都解释为真,包括特殊值Ture

>>>
>>> sum = True + False
>>> print(sum)
1

bool函数用来转换其他值为布尔值

>>> print(bool(''),bool([]),bool(()),bool(0),bool(dict()),bool(True),bool(''))
False False False False False True True

条件执行和if语句

if语句:如果条件为真,则执行后面的语句块。为假则不执行
else子句:属于if语句的子句,当if为假时,则执行else的语句块
elif子句:如果检查多个条件,就可以使用elif,同时也具有else的子句

print('guess number game begin!')
num = 500
while(True):
  num1 =int(input('Enter a number: '))
  if num1 > num:
    print('sorry,it\'s bigger than expect num,please try again')
  elif num1 < num:
    print('sorry,it\'s smaller than expect num,please try again')
  else:
    print('good,it\'s right')
    break

嵌套代码块:if语句中可以嵌套if语句

while(True):
name = input('what is your name ?')
name = name.title()
if name.endswith('Zhao'):
if name.startswith('Mr.'):
print('hello, Mr.Zhao')
elif name.startswith('Mrs.'):
print('hello,Mrs.Zhao')
else:
print('hello,Zhao')
else:
  print('hello,stranger')
break

更复杂的条件

比较运算符:x ==y 、x < y、 x > y、 x >= y、 x<=y 、x!=y、 x is y 、x is not y、 x in y 、x not in y
使用==运算符来判断两个对象是否相等,使用is判定两者是否等同(同一个对象)

>>> x = y = [1,2,3,4]
>>> z = [1,2,3,4]
>>> print(x is y)
True
>>> print(x is z)
False
>>> print(id(x),id(y),id(z))
38556456 38556456 41088104
>>> print(x is not z)
True
>>> print(x == z)
True
>>> a = b = ('hello')
>>> c = ('hello')
>>> print(id(a),id(b),id(c))
38648064 38648064 38648064
>>> print(a is c)
True
>>>

字符串和序列比较

>>> print('a' < 'b')
True
>>> print('ZYj'.lower() == 'zyj')
True
>>> print([1,2] < [2,1])
True

布尔运算符:and or not

number = int(input('enter a number between 1 and 10: '))
if number <=10 and number >=1:
  print('Great')
else:
  print('wrong')
if not 0: #返回真;
  print('Great')
else:
  print('wrong')

短路逻辑和条件表达式:

在X and y 中如果x为假,表达式会返回x的值。如果x为真,会返回y的值;

在x or y中,如果x为真,直接返回x的值,否则就返回y的值。

>>> print(0 or 4)
4
>>> print(1 or 4)
1
>>> print(0 and 4)
0
>>> print(1 and 4)
4
>>>

断言:判断语句后的值为真,否则直接报错

>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
assert 0 < age < 100
AssertionError

循环

while循环

name = ''
while not name.strip():
name = input('enter your name: ')
print('hello, %s!' % name) number = 0
nums = []
while (number <= 100):
nums.append(number)
number += 1
print(nums)  

for循环
内建范围函数:range(),range(0,10) range(10) [0,1,2,3,4,5,6,7,8,9]

num = range(10)
print(num)
for number in range(0,10):
print(number)

循环遍历字典元素

d ={"name":'zyj','score':''}
for key in d:
print(key,d[key])
>>>
name zyj
score 99
>>> d1 = dict(name1 = 'zyj',score1 = 90,name2 = 'sl',score2 = '')
print(d1)
print(d1.items())
for key,value in d1.items():
print(key,value) 
>>>
{'score1': 90, 'name1': 'zyj', 'score2': '', 'name2': 'sl'}
dict_items([('score1', 90), ('name1', 'zyj'), ('score2', ''), ('name2', 'sl')])
score1 90
name1 zyj
score2 60
name2 sl
>>>

并行迭代:同时迭代两个序列,
使用索引方式实现:

names = ['zyj','sl','xh']
ages = ['','','']
for i in range(len(names)):
print(names[i] +' is '+ ages[i]+' years old') >>>
zyj is 10 years old
sl is 20 years old
xh is 30 years old
>>>

zip函数可以进行并行迭代,将两个序列“压缩”在一起。然后返回一个元组的列表或迭代器对象,注意:zip可以处理不等长的序列

names = ['zyj','sl','xh']
ages = ['','','']
print(zip(names,ages))
for name,age in zip(names,ages):
print(name +' is '+ age+' years old')
>>>
<zip object at 0x0280FF80>
zyj is 10 years old
sl is 20 years old
xh is 30 years old s = zip(range(5),range(10))
for i,j in s:
print(i,j)
0 0
1 1
2 2
3 3
4 4
>>>

按索引迭代enumerate函数迭代序列的索引-值对,返回的是索引-值对的元组迭代器

s1 = ['hello','world']
print(s1)
print(enumerate(s1))
for index,value in enumerate(s1): #遍历序列中所有的序列和值
s1[index] = 'hi' #将所有的元素进行替换,不可变序列不可替换
print(index,s1[index])
print(s1)
>>>
['hello', 'world']
<enumerate object at 0x02B94D78>
0 hi
['hi', 'world']
1 hi
['hi', 'hi'] #返回不可变序列的索引-值对。
s2 = 'hello'
print(enumerate(s2))
for index,value in enumerate(s2):
print(index,value) <enumerate object at 0x02B94D78>
0 h
1 e
2 l
3 l
4 o
>>>

翻转和排序迭代:reversed和sorted,可作用于任何序列和可迭代对象,不是原地操作,而是返回翻转或排序后的版本,reversed返回迭代器对象

print(sorted([1,2,3,5,6,4,3,1]))
print(reversed([1,2,3,5,6,4,3,1]))
print(list(reversed([1,2,3,5,6,4,3,1])))
print(tuple(reversed([1,2,3,5,6,4,3,1])))
print(sorted('hello!'))
print(reversed('hello!'))
print(list(reversed('hello!')))
print(tuple(reversed('hello!'))) >>>
[1, 1, 2, 3, 3, 4, 5, 6]
<list_reverseiterator object at 0x02F373D0>
[1, 3, 4, 6, 5, 3, 2, 1]
(1, 3, 4, 6, 5, 3, 2, 1)
['!', 'e', 'h', 'l', 'l', 'o']
<reversed object at 0x02F373D0>
['!', 'o', 'l', 'l', 'e', 'h']
('!', 'o', 'l', 'l', 'e', 'h')
>>>

列表推导式

list = [x*x for x in range (10)]
print(list) list1 = [x*x for x in range(10) if x%2 == 0]
print(list1) list2 = [(x,y) for x in range(3) for y in range(3)]
print(list2) list2 = [[x,y] for x in range(3) for y in range(3)]
print(list2) list2 = [{x:y} for x in range(3) for y in range(3)]
print(list2) list2 = [(x,y) for x in range(3) for y in range(3) if x%2 if x%3]
print(list2)
>>>
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 4, 16, 36, 64]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
[{0: 0}, {0: 1}, {0: 2}, {1: 0}, {1: 1}, {1: 2}, {2: 0}, {2: 1}, {2: 2}]
[(1, 0), (1, 1), (1, 2)]
>>>

pass 语句什么都不做,可以作为占用符使用,
del 用来删除变量,或者数据结构的一部分,但是不能用来删除值,python有内建垃圾回收,会对值进行删除
exec:执行python程序
eval():函数对写在字符串中的表达式进行计算并返回结果

x = 1
del x
# print(x) #返回x未定义 x = ['hello','world']
y = x
y[1] = 'python'
print(x)
del x
print(y) #y为hello python exec ("print('hello,world')") from math import sqrt
exec ("sqrt = 1")
#print(sqrt(4)) #返回变量不可用 from math import sqrt
scope = {} #scope为放置代码字符串命名空间作用的字典
exec("'sqrt = 1'in scope")
print(sqrt(4)) print(eval("2*3")) >>>
['hello', 'python']
['hello', 'python']
hello,world
2.0
6
>>>

ord()返回单字符字符串的int值
chr(n)返回n所代表的包含一个字符的字符串

>>> print(ord("c"))
99
>>> print(chr(99))
c
>>>