python运算符以及简单语句

1、布尔类型

bool类型的值:True 1 和 False 0

可进行四则运算

注意首字母大写

1.1比较运算

比较两个对象:
• 符号:>, < =, !=, >=, <=
• 同种类型对象比较
• 返回值:True和False

>>> True + True
2
>>> True *3
3
>>> int(False)
0
>>> bool(0)
False

1.2逻辑运算(布尔运算)

and

>>> False and 3
False
>>> 0 and 3
0
>>> 3>2 and 4>3
True
>>> 3>2 and 4
4

or

>>> 3 or 0
3
>>> 0 or 3
3

not 否定一切

>>> not 3
False
>>> not 0
True

2、简单的语句

import语句

Import module
Import module as new_name
From odule import function
From odule import function as new_name
From odule import *

>>> import math as shuxue
>>> shuxue.pi
3.141592653589793
>>> from math import pi
>>> pi
3.141592653589793

赋值语句

基本形式:variable = object
其他花样:

>>> a = 1,2,3
>>> a
(1, 2, 3)
>>> a,b,c = 1,2,3
>>> a,b,c
(1, 2, 3)
>>> a
1
>>> b
2
>>> c
3
>>> a,_,c = 1,2,3
>>> a,c
(1, 3)
>>> _
2
>>> a,*b = 1,2,3
>>> a
1
>>> b
[2, 3]
>>> a = b = a
>>> b
1
>>> a
1
>>> a = a+1
>>> a
2
>>> a += 1
>>> a
3
>>> a -= 2
>>> a
1
>>> a *= 2
>>> a
2
>>> a /= 2
>>> a
1.0

3、条件语句if

'''
编写程序,随机生成10以内的一个整数,如果该数字大于圆周率
π,就将其当做直径计算圆的周长和面积;否则当做半径计算圆
的周长和面积。最后将计算结果输出。
'''
import random
import mathn = random.randint(1, 10)
if n > math.pi:perimeter = n * math.piarea = math.pi * (n / 2) ** 2
else:perimeter = 2 * n * math.piarea = math.pi * pow(n, 2)print("random n is: ", n)
print("Perimeter is: ", round(perimeter, 2))
print('Area is: ', round(area, 2))

条件语句写成一行,三元操作

>>> x = 2
>>> a = 'python' if x > 2 else "physics"
>>> a
'physics'

4、循环语句for

>>> for i in 'hello':print(i)h
e
l
l
o>>> lst = [1, 2, 3, 4]
>>> for i in lst:print(i, i+10)1 11
2 12
3 13
4 14>>> d = {'name':'winner','lang':'python','age':'18'}
>>> for k in d:print(k)name
lang
age
>>> for k in d:print(k,d[k])name winner
lang python
age 18
>>> dt = {}
>>> for k in d:dt[d[k]] = k>>> dt
{'winner': 'name', 'python': 'lang', '18': 'age'}
>>> for k,v in d.items():print(k,v)name winner
lang python
age 18

可迭代对象

>>> help(iter)
Help on built-in function iter in module builtins:iter(...)iter(iterable) -> iteratoriter(callable, sentinel) -> iteratorGet an iterator from an object.  In the first form, the argument mustsupply its own iterator, or be a sequence.In the second form, the callable is called until it returns the sentinel.

判断一个对象是否是可迭代对象:

使用 dir() 函数,查看是否有 iter

'''
例题:创建一个数据集,包含1到10的随机整数,共计100个数。
并统计每个数字的次数。
'''import randomlst = []
for i in range(100):n = random.randint(1,10)lst.append(n)
print(lst)d = {}
for n in lst:if n in d:d[n] += 1else:d[n] = 1
print(d)

for循环中几个常用的函数

range()

class range(object)|  range(stop) -> range object|  range(start, stop[, step]) -> range object|  |  Return an object that produces a sequence of integers from start (inclusive)|  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.|  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.|  These are exactly the valid indices for a list of 4 elements.|  When step is given, it specifies the increment (or decrement).

range(0, 4)产生的是迭代器对象,不会被读入内存中,此时不会占用内存资源,只有被使用时才拿到内存中

>>> r = range(4)
>>> r
range(0, 4)
>>> type(r)
<class 'range'>
>>> for i in r:print(i)0
1
2
3
>>> list(range(100))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> lst = []
>>> for i in range(100):if i%3 == 0:lst.append(i)>>> lst
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
>>> list(range(0,100,3))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

zip()

zip(*iterables) --> A zip object yielding tuples until an input is exhausted.|  |     >>> list(zip('abcdefg', range(3), range(4)))|     [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]|  |  The zip object yields n-length tuples, where n is the number of iterables|  passed as positional arguments to zip().  The i-th element in every tuple|  comes from the i-th iterable argument to zip().  This continues until the|  shortest argument is exhausted.
>>> a = 'qiwsir'
>>> b = 'python'
>>> z = zip(a,b)
>>> list(z)
[('q', 'p'), ('i', 'y'), ('w', 't'), ('s', 'h'), ('i', 'o'), ('r', 'n')]
>>> c = [1,2,3]
>>> d = [4,5,6,7]
>>> list(zip(c,d))
[(1, 4), (2, 5), (3, 6)]
>>> c = [1,2,3,4,5]
>>> d = [5,6,7,8,9]
>>> r = []
>>> for i in range(len(c)):r.append(c[i] + d[i])>>> r
[6, 8, 10, 12, 14]
>>> r2 = []
>>> for x,y in zip(c,d):r2.append(x+y)>>> r2
[6, 8, 10, 12, 14]

enumerate()

class enumerate(object)|  enumerate(iterable, start=0)|  |  Return an enumerate object.|  |    iterable|      an object supporting iteration|  |  The enumerate object yields pairs containing a count (from start, which|  defaults to zero) and a value yielded by the iterable argument.|  |  enumerate is useful for obtaining an indexed list:|      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
返回序列中所有元素及其索引
>>> list(enumerate(s))
[(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four')]>>> lst = [1,5,3,20,6,2,7]
>>> for i in range(len(lst)):if lst[i] % 2 == 0;
>>> lst
[1, 5, 3, 'even', 'even', 'even', 7]>>> lst = [1,5,3,20,6,2,7]
>>> for i,ele in enumerate(lst):if ele%2 == 0:lst[i] = 'even'
>>> lst
[1, 5, 3, 'even', 'even', 'even', 7]

列表解析

>>> lst = []
>>> for i in range(10):lst.append(i**2)
>>> lst
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
>>> [i**2 for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
>>> [i for i in range(100) if i%3==0]
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
>>>
'''
字符串s = ‘Life is hort You ned python’。统计这个字符串
中每个单词的字母数量。
'''s = 'Life is short You need python'd = {}
for letter in s:if letter.isalpha():if letter in d:d[letter] += 1else:d[letter] = 1
print(d)

5、while循环语句

while [conditon]:
staements

a = 0
while a < 3:s = input('input your lang:')if s == "python":print("your lang is{0}".format(s))breakelse:a += 1print("a=",a)
print('the end a:',a)

continue:终止当次循环,不执行下面的代码,直接进入下一次循环

break:在当前位置终止循环并跳出整个循环体,执行循环体下面的代码

a = 11
while a > 0:a -= 1if a % 2 == 0:continueprint(a)else:print(a)
'''
例题:制作一个满足如下功能的猜数游戏:
• 计算机随机生成一个10以内的正整数;
• 用户通过键盘输入数字,猜测计算机所生成的随机数。
• 注意:对用户的输入次数不做限制。
'''
import random
number = random.randint(1,100)while True:num_input = input('input a number:')if not num_input.isdigit():print('Please input interger.')elif int(num_input) < 0 or int(num_input) >= 100:print("The number should be in 1 to 100.")else:if number == int(num_input):print('OK')breakelif number > int(num_input):print('your number is smaller.')else:print('your number is bigger.')

【python学习笔记】python运算符以及简单语句相关推荐

  1. python学习笔记(九)之语句1

    python学习笔记(九)之语句1 print python2中,print是一个语句,python3中它是一个函数. 实例1: >> print "hello,world!&q ...

  2. python学习笔记之运算符

    目录 前言 软件环境 身份运算符 算术运算符 比较运算符 位移运算符 自变运算符 位运算符 逻辑运算符 成员关系运算符 Python真值表 最后 前言 在前面的博文介绍了Python的数据结构之后,接 ...

  3. Python学习笔记-Python 条件语句

    Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: Python程序语言指定任何非0和非空(null)值为tr ...

  4. Python学习笔记——Python和基础知识

    Python优缺点 优点 简单----Python是一种代表简单主义思想的语言.阅读一个良好的Python程序就感觉像是在读英语一样,尽管这个英语的要求非常严格!Python的这种伪代码本质是它最大的 ...

  5. Python学习笔记 - Python数据类型

    前言 在Python语言中,所有的数据类型都是类,每一个变量都是类的"实例".没有基本数据类型的概念,所以整数.浮点数和字符串也都是类. Python有6种标准数据类型:数字.字符 ...

  6. (转载)[python学习笔记]Python语言程序设计(北理工 嵩天)

    作者:九命猫幺 博客出处:http://www.cnblogs.com/yongestcat/ 欢迎转载,转载请标明出处. 如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐 阅读 ...

  7. Python学习笔记 Python概述 编码规范 输出与输入 变量 标识符

    Python学习第一天 Python的概述 1.Python的优缺点 1.1 优点: 1.2 缺点: 2.Python的编码规范 3.注释 3.Python的输出与输入 4.Python中的变量 5. ...

  8. Python学习笔记--Python字符串连接方法总结

    声明: 这些总结的学习笔记,一部分是自己在工作学习中总结,一部分是收集网络中的知识点总结而成的,但不到原文链接.如果有侵权,请知会,多谢. python中有很多字符串连接方式,总结一下: 1)最原始的 ...

  9. Python学习笔记 - Python语言概述和开发环境

    一.Python简介 1.1  Python语言简史 Python由荷兰人吉多·范罗苏姆(Guido van Rossum)于1989年圣诞节期间,在阿姆斯特丹,为了打发圣诞节的无聊时间,决心开发一门 ...

  10. Python学习笔记 - Python语法基础

    前言 本篇博文主要介绍Python中的一些最基础的语法,其中包括标识符.关键字.内置函数.变量.常量.表达式.语句.注释.模块和包等内容. 一.标识符.关键字和内置函数 任何一种语言都离不开标识符和关 ...

最新文章

  1. post传参部分数据丢失
  2. 2019牛客提前批一血:猝不及防的java实习面经
  3. 英语语法---不定式短语详解
  4. 20175213 2018-2019-2 《Java程序设计》第6周学习总结
  5. .net应用程序版本控制
  6. 使用Mysql进行分页与排序
  7. CentOS7中的firewall 和 iptables
  8. c#如何取得事件注册的方法
  9. linux网卡配置规范
  10. java_面试题WH_W
  11. 在计算机上最常用的英语单词,计算机常用英语单词
  12. [Python人工智能] 四.神经网络和深度学习入门知识
  13. 《后端》bug: java.lang.IllegalArgumentException: geronimo.jta.1.1.spec: Invalid module name: ‘1‘ is not
  14. shell批量修改文件后缀名
  15. 光通信的再思考:5G流量爆发下的数据密度革命
  16. STM32 HAL库详解
  17. AndroidStudio请求网络数据,把解析出来的数据放在listview里
  18. 敏捷开发的项目管理工具分享
  19. 有关光照模块的具体问题及解决方案
  20. wps浏览器插件(wps online) webwps

热门文章

  1. c语言2维数组每一行最小值,二维数组每一行最大值
  2. K8s预选策略和优选函数简介
  3. OTP(OneTimeProgrammable)开发之义隆仿真器
  4. 普通人除了打工,究竟如何才能赚到钱?
  5. python中abs和fabs的区别_abs()与fabs()的速度差异和fabs()的优势
  6. 高通骁龙MSM8916核心板 ARM Cortex-A53 四核 中文资料
  7. c语言实现求一个矩阵特征值和特征向量
  8. java word转html乱码怎么办,poi导出word 乱码 poi word转html 乱码
  9. 指数灰度变换法 matlab,matlab指数灰度变换
  10. HDU 4960:Another OCD Patient