python快速入门【三】-----For 循环、While 循环
python入门合集:
python快速入门【三】-----For 循环、While 循环
For 循环
For循环是迭代对象元素的常用方法(在第一个示例中,列表)
具有可迭代方法的任何对象都可以在for循环中使用。
python的一个独特功能是代码块不被{} 或begin,end包围。相反,python使用缩进,块内的行必须通过制表符缩进,或相对于周围的命令缩进4个空格。
虽然这一开始可能看起来不直观,但它鼓励编写更易读的代码,随着时间的推移,你会学会喜欢它
In [1]
#取第一个列表成员(可迭代),暂称它数字(打印它)
#取列表的第二个成员(可迭代),暂时将其称为数字,等等......
for number in [23, 41, 12, 16, 7]:
print(number)
print('Hi')
23
41
12
16
7
Hi
枚举
返回一个元组,其中包含每次迭代的计数(从默认为0开始)和迭代序列获得的值:
In [2]
friends = ['steve', 'rachel', 'michael', 'adam', 'monica']
for index, friend in enumerate(friends):
print(index,friend)
0 steve
1 rachel
2 michael
3 adam
4 monica
Task
从文本中删除标点符号并将最终产品转换为列表:
On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way
(加州旅馆)
In [3]
text = '''On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way'''
In [4]
print(text)
On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way
基本上,任何具有可迭代方法的对象都可以在for循环中使用。即使是字符串,尽管没有可迭代的方法 - 但我们不会在这里继续。具有可迭代方法基本上意味着数据可以以列表形式呈现,其中有序地存在多个值。
In [5]
for char in '-.,;\n"\'':
text = text.replace(char,' ')
print(text)
On a dark desert highway cool wind in my hair Warm smell of colitas rising up through the air Up ahead in the distance I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway I heard the mission bell And I was thinking to myself This could be Heaven or this could be Hell Then she lit up a candle and she showed me the way
In [6]
# Split converts string to list.
# Each item in list is split on spaces
text.split(' ')[0:20]
['On',
'a',
'dark',
'desert',
'highway',
'',
'cool',
'wind',
'in',
'my',
'hair',
'Warm',
'smell',
'of',
'colitas',
'',
'rising',
'up',
'through',
'the']
In [7]
# Dont want to have non words in my list for example ''
# which in this case are things of zero length
len('')
0
In [8]
# Making new list with no empty words in it
cleaned_list = []
In [9]
for word in text.split(' '):
word_length = len(word)
if word_length > 0:
cleaned_list.append(word)
In [10]
cleaned_list[0:20]
['On',
'a',
'dark',
'desert',
'highway',
'cool',
'wind',
'in',
'my',
'hair',
'Warm',
'smell',
'of',
'colitas',
'rising',
'up',
'through',
'the',
'air',
'Up']
Continue
continue语句将转到循环的下一次迭代
continue语句用于忽略某些值,但不会中断循环
In [11]
cleaned_list = []
for word in text.split(' '):
if word == '':
continue
cleaned_list.append(word)
cleaned_list[1:20]
['a',
'dark',
'desert',
'highway',
'cool',
'wind',
'in',
'my',
'hair',
'Warm',
'smell',
'of',
'colitas',
'rising',
'up',
'through',
'the',
'air',
'Up']
Break
break语句将完全打断循环
In [12]
cleaned_list = []
In [13]
for word in text.split(' '):
if word == 'desert':
print('I found the word I was looking for')
break
cleaned_list.append(word)
cleaned_list
I found the word I was looking for
['On', 'a', 'dark']
Task (顺道介绍一下Range函数)
- 编写一个Python程序,它迭代整数从1到50(使用for循环)。对于偶数的整数,将其附加到列表even_numbers。对于奇数的整数,将其附加到奇数奇数列表中
In [14]
# Making empty lists to append even and odd numbers to.
even_numbers = []
odd_numbers = []
for number in range(1,51):
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
In [15]
print("Even Numbers: ", even_numbers)
Even Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
In [16]
print("Odd Numbers: ", odd_numbers)
Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
Python 2 vs Python 3 (Range函数的不同点)
python 2 xrange and python 3 range are same (resembles a generator) python 2 range生成一个list
注意: 较长的列表会很慢
更多参考: http://pythoncentral.io/pythons-range-function-explained/
While 循环
| For 循环 | While 循环 |
|---|---|
| 遍历一组对象 | 条件为false时自动终止 |
| 没有break也可以结束 | 使用break语句才能退出循环 |
如果我们希望循环在某个时刻结束,我们最终必须使条件为False
In [1]
# Everytime through the loop, it checks condition everytime until count is 6
# can also use a break to break out of while loop.
count = 0
while count <= 5:
print(count)
count = count + 1
0
1
2
3
4
5
break语句
使用break可以完全退出循环
In [2]
count = 0
while count <= 5:
if count == 2:
break
count += 1
print (count)
1
2
while True条件使得除非遇到break语句,否则不可能退出循环
如果您陷入无限循环,请使用计算机上的ctrl + c来强制终止
In [3]
num = 0
while True:
if num == 2:
print('Found 2')
break
num += 1
print (num)
1
2
Found 2
提醒:使用模运算符(%),它将数字左边的余数除以右边的数字
In [4]
# 1 divided by 5 is 0 remainder 1
1 % 5
1
In [5]
# 5 divided by 5 is 0 remainder 0
5 % 5
0
| 比较操作符 | 功能 |
|---|---|
| < | 小于 |
| <= | 小于或等于 |
| 大于 = | 大于或等于 == | 等于 != | 不等于
In [6]
x = 1
while x % 5 != 0:
x += 1
print(x)
2
3
4
5
当我们知道要循环多少次时,Range很有用
下面例子是: 从0开始,但不包括5
In [7]
candidates = list(range(0, 5))
candidates
[0, 1, 2, 3, 4]
In [8]
while len(candidates) > 0:
first = candidates[0]
candidates.remove(first)
print(candidates)
[1, 2, 3, 4]
[2, 3, 4]
[3, 4]
[4]
[]
python快速入门【三】-----For 循环、While 循环的更多相关文章
- Python快速入门PDF高清完整版免费下载|百度云盘
百度云盘:Python快速入门PDF高清完整版免费下载 提取码:w5y8 内容简介 这是一本Python快速入门书,基于Python 3.6编写.本书分为4部分,第一部分讲解Python的基础知识,对 ...
- Python快速入门
Python快速入门 一.基础概要 命名:h.py Linux命令行运行:python h.py 注释.数字.字符串: 基本类型只有数字与字符串 #python注释是这样写的 ''' 当然也可以这样 ...
- 3.Python爬虫入门三之Urllib和Urllib2库的基本使用
1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它是一段HTML代码,加 JS.CSS ...
- 转 Python爬虫入门三之Urllib库的基本使用
静觅 » Python爬虫入门三之Urllib库的基本使用 1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器 ...
- python快速入门及进阶
python快速入门及进阶 by 小强
- Python系列:三、流程控制循环语句--技术流ken
Python条件语句 Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: Python程序语言指定任何非0和非 ...
- python基础入门之二 —— 条件、循环语句
1.条件语句 if if…else… 多重if if嵌套 三目运算符 (化简的if else) if 条件: 条件成立执行代码1 条件成立执行代码2 if False: print('if判断 ...
- php之快速入门学习-14(php-for循环)
PHP 循环 - For 循环 循环执行代码块指定的次数,或者当指定的条件为真时循环执行代码块. for 循环 for 循环用于您预先知道脚本需要运行的次数的情况. 语法 for (初始值; 条件; ...
- Python快速入门之与C语言异同
代码较长,建议使用电脑阅读本文. 10分钟入门Python 本文中使用的是Python3如果你曾经学过C语言,阅读此文,相信你能迅速发现这两种语言的异同,达到快速入门的目的.下面将开始介绍它们的异同. ...
- Python与C语言基础对比(Python快速入门)
代码较长,建议使用电脑阅读本文. 10分钟入门Python 本文中使用的是Python3 如果你曾经学过C语言,阅读此文,相信你能迅速发现这两种语言的异同,达到快速入门的目的.下面将开始介绍它们的异同 ...
随机推荐
- ChatGPT访问互联网,不神秘了
我测试了一下,它其实调用了微软必应的api,搜索了关键词而已 比如我问它:https://twitter.com/elonmusk 马斯克最近在忙什么 它的回答是: 近期,马斯克在做的一些事情包括: ...
- BP 供应商创建与修改
1业务场景 BP中,供应商和客户的创建发生了很大变化,之前的BAPI无法使用,本文档采用新的方法创建供应商. 2创建 2.1业务伙伴 2.2添加BP角色 2.3维护银行数据 2.4维护类别税号数据 2 ...
- 【3rd_Party】format() 处理一些常见的格式化解决方案
fmt的痛与对format设计的思考 fmt:轻量高性能的C++格式化库 C++20 引入了新的 format() 函数,该函数以字符串形式返回参数的格式化表示.format() 使用 python ...
- 【第三方库】从编译到运行,轻松学会gflags库
gflags是Google开源的一个库,可以很方便地定义一些全局变量,并且可以从命令行设置他们的值,广泛应用于各个项目中以及自己平时的开发中.本期参考gflags的官方文档,简单直接介绍下怎么使用这个 ...
- AtCoder Educational DP Contest 刷题记录
写在前面 深感自己 DP 很弱的 村人B 刷了点 DP 题,题集地址戳这里. 后记:刷完后感觉自己又行了 A - Frog 1 题意 给定 \(n\) 个石头,第 i 个石头的高度为 \(h_i\). ...
- 2012年第三届蓝桥杯【C++省赛B组】
第一题:微生物增殖 假设有两种微生物 X 和 Y X出生后每隔3分钟分裂一次(数目加倍),Y出生后每隔2分钟分裂一次(数目加倍). 一个新出生的X,半分钟之后吃掉1个Y,并且,从此开始,每隔1分钟吃1 ...
- 智慧地产-售楼中心 3D 沙盘可视化
前言 随着"互联网+房地产"走入全国各大地产项目,房企依托互联网将房地产从传统地产转向智慧地产已然是眼下用户最欢迎的转型模式.智慧地产是由智慧社区.智慧园区.智慧公寓及智能家居等组 ...
- linux驱动开发中copy_from_user open read write等常用函数总结
目录 open read write copy_to_user copy_from_user open 函数定义: int open( const char * pathname, int flags ...
- C#设计模式16——中介者模式的写法
是什么: 中介者模式是一种行为型设计模式,它定义了一个中介者对象来封装一系列对象之间的交互.中介者模式可以使得对象间的交互更加松耦合,避免了对象之间的直接依赖,从而使系统更加灵活.易于扩展和维护. 为 ...
- C# 加解密
1. Md5 /// <summary> /// 不可逆加密 /// 1 防止被篡改 /// 2 防止明文存储 /// 3 防止抵赖,数字签名 /// </summary> ...