首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python快速入门【三】-----For 循环、While 循环

python快速入门【三】-----For 循环、While 循环

作者头像
汀丶人工智能
发布于 2022-12-01 07:46:04
发布于 2022-12-01 07:46:04
54100
代码可运行
举报
文章被收录于专栏:NLP/KGNLP/KG
运行总次数:0
代码可运行

python入门合集:

python快速入门【一】-----基础语法

python快速入门【二】----常见的数据结构

python快速入门【三】-----For 循环、While 循环

python快速入门【四】-----各类函数创建

python快速入门【五】---- 面向对象编程

python快速入门【六】----真题测试


For 循环

For循环是迭代对象元素的常用方法(在第一个示例中,列表)

具有可迭代方法的任何对象都可以在for循环中使用。

python的一个独特功能是代码块不被{} 或begin,end包围。相反,python使用缩进,块内的行必须通过制表符缩进,或相对于周围的命令缩进4个空格。

虽然这一开始可能看起来不直观,但它鼓励编写更易读的代码,随着时间的推移,你会学会喜欢它

In 1

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#取第一个列表成员(可迭代),暂称它数字(打印它)
#取列表的第二个成员(可迭代),暂时将其称为数字,等等......

for number in [23, 41, 12, 16, 7]: 
    print(number)
print('Hi')
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
23
41
12
16
7
Hi

枚举

返回一个元组,其中包含每次迭代的计数(从默认为0开始)和迭代序列获得的值:

In 2

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
friends = ['steve', 'rachel', 'michael', 'adam', 'monica']
for index, friend in enumerate(friends):
    print(index,friend)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
print(text)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
for char in '-.,;\n"\'':
    text = text.replace(char,' ')
print(text)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# Split converts string to list.
# Each item in list is split on spaces
text.split(' ')[0:20]
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
['On',
 'a',
 'dark',
 'desert',
 'highway',
 '',
 'cool',
 'wind',
 'in',
 'my',
 'hair',
 'Warm',
 'smell',
 'of',
 'colitas',
 '',
 'rising',
 'up',
 'through',
 'the']

In 7

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# Dont want to have non words in my list for example ''
# which in this case are things of zero length
len('')
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
0

In 8

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# Making new list with no empty words in it
cleaned_list = []

In 9

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
for word in text.split(' '): 
    word_length = len(word)
    if word_length > 0:
        cleaned_list.append(word)

In 10

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
cleaned_list[0:20]
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
['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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
cleaned_list = []

for word in text.split(' '): 
    if word == '':
        continue
    cleaned_list.append(word)
cleaned_list[1:20]
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
['a',
 'dark',
 'desert',
 'highway',
 'cool',
 'wind',
 'in',
 'my',
 'hair',
 'Warm',
 'smell',
 'of',
 'colitas',
 'rising',
 'up',
 'through',
 'the',
 'air',
 'Up']

Break

break语句将完全打断循环

In 12

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
cleaned_list = []

In 13

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
for word in text.split(' '): 
    if word == 'desert':
        print('I found the word I was looking for')
        break
    cleaned_list.append(word)
cleaned_list
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
I found the word I was looking for
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
['On', 'a', 'dark']

Task (顺道介绍一下Range函数)

  1. 编写一个Python程序,它迭代整数从1到50(使用for循环)。对于偶数的整数,将其附加到列表even_numbers。对于奇数的整数,将其附加到奇数奇数列表中

In 14

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
print("Even Numbers: ", even_numbers)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
print("Odd Numbers: ", odd_numbers)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 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
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
0
1
2
3
4
5

break语句

使用break可以完全退出循环

In 2

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
count = 0
while count <= 5:
    if count == 2:
        break
    count += 1
    print (count)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1
2

while True条件使得除非遇到break语句,否则不可能退出循环

如果您陷入无限循环,请使用计算机上的ctrl + c来强制终止

In 3

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
num = 0
while True:
    if num == 2:
        print('Found 2')
        break
    num += 1
    print (num)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1
2
Found 2

提醒:使用模运算符(%),它将数字左边的余数除以右边的数字

In 4

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 1 divided by 5 is 0 remainder 1
1 % 5
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1

In 5

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 5 divided by 5 is 0 remainder 0
5 % 5
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
0

比较操作符

功能

<

小于

<=

小于或等于

| 大于 = | 大于或等于 == | 等于 != | 不等于

In 6

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
x = 1
while x % 5 != 0:
    x += 1
    print(x)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
2
3
4
5

当我们知道要循环多少次时,Range很有用

下面例子是: 从0开始,但不包括5

In 7

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
candidates = list(range(0, 5))
candidates
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[0, 1, 2, 3, 4]

In 8

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
while len(candidates) > 0: 
    first = candidates[0]
    candidates.remove(first)
    print(candidates)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[1, 2, 3, 4]
[2, 3, 4]
[3, 4]
[4]
[]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-03-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
Rust语法入门
Rust 是一种系统级编程语言,它的设计目标是提供高性能、安全性和并发性。Rust 的主要优势包括:
码客说
2023/04/17
1.4K0
一网打尽 Rust 语法
大家好,我是「柒八九」。一个「专注于前端开发技术/Rust及AI应用知识分享」的Coder
前端柒八九
2024/04/30
2250
一网打尽 Rust 语法
🌱 Rust内存管理黑魔法:从入门到"放弃"再到真香
内存管理是程序世界的"隐形战场",而 Rust 用一套所有权系统直接重构规则——没有 GC、没有手动 malloc/free,却能在编译期拦截 90% 的内存错误!
Jimaks
2025/04/27
2650
rust闭包(Closure)
闭包在现代化的编程语言中普遍存在。闭包是一种匿名函数,它可以赋值给变量也可以作为参数传递给其它函数,不同于函数的是,它允许捕获调用者作用域中的值。Rust 闭包在形式上借鉴了 Smalltalk 和 Ruby 语言,与函数最大的不同就是它的参数是通过 |parm1| 的形式进行声明,如果是多个参数就 |param1, param2,…|, 下面给出闭包的形式定义:
zy010101
2023/04/27
7480
rust闭包(Closure)
Rust到底值不值得学--Rust对比、特色和理念
其实我一直弄不明白一点,那就是计算机技术的发展,是让这个世界变得简单了,还是变得更复杂了。 当然这只是一个玩笑,可别把这个问题当真。
俺踏月色而来
2019/10/14
2.8K0
Rust闭包的虫洞穿梭
闭包(Closure)的概念由来已久。无论哪种语言,闭包的概念都被以下几个特征共同约束:
袁承兴
2020/09/19
1.4K0
rust 上手很难?搞懂这些知识,前端开发能快速成为 rust 高手
在我的交流群里有许多人在讨论 rust。所以陆续有人开始尝试学习 rust,不过大家的一致共识就是:rust 上手很困难。当然,这样的共识在网上也普遍存在。
用户6901603
2024/03/20
1.6K1
rust 上手很难?搞懂这些知识,前端开发能快速成为 rust 高手
Rust 入门 (Rust Rocks)
做区块链的基本几乎没有人不知道 Rust 这门编程语言,它非常受区块链底层开发人员的青睐。说来也奇怪,Rust 起源于 Mazilla,唯一大规模应用就是 Firefox,作为小众语言却在区块链圈子里火了。这其中应该和以太坊的发起人 Govin Wood 创建的 Parity 项目有关,Parity 是一款用 Rust 编写的以太坊客户端。
lambeta
2019/09/24
2.5K0
Rust学习:如何解读函数签名?
在Rust中,函数签名类似“讲故事”。经验丰富的Rust程序员,只需浏览一个函数的签名,就可以知道该函数大部分的行为。
MikeLoveRust
2019/09/03
2.3K0
Rust入坑指南:智能指针
在了解了Rust中的所有权、所有权借用、生命周期这些概念后,相信各位坑友对Rust已经有了比较深刻的认识了,今天又是一个连环坑,我们一起来把智能指针刨出来,一探究竟。
Jackeyzhe
2020/03/12
9480
rust的高级特性
rust中的表达式是什么{}包围的部分,函数,impl,match里面,if else表达式,通过这些功能分割系统
李子健
2022/05/10
6870
rust的内存管理
内存管理是rust最有意思的事情了。rust的内存管理有三条准则。 let分配资源 分配会转移所有权,比如赋值直接move了 值和变量在作用域末尾会被清理,释放 drop方法会在释放前调用 rust支持移动语义和复制语义,为此抽象出了两个trait,clone和copy 非堆内存可以使用copy,隐式转化,clone需要显示调用 关于借用的规则,使用& 一个引用的生命周期不能超过其被引用的时间 如果存在一个可变借用,不允许存在其他值 如果不存在可变借用,允许存在多个不可变借用 借用规则方法类型 &self
李子健
2022/05/08
8040
【翻译】Rust生命周期常见误区
我曾经有过的所有这些对生命周期的误解,现在有很多初学者也深陷于此。我用到的术语可能不是标准的,所以下面列了一个表格来解释它们的用意。
MikeLoveRust
2020/07/28
1.7K0
听GPT 讲Rust源代码--library/alloc(2)
在Rust源代码中,rust/library/alloc/src/vec/mod.rs这个文件是Rust标准库中的Vec类型的实现文件。Vec是一个动态大小的数组类型,在内存中以连续的方式存储其元素。
fliter
2024/02/26
2560
听GPT 讲Rust源代码--library/alloc(2)
Rust中的关键字
原始标识符(Raw identifiers)允许你使用通常不能使用的关键字,其带有 r# 前缀
fliter
2023/10/05
2740
Rust中的关键字
【Rust】005-Rust 结构体
在Rust中,元组结构体是一种特殊的结构体形式,它结合了元组和结构体的特性。元组结构体类似于普通的结构体,但它没有字段名称,只有字段类型。这种结构体更像是带标签的元组,通常用于需要对某些数据进行简单封装而不需要命名每个字段的场景。
訾博ZiBo
2025/01/06
1790
《Rust避坑式入门》第1章:挖数据竞争大坑的滥用可变性
赵可菲是一名Java程序员,一直在维护一个有十多年历史的老旧系统。这个系统即将被淘汰,代码质量也很差,每次上线都会出现很多bug,她不得不加班修复。公司给了她3个月的内部转岗期,如果转不出去就会被裁员。她得知公司可能会用Rust重写很多系统,于是就报名参加了公司的Rust培训,希望能够转型。
程序员吾真本
2024/08/29
6960
《Rust避坑式入门》第1章:挖数据竞争大坑的滥用可变性
【译】为 嵌入式 C 程序员编写的 Rust 指南
这是来自 Google OpenTitan 团队,给嵌入式 C 程序员专门打造的一份 Rust 指南。
张汉东
2021/10/13
5.5K0
Rust 总结
所有权是用来管理堆上内存的一种方式,在编译阶段就可以追踪堆内存的分配和释放,不会对程序的运行期造成任何性能上的损失。
谛听
2022/06/04
1.8K0
Rust入门之严谨如你
Rust作为一门快速发展的编程语言,已经在很多知名项目中使用,如firecracker、libra、tikv,包括Windows和Linux都在考虑Rust【1】。其中很重要的因素便是它的安全性和性能,这方面特性使Rust非常适合于系统编程。
Radar3
2020/11/25
1.8K2
相关推荐
Rust语法入门
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验