python语句,,print语句pri
python语句,,print语句pri
print语句
print函数中使用逗号输出多个表达式,打印的结果之间使用空格隔开。
print(‘name:‘,‘zyj‘,‘age:‘,‘24‘)print(1,2,3) #结果为1 2 3
import语句
import somemodulefrom somemodule import somefunctionfrom somemodule import somefunction, anotherfunction, yetanotherfunctionfrom somemodule import *import somemodule as newmodulenamefrom somemodule import somefunction as newfunctionnamefrom module1 import open as open1from module2 import open as open2
赋值语句
1、多个赋值操作同时进行
x,y,z = 1,2,3print(x,y,z)x,y = y,xy,z = z,yprint(x,y,z)
2、序列解包:将多个值得序列解开,然后放到变量的序列中.注:必须进行等长元素赋值,否则会报错。
values = 1,2,3print(values)x,y,z = valuesprint(x)lst = [1,2,3]a,b,c = lstprint(a,b,c)str = ‘hello‘a,b,c,d,e = strprint(a,b,c,d,e)
3、使用*的特性可以将其他参数都收集在一个变量中的实现,通过此方式返回的均为列表。
a,b,*rest = [1,2,3,4]print(a,b,rest) # rest = [3,4]*rest,a =(1,2)print(rest,a) # rest =[1]d = {‘name‘:‘zyj‘,‘score‘:‘99‘}d1 = d.keys()print(d1) # ([‘name‘,‘score‘])*rest,c = d1print(rest,c) #结果:[‘name‘] score
4、链式赋值:是将同一值赋值给多个变量的捷径
x = y = ‘hello‘print(x,y)#等价于:y = ‘hello‘x = yprint(id(x))print(id(y))#当赋值对象为不可变元素,则赋值相同的对象给不同的变量,其id是相同的,即内存中有一份对象,只是引用计数增加而已。a = ‘hello‘b = ‘hello‘print(id(a))print(id(b))
c = d = [1,2,3,4]print(id(c))print(id(d))
#等价于:g = [1,2]f = gprint(id(g))print(id(f))#当赋值对象为可变元素,则赋值相同的对象给不同的变量,其id是不相同的,即内存中有两份对象。e = [1,2,3,4]f = [1,2,3,4]print(id(e))print(id(f))
5、增量赋值:如 x+=1 等同于x = x+1,对于* / %等标准运算符都适用
x = 2x+=1print(x)x*=2print(x)# x / = 3 python3中的除法,不论运算数是整数还是浮点数,最终结果否是浮点数x //=3print(x)# 对于其他数据类型也适用str1 = ‘hello, ‘str1 += ‘world! ‘str1 *= 2print(str1)
条件与条件语句
布尔表达式:
False None 0 "" () [] {} 会被解释器视为false,其他的一切都解释为真,包括特殊值Ture
sum = True + Falseprint(sum) #结果为1,True = 1 ,False = 0
bool函数用来转换其他值为布尔值
print(bool(‘‘))print(bool([]))print(bool(()))print(bool(0))print(bool(dict()))print(bool(True))print(bool(‘0‘))
条件执行和if语句
if语句:如果条件为真,则执行后面的语句块。为假则不执行
else子句:属于if语句的子句,当if为假时,则执行else的语句块
elif子句:如果检查多个条件,就可以使用elif,同时也具有else的子句
print(‘guess number game begin!‘)num = 500while(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)print(x is z)print(id(x),id(y),id(z))print(x is not z)print(x == z)a = b = (‘hello‘)c = (‘hello‘)print(id(a),id(b),id(c))print(a is c)
字符串和序列比较
print(‘a‘ < ‘b‘)print(‘ZYj‘.lower() == ‘zyj‘) print([1,2] < [2,1])print([1,2] < [1,1,2])
布尔运算符: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的值。
name = input(‘your name:‘) or ‘null‘ #字符串若为空会认为是假,因此会返回‘null‘print(name)print(0 or 4) #返回4print(1 or 4) #直接返回1print(0 and 4) #直接返回0print(1 and 4) #返回4
断言:判断语句后的值为真,否则直接报错
age = 10assert 0 < age < 100 age = -1assert 0 < age < 100 # 返回AssertionError
循环
while循环
name = ‘‘while not name.strip():name = input(‘enter your name: ‘)print(‘hello, %s!‘ % name)number = 0nums = []while (number <= 100):nums.append(number)number += 1print(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‘:‘99‘}for key in d:print(key,d[key])d1 = dict(name1 = ‘zyj‘,score1 = 90,name2 = ‘sl‘,score2 = ‘60‘)print(d1)print(d1.items())for key,value in d1.items():print(key,value)
并行迭代:同时迭代两个序列,
使用索引方式实现:
names = [‘zyj‘,‘sl‘,‘xh‘]ages = [‘10‘,‘20‘,‘30‘]for i in range(len(names)):print(names[i] +‘ is ‘+ ages[i]+‘ years old‘)
zip函数可以进行并行迭代,将两个序列“压缩”在一起。然后返回一个元组的列表或迭代器对象,注意:zip可以处理不等长的序列
names = [‘zyj‘,‘sl‘,‘xh‘]ages = [‘10‘,‘20‘,‘30‘]print(zip(names,ages))for name,age in zip(names,ages):print(name +‘ is ‘+ age+‘ years old‘)
#zip处理不等长的序列:以最短的序列为结束标志s = zip(range(5),range(10))for i,j in s:print(i,j)
按索引迭代enumerate函数迭代序列的索引-值对,返回的是索引-值对的元组迭代器
s1 = [‘hello‘,‘world‘]print(s1)print(enumerate(s1))for index,value in enumerate(s1): #遍历序列中所有的序列和值s1[index] = ‘hi‘ #将所有的元素进行替换,不可变序列不可替换print(index,s1[index])print(s1)
#返回不可变序列的索引-值对。
s2 = ‘hello‘
print(enumerate(s2))
for index,value in enumerate(s2):
print(index,value)
翻转和排序迭代: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!‘)))
列表推导式
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)
pass 语句什么都不做,可以作为占用符使用,
del 用来删除变量,或者数据结构的一部分,但是不能用来删除值,python有内建垃圾回收,会对值进行删除
exec:执行python程序
eval():函数对写在字符串中的表达式进行计算并返回结果
x = 1del xprint(x) #返回x未定义x = [‘hello‘,‘world‘]y = xy[1] = ‘python‘print(x)del xprint(y) #y为hello pythonexec ("print(‘hello,world‘)")from math import sqrtexec ("sqrt = 1")#print(sqrt(4)) #返回变量不可用from math import sqrtscope = {} #scope为放置代码字符串命名空间作用的字典exec("‘sqrt = 1‘in scope")print(sqrt(4))print(eval("2*3"))
ord()返回单字符字符串的int值
chr(n)返回n所代表的包含一个字符的字符串
print(ord("c")) #返回99print(chr(99)) #返回c
python语句
相关内容
- 暂无相关文章
评论关闭