python冒泡循环示例_Python for循环示例

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:

输出

a
n
a
c
o
n
d
a

遍历列表,元组 (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:

输出

Apple
Banana
Car
Dolphin

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

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

nums = (1, 2, 3, 4)

sum_nums = 0

for num in nums:
    sum_nums = sum_nums + num

print(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 = 2

found = False
for num in nums:
    if n == num:
        found = True
        break

print(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 = 0

for num in nums:
    if num < 0:
        continue
    sum_positives += num

print(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 sum
print_sum_even_nums([2, 4, 6, 8])

# this won't print the sum because of an odd number in the sequence
print_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块。

翻译自: https://www.journaldev.com/14136/python-for-loop-example

python冒泡循环示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值