博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python冒泡循环示例_Python for循环示例
阅读量:2538 次
发布时间:2019-05-11

本文共 5174 字,大约阅读时间需要 17 分钟。

python冒泡循环示例

Python for loop is used for iterating over a sequence. The for loop is present in almost all programming languages.

Python for循环用于迭代序列。 for循环几乎存在于所有编程语言中。

Python for循环 (Python for loop)

We can use for loop to iterate over a list, tuple or strings. The syntax of for loop is:

我们可以使用for循环遍历列表,元组或字符串。 for循环的语法为:

for itarator_variable in sequence_name:	Statements	. . .	Statements

Let’s look at some examples of using for loop in Python programs.

让我们看一些在Python程序中使用for循环的示例。

使用for循环打印字符串的每个字母 (Using for loop to print each letter of a string)

Python string is a sequence of characters. We can use for loop to iterate over the characters and print it.

Python字符串是字符序列。 我们可以使用for循环遍历字符并打印出来。

word="anaconda"for letter in word:	print (letter)

Output:

输出

anaconda

遍历列表,元组 (Iterating over a List, Tuple)

List and Tuple are iterable objects. We can use for loop to iterate over their elements.

List和Tuple是可迭代的对象。 我们可以使用for循环遍历它们的元素。

words= ["Apple", "Banana", "Car", "Dolphin" ]for word in words:	print (word)

Output:

输出

AppleBananaCarDolphin

Let’s look at an example to find the sum of numbers in a tuple.

让我们看一个示例,查找元组中的数字总和。

nums = (1, 2, 3, 4)sum_nums = 0for num in nums:    sum_nums = sum_nums + numprint(f'Sum of numbers is {sum_nums}')# Output# Sum of numbers is 10

Python嵌套循环 (Python Nested For Loop)

When we have a for loop inside another for loop, it’s called nested for loop. The following code shows nested for loops in Python.

当我们在另一个for循环中有一个for循环时,称为嵌套for循环。 以下代码显示了Python中嵌套的for循环。

words= ["Apple", "Banana", "Car", "Dolphin" ]for word in words:        #This loop is fetching word from the list        print ("The following lines will print each letters of "+word)        for letter in word:                #This loop is fetching letter for the word                print (letter)        print("") #This print is used to print a blank line

Output

输出量

带有range()函数的Python for循环 (Python for loop with range() function)

Python range() is one of the built-in functions. It is used with for loop to run a block of code specific number of times.

Python range()是内置函数之一。 它与for循环一起使用,以运行特定次数的代码块。

for x in range(3):    print("Printing:", x)	# Output# Printing: 0# Printing: 1# Printing: 2

We can also specify start, stop, and step parameters for range function.

我们还可以为范围功能指定开始,停止和步进参数。

for n in range(1, 10, 3):    print("Printing with step:", n)	# Output# Printing with step: 1# Printing with step: 4# Printing with step: 7

带for循环的break语句 (break statement with for loop)

The break statement is used to exit the for loop prematurely. It’s used to break the for loop when a specific condition is met.

break语句用于过早退出for循环。 当满足特定条件时,它用于中断for循环。

Let’s say we have a list of numbers and we want to check if a number is present or not. We can iterate over the list of numbers and if the number is found, break out of the loop because we don’t need to keep iterating over the remaining elements.

假设我们有一个数字列表,我们想检查一个数字是否存在。 我们可以遍历数字列表,如果找到了该数字,请跳出循环,因为我们不需要继续遍历其余元素。

nums = [1, 2, 3, 4, 5, 6]n = 2found = Falsefor num in nums:    if n == num:        found = True        breakprint(f'List contains {n}: {found}')# Output# List contains 2: True

用for循环继续语句 (continue statement with for loop)

We can use continue statements inside a for loop to skip the execution of the for loop body for a specific condition.

我们可以在for循环内使用continue语句,以跳过特定条件下for循环主体的执行。

Let’s say we have a list of numbers and we want to print the sum of positive numbers. We can use the continue statements to skip the for loop for negative numbers.

假设我们有一个数字列表,我们想打印正数之和。 我们可以使用continue语句跳过for循环中的负数。

nums = [1, 2, -3, 4, -5, 6]sum_positives = 0for num in nums:    if num < 0:        continue    sum_positives += numprint(f'Sum of Positive Numbers: {sum_positives}')

带有可选else块的Python for循环 (Python for loop with optional else block)

We can use else clause with for loop in Python. The else block is executed only when the for loop is not terminated by a break statement.

我们可以在Python中将else子句与for循环一起使用。 仅当for循环未由break语句终止时,才会执行else块。

Let’s say we have a function to print the sum of numbers if and only if all the numbers are even. We can use break statement to terminate the for loop if an odd number is present. We can print the sum in the else part so that it gets printed only when the for loop is executed normally.

假设我们有一个函数,当且仅当所有数字均为偶数时,才打印数字之和。 如果存在奇数,我们可以使用break语句终止for循环。 我们可以在else部分中打印总和,以便仅在正常执行for循环时才打印总和。

def print_sum_even_nums(even_nums):    total = 0    for x in even_nums:        if x % 2 != 0:            break        total += x    else:        print("For loop executed normally")        print(f'Sum of numbers {total}')# this will print the sumprint_sum_even_nums([2, 4, 6, 8])# this won't print the sum because of an odd number in the sequenceprint_sum_even_nums([2, 4, 5, 8])# Output# For loop executed normally# Sum of numbers 20

结论 (Conclusion)

The for loop in Python is very similar to other programming languages. We can use break and continue statements with for loop to alter the execution. However, in Python, we can have optional else block in for loop too.

Python中的for循环与其他编程语言非常相似。 我们可以使用带有for循环的break和Continue语句来更改执行。 但是,在Python中,我们也可以在for循环中使用可选的else块。

翻译自:

python冒泡循环示例

转载地址:http://yhlzd.baihongyu.com/

你可能感兴趣的文章
生产订单“生产线别”带入生产入库单
查看>>
crontab导致磁盘空间满问题的解决
查看>>
java基础 第十一章(多态、抽象类、接口、包装类、String)
查看>>
Hadoop 服务器配置的副本数量 管不了客户端
查看>>
欧建新之死
查看>>
自定义滚动条
查看>>
APP开发手记01(app与web的困惑)
查看>>
笛卡尔遗传规划Cartesian Genetic Programming (CGP)简单理解(1)
查看>>
mysql 日期时间运算函数(转)
查看>>
初识前端作业1
查看>>
ffmpeg格式转换命令
查看>>
万方数据知识平台 TFHpple +Xpath解析
查看>>
Hive实现oracle的Minus函数
查看>>
秒杀多线程第四篇 一个经典的多线程同步问题
查看>>
RocketMQ配置
查看>>
vs code调试console程序报错--preLaunchTask“build”
查看>>
蚂蚁金服井贤栋:用技术联手金融机构,形成服务小微的生态合力
查看>>
端口号大全
查看>>
机器学习基石笔记2——在何时可以使用机器学习(2)
查看>>
POJ 3740 Easy Finding (DLX模板)
查看>>