Python学习6——条件,循环语句

条件语句

真值也称布尔值。

用作布尔表达式时,下面的值都将被视为假:False None  0   ""   ()   []   {}。

布尔值True和False属于类型bool,而bool与list、str和tuple一样,可用来转换其他的值。

>>> bool(‘I think,therefore I am‘)
True
>>> bool(10)
True
>>> bool(‘‘)
False
>>> bool(0)
False

if语句

>>> name = input(‘What is your name?‘)
What is your name?Gumby
>>> if name.endswith(‘Gumby‘):
    print(name)

Gumby

如果条件(if和冒号之间的表达式)是前面定义的真,就执行后续代码块,如果条件为假,就不执行。

else子句,elif子句,嵌套代码块

>>> name = input(‘What is your name?‘)
What is your name?Gumby
>>> if name.endswith(‘Gumby‘):
    if name.startswith(‘Mr.‘):
        print(‘Hello,Mr.Gumby‘)
    elif name.startswith(‘Mrs.‘):
        print(‘Hello,Mrs.Gumby‘)
    else:
        print(‘Hello,Gumby‘)
else:
    print(‘Hello,stranger‘)

Hello,Gumby

比较运算符:

表达式 描述
x == y x等于y
x < y x小于y
x > y x大于y
x >= y  x大于或等于y
x <= y x小于或等于y
x != y x不等于y
x is y x和y是同一个对象
x is not y x和y是不同的对象
x in y x是容器y的成员
x not in y x不是容器y的成员
>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False
>>> #is检查两个对象是否相同(不是相等),变量x和y指向同一个列表,而z指向另一个列表(即使它们包含的值是一样的),这两个列表虽然相等,但并非同一个列表。

ord函数可以获取字母的顺序值,chr函数的作用与其相反:

>>> ord(‘a‘)
97
>>> ord(‘v‘)
118
>>> chr(118)
‘v‘

断言:assert

>>> age = 10
>>> assert 0 < age < 11
>>> age = -1
>>> assert 0 < age < 11
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    assert 0 < age < 11
AssertionError
>>> age = -1
>>> assert 0 < age < 11,‘the age must be realistic‘ #字符串对断言做出说明
Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    assert 0 < age < 11,‘the age must be realistic‘ #字符串对断言做出说明
AssertionError: the age must be realistic

循环

while 循环

>>> name = ‘‘
>>> while not name.strip():        #屏蔽空格
    name = input(‘please enter your name:‘)
    print(‘hello,{}!‘.format(name))

please enter your name:Momo
hello,Momo!

for循环

>>> numbers = [0,1,2,3,4,5,6,7,8]
>>> for number in numbers:
    print(number)

0
1
2
3
4
5
6
7
8

内置函数range():

>>> range(0,10)
range(0, 10)
>>> list(range(0,10))  #范围[0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)     #如果只提供1个位置,将把这个位置视为结束位置,并假定起始位置为0
range(0, 10)
>>> for num in range(1,10):
    print(num)

1
2
3
4
5
6
7
8
9

迭代字典:

>>> d = dict(a=1,b=2,c=3)
>>> d
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
>>> for key in d:
    print(key,‘to‘,d[key])

a to 1
b to 2
c to 3

换一种方式迭代:

>>> for key,value in d.items():
    print(key,‘to‘,value)

a to 1
b to 2
c to 3
>>> d.items()
dict_items([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])

并行迭代:

同时迭代2个序列。

>>> names = [‘aaa‘,‘bbb‘,‘ccc‘]
>>> ages = [10,11,12]
>>> for i in range(len(names)):
    print(names[i],‘is‘,ages[i],‘years old‘)

aaa is 10 years old
bbb is 11 years old
ccc is 12 years old

内置函数zip,可以将2个序列缝合起来,并返回一个由元组组成的序列。

>>> list(zip(names,ages))
[(‘aaa‘, 10), (‘bbb‘, 11), (‘ccc‘, 12)]
>>> for name,age in zip(names,ages):
    print(name,‘is‘,age,‘years old‘)

aaa is 10 years old
bbb is 11 years old
ccc is 12 years old

zip函数可以缝合任意数量的序列,当序列的长度不同时,zip函数将在最短的序列用完后停止缝合。

>>> list(zip(range(5),range(10)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

迭代时获取索引:

>>> strings = [‘aac‘,‘ddd‘,‘aa‘,‘ccc‘]
>>> for string in strings:
    if ‘aa‘ in string:         #替换列表中所有包含子串‘aa’的字符串
        index = strings.index(string)    #在列表中查找字符串
        strings[index] = ‘[censored]‘

>>> strings
[‘[censored]‘, ‘ddd‘, ‘[censored]‘, ‘ccc‘]

优化一下:

>>> strings = [‘aac‘,‘ddd‘,‘aa‘,‘ccc‘]
>>> index = 0
>>> for string in strings:
    if ‘aa‘ in string:
        strings[index] = ‘[censored]‘
    index += 1

>>> strings
[‘[censored]‘, ‘ddd‘, ‘[censored]‘, ‘ccc‘]

继续优化:

内置函数enumerate能够迭代索引-值对,其中的索引是自动提供的。

>>> strings = [‘aac‘,‘ddd‘,‘aa‘,‘ccc‘]
>>> for index,string in enumerate(strings):
    if ‘aa‘ in string:
        strings[index] = ‘[censored]‘
>>> strings
[‘[censored]‘, ‘ddd‘, ‘[censored]‘, ‘ccc‘]

反向迭代和排序后在迭代:

>>> sorted([4,2,5,1,3])
[1, 2, 3, 4, 5]
>>> sorted(‘hello,world‘)   #sorted返回一个列表
[‘,‘, ‘d‘, ‘e‘, ‘h‘, ‘l‘, ‘l‘, ‘l‘, ‘o‘, ‘o‘, ‘r‘, ‘w‘]
>>> list(reversed(‘Hello,world‘))   #reversed返回一个可迭代对象,
[‘d‘, ‘l‘, ‘r‘, ‘o‘, ‘w‘, ‘,‘, ‘o‘, ‘l‘, ‘l‘, ‘e‘, ‘H‘]
>>> ‘‘.join(reversed(‘Hello,world‘))
‘dlrow,olleH‘
>>> sorted(‘aBc‘,key=str.lower)   #按照字母表排序,可以先转换为小写
[‘a‘, ‘B‘, ‘c‘]

break 跳出循环

>>> from math import sqrt
>>> for n in range(99,1,-1):   #找出2-100的最大平方值,从100向下迭代,找到第一个平方值后,跳出循环。步长为负数,让range向下迭代。
    root = sqrt(n)
    if root == int(root):    #开平方为整
        print(n)
        break

81

while True/break

>>> while True:    #while True导致循环永不结束
    word = input(‘enter your name:‘)
    if not word:break   #在if语句中加入break可以跳出循环
    print(word)

enter your name:aa
aa
enter your name:bb
bb
enter your name:
>>> 

简单推导

列表推导式一种从其他列表创建列表的方式,类似于数学中的集合推导。

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

打印能被3整除的平方值

>>> [x*x for x in range(10) if x%3 == 0]
[0, 9, 36, 81]

使用多个for部分,将名字的首字母相同的男孩和女孩配对。

>>> girls = [‘aaa‘,‘bbb‘,‘ccc‘]
>>> boys = [‘crde‘,‘bosy‘,‘adeb‘]
>>> [b+‘+‘+g for b in boys for g in girls if b[0]==g[0]]
[‘crde+ccc‘, ‘bosy+bbb‘, ‘adeb+aaa‘]

上面的代码还能继续优化:

>>> girls = [‘aaa‘,‘bbb‘,‘ccc‘]
>>> boys = [‘crde‘,‘bosy‘,‘adeb‘]
>>> letterGrils = {}
>>> for girl in girls:
    letterGrils.setdefault(girl[0],[]).append(girl)   #每项的键都是一个字母,值为该字母开头的女孩名字组成的列表

>>> print([b+‘+‘+g for b in boys for g in letterGrils[b[0]]])
[‘crde+ccc‘, ‘bosy+bbb‘, ‘adeb+aaa‘]

字典推导

>>> squares = {i:‘{} squared is {}‘.format(i,i**2) for i in range(10)}
>>> squares[8]
‘8 squared is 64‘

原文地址:https://www.cnblogs.com/suancaipaofan/p/11070937.html

时间: 2024-08-10 18:46:31

Python学习6——条件,循环语句的相关文章

python基础之条件循环语句

前两篇说的是数据类型和数据运算,本篇来讲讲条件语句和循环语句. 0x00. 条件语句 条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: Python interprets non-zero values as True. None and 0 are interpreted as False. Python 判断非0的值为 True, 而None和0被认为是 False.注意这里的True和False首字母大写,Py

python学习:利用循环语句完善输入设置

利用循环语句完善输入设置 使用for循环: 代码1:_user = "alex"_password = "abc123" for i in range(3): username = input("Username:") password = input("Password:") if username == _user and password == _password: print("Welcome %s logi

python学习笔记七:条件&循环语句

1.print/import更多信息 print打印多个表达式,使用逗号隔开 >>> print 'Age:',42 Age: 42   #注意个结果之间有一个空格符 import:从模块导入函数 import 模块 from 模块 import 函数 from 模块 import * 如果两个模块都有open函数的时候, 1)使用下面方法使用: module1.open()... module2.open()... 2)语句末尾增加as子句 >>> import ma

九、while 条件循环语句、case 条件测试语句、计划任务服务程序

4.3.3 while条件循环语句 while条件循环语句是一种让脚本根据某些条件来重复执行命令的语句,它的循环结构往往在执行前并不确定最终执行的次数,完全不同于for循环语句中有目标.有范围的使用场景.while循环语句通过判断条件测试的真假来决定是否继续执行命令,若条件为真就继续执行,为假就结束循环.while语句的语法格式如图4-21所示. 图4-21  while循环语句的语法格式 接下来结合使用多分支的if条件测试语句与while条件循环语句,编写一个用来猜测数值大小的脚本Guess.

python代码缩进和循环语句2

我们接着讲for函数. range()函数和len()函数常常一起用于字符串索引,这里我们要显示每一个的元素及其索引值. #小插曲,在cmd中,清除屏幕的方法是输入cls,即 clean screen. 让我们分析一下这个语句. foo='abc' for i in range(len(foo)): print foo[i],'%d'%i    #值得注意的地方是,这个%d,的后面,要加个%i,意思是,%d要从i里面取值. [称作格式化输出.] a '0' b '1' c '2' 先输出a,我们

Python学习_05_条件、循环

条件 和其他语言类似,python中使用if...elif...else来形成分支,支持三目操作符 ?:,python中没有switch,但是缩进的特性让if...elif...else的结构同样便于阅读 循环控制 python中除了break,continue这两个一般的循环控制语句之外,还有一个pass,执行空操作.由于python的语法特性,添加pass可以留空某一个域,避免在调试过程中反复报错. while循环 python中的while循环比其他语言增加了一个特性:支持else.在其他

Python语言学习前提:循环语句

一.循环语句 1.循环语句:允许执行下一个语句或语句组多次 2. 循环类型 3. 循环控制语句 4. while 循环语句 a.while循环语句:在某个条件下,循环执行某段程序,以处理需要重复处理的相同任务 while 判断条件(condition): 执行语句(statements)...... b. continue 和 break 用法 #! /usr/bin/env python i = 1 while i < 10: i +=1 if i%2 >0: #非双数时跳过输出 conti

python 学习笔记day02-python循环、文件、函数、模块

循环语句 while 循环 while 循环语法结构 当需要语句不断的重复执行时,可以使用 while 循环 while expression: while_sutie 语句 while_suite 会被连续不断的循环执行,直到表达式的值变成 0 或 False         #!/usr/bin/env python         # -- coding: utf-8 --         sum100 = 0         counter = 1         while count

python学习之while循环

Python While 循环语句 Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while 判断条件: 执行语句-- 执行语句可以是单个语句或语句块.判断条件可以是任何表达式,任何非零.或非空(null)的值均为true. 当判断条件假false时,循环结束. 执行流程图如下: while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break

python(四)循环语句

条件判断与循环语句 目录: 1.python循环语句介绍 2.条件判断  [if ,elif, else] 3.循环语句  [for,while] Python 循环语句 前提:如果让你1-100之间的整数,你用程序应该怎么实现. 本章节将向大家介绍Python的循环语句,程序在一般情况下是按顺序执行的. 编程语言提供了各种控制结构,允许更复杂的执行路径. 循环语句允许我们执行一个语句或语句组多次,下面是在大多数编程语言中的循环语句的一般形式: Python提供了for循环和while循环 循环