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
>>>
python语句的更多相关文章
- divmod(a,b)函数是实现a除以b,然后返回商与余数的元组、eval可以执行一个字符串形式的表达式、exec语句用来执行储存在字符串或文件中的Python语句
#!/usr/bin/env python a = 10/3 print(a) #divmod计算商与余数 r = divmod(10001,20) print(r) #eval可以执行一个字符串形式 ...
- 《Python 学习手册4th》 第十章 Python语句简介
''' 时间: 9月5日 - 9月30日 要求: 1. 书本内容总结归纳,整理在博客园笔记上传 2. 完成所有课后习题 注:“#” 后加的是备注内容 (每天看42页内容,可以保证月底看完此书) “重点 ...
- 在 C 代码中嵌入 Python 语句或使用 Python 模块 (Visual Studio 2013 环境设置)
1) 新建一个 内嵌 Python 语句的 C 代码, // This is a test for check insert the Python statements or module in C. ...
- python语句和语法
python语句和语法 python程序结构: 1.程序由模块构成. 2.模块包含语句. 3.语句包含表达式. 4.表达式建立并处理对象. python的语法实质上是有语句和表达式组成的.表达式处理对 ...
- 算法笔试过程中的几个输入输出python语句
title: python在线笔试学习笔记 localimage: image1 urlname: writenexam categories: summary tags: [writen, exam ...
- python语句结构(控制语句与pass语句)
python语句结构(控制语句和pass语句) break-跳出循环:语句可以跳出for和while语句的循环体.如果你从for和while循环中终止,任何对应循环的else语块均终止 continu ...
- python语句结构(range函数)
python语句结构(range函数) range()函数 如果你需要遍历数字序列,可以使用内置range()函数,它会生成序列 也可以通过range()函数指定序列的区间 也可以使用range()函 ...
- python语句结构(if判断语句)
一.python语句结构分类 条件控制语句:if 语句 if....elif语句 if嵌套 循环语句:while语句 for循环 控制语句:break.continue.pass语句 二.pyt ...
- 关于tf.cond函数中“正确”与“错误”函数中的普通python语句始终执行的问题
import tensorflow as tf import numpy as np x = tf.constant(2) y = tf.constant(3) global mask0 mask0 ...
- python语句与函数
赋值语句 : 分支语句 : 函数 :根据输入参数产生不同输出功能 程序的输入与输出 input() 从控制台获得用户输入的函数 使用格式 print()函数 以字符形式向控制台输出结果的函数 字符类型 ...
随机推荐
- webview滑动事件 与内部html左右滑动事件冲突问题的解决办法
最近在做个混合app , 用html做页面,然后通过webview嵌套在activity中,效果是这样: 开始还是比较顺利,增加了菜单退出按钮,返回键页面回退功能,页面加载显示加载图标(在app端实现 ...
- Codeforces VK CUP 2015 D. Closest Equals(线段树+扫描线)
题目链接:http://codeforces.com/contest/522/problem/D 题目大意: 给你一个长度为n的序列,然后有m次查询,每次查询输入一个区间[li,lj],对于每一个查 ...
- iOS开发——高级篇——通讯录
一.简介 1.如何访问用户的通讯录1)在iOS9之前有2个框架可以访问用户的通讯录AddressBookUI.framework提供了联系人列表界面.联系人详情界面.添加联系人界面等一般用于选择联系人 ...
- BZOJ4551——[Tjoi2016&Heoi2016]树
1.题意: 给定一颗有根树(根为1),有以下 两种操作:1. 标记操作:对某个结点打上标记(在最开始,只有结点1有标记,其他结点均无标记,而且对于某个 结点,可以打多次标记.)2. 询问操作:询问某个 ...
- mount挂载问题
安装nfs-utils即可
- 两个已排序数组进行合并后的第K大的值--进军硅谷
我看到此题时,首先想到一个一个比较遍历过去,这是最暴力的方法,后面我想到了已经排序,那么对每个数组进行二分,然后比较这两个值.此书第三种解法,挺不错,只对那个长度较小的数组进行二分查找,保证i+j-1 ...
- ASM:《X86汇编语言-从实模式到保护模式》越计卷:实模式下对DMA和Sound Blaster声卡的控制
说实话越计卷作者用了16页(我还是删过的),来讲怎么控制声卡,其实真正归纳起来就那么几点. ★PART1:直接存储访问 1. 总线控制设备(bus master) 在硬件技术不发达的早期,处理器是最重 ...
- MVC+Easeyui dialog的小问题
今天在尝试 MVC+Easyui的练习中遇到的一些,小问题. 在.net MVC 中 在_layout.cshtml中设置Easyui 环境 ,在传到子页中,发现$("#dlg" ...
- C# 如何用多个字符串来切分字符串并去除空格
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...
- 《图形学》实验六:中点Bresenham算法画圆
开发环境: VC++6.0,OpenGL 实验内容: 使用中点Bresenham算法画圆. 实验结果: 代码: #include <gl/glut.h> #define WIDTH 500 ...