Python While循环

Python While循环

在编程中,循环被设计用于重复执行指定的代码块。在本教程中,我们将学习如何在Python中构建while循环,while循环的语法,像break和continue这样的循环控制语句,以及其他的练习。

Python While循环的介绍

在本文中,我们讨论Python中的while循环。只要给定的条件为真,即条件表达式为true,Python的while循环将执行代码块的迭代。

如果我们不知道预先执行迭代的次数,我们可以编写一个无限循环。

Python While循环的语法

现在,我们讨论Python while循环的语法。语法如下:

Statement
while Condition:
        Statement

给定条件(即conditional_expression)在Python的while循环中首先进行评估。然后,如果条件表达式给出布尔值为True,则执行while循环中的语句。当完整代码块执行时,再次验证条件表达式。此过程重复发生,直到条件表达式返回布尔值为False。

  • Python的while循环的语句由缩进来确定。
  • 代码块在第一个没有缩进的语句之前开始,并以此语句结束。
  • 在Python中,任何非零数字都被解释为布尔值True。False被解释为None和0。

示例

现在我们给出Python中while循环的一些示例。示例如下 –

程序代码1:

现在我们给出在Python中使用while循环打印1到10的数字的代码示例。代码如下 –

i=1
while i<=10:
    print(i, end=' ')
    i+=1

输出:

现在我们在Python中编译上述代码,并在成功编译后运行它。然后输出如下 –

1 2 3 4 5 6 7 8 9 10 

程序代码2:

现在我们给出使用while循环的Python代码示例,用于在1到50之间打印可被5或7整除的数字。代码如下所示 –

i=1
while i<51:
    if i%5 == 0 or i%7==0 :
        print(i, end=' ')
    i+=1

输出:

现在我们在python中编译上面的代码,并在成功编译后运行它。然后以下是输出结果 –

5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50

程序代码:

现在我们用Python给出使用while循环的代码示例,计算前15个自然数的平方和。代码如下 –

# Python program example to show the use of while loop 

num = 15

# initializing summation and a counter for iteration
summation = 0
c = 1

while c <= num: # specifying the condition of the loop
    # begining the code block
    summation = c**2 + summation
    c = c + 1    # incrementing the counter

# print the final sum
print("The sum of squares is", summation)

输出:

现在我们用Python编译上面的代码,编译成功后运行它。然后以下是输出结果 –

The sum of squares is 1240

假设我们的计数器参数i对于条件给出的boolean值为true,即i小于或等于num,循环会重复执行代码块i次。

接下来是一个关键点(经常被遗忘)。我们必须在循环的语句中增加计数器参数的值。如果不这样做,我们的while循环将无限执行下去(一个无限循环)。

最后,我们使用print语句打印结果。

Python While循环练习

1. 素数和Python While循环

使用while循环,我们将构建一个Python程序来验证给定的整数是否为素数。

程序代码:

现在我们给出一个在Python中使用while循环是否是质数的示例代码。代码如下 –

num = [34, 12, 54, 23, 75, 34, 11]  

def prime_number(number):
    condition = 0
    iteration = 2
    while iteration <= number / 2:
        if number % iteration == 0:
            condition = 1
            break
        iteration = iteration + 1

    if condition == 0:
        print(f"{number} is a PRIME number")
    else:
        print(f"{number} is not a PRIME number")
for i in num:
    prime_number(i)

输出:

现在我们在Python中编译上述代码,并在成功编译后运行它。然后输出如下所示 –

34 is not a PRIME number
12 is not a PRIME number
54 is not a PRIME number
23 is a PRIME number
75 is not a PRIME number
34 is not a PRIME number
11 is a PRIME number

2. 阿姆斯特朗数和Python的While循环

我们将使用一个while循环构建一个Python程序来验证给定的整数是否是一个阿姆斯特朗数。

程序代码:

现在我们给出在Python中使用while循环的阿姆斯特朗数的代码示例。代码如下 –

n = int(input())
n1=str(n)
l=len(n1)
temp=n
s=0
while n!=0:
    r=n%10
    s=s+(r**1)
    n=n//10
if s==temp:
    print("It is an Armstrong number")
else:
    print("It is not an Armstrong number ")

输出:

现在我们在Python中编译上述代码,在成功编译后,我们运行它。然后输出如下 –

342
It is not an Armstrong number

3. 使用While循环的乘法表

在这个例子中,我们将使用While循环来打印给定数字的乘法表。

程序代码:

在这个例子中,我们将使用While循环来打印给定数字的乘法表。代码如下 –

num = 21      
counter = 1    
# we will use a while loop for iterating 10 times for the multiplication table      
print("The Multiplication Table of: ", num)    
while counter <= 10: # specifying the condition
    ans = num * counter    
    print (num, 'x', counter, '=', ans)    
    counter += 1 # expression to increment the counter

输出:

现在我们在python中编译上述代码,在成功编译后,我们运行它。然后输出如下 –

The Multiplication Table of:  21
21 x 1 = 21
21 x 2 = 42
21 x 3 = 63
21 x 4 = 84
21 x 5 = 105
21 x 6 = 126
21 x 7 = 147
21 x 8 = 168
21 x 9 = 189
21 x 10 = 210

4. Python使用列表的while循环

编程代码1:

现在我们给出在Python中使用while循环对列表中的每个数字进行平方的代码示例。代码如下 –

# Python program to square every number of a list  
# initializing a list  
list_ = [3, 5, 1, 4, 6]  
squares = []  
# programing a while loop   
while list_: # until list is not empty this expression will give boolean True after that False  
    squares.append( (list_.pop())**2)  
#  Print the squares of all numbers.
print( squares )  

输出:

现在我们在Python中编译上面的代码,并且在成功编译后运行它。然后输出如下所示-

[36, 16, 1, 25, 9]

在上面的示例中,我们对给定的整数列表执行一个while循环,如果列表中找到一个元素,则会重复运行。

程序代码2:

现在我们提供了Python中使用while循环确定列表中每个数字的奇数和偶数的代码示例。代码如下 –

list_ = [3, 4, 8, 10, 34, 45, 67,80]        # Initialize the list
index = 0
while index < len(list_):
    element = list_[index]
    if element % 2 == 0:
        print('It is an even number')       # Print if the number is even.
    else:
        print('It is an odd number')        # Print if the number is odd.
    index += 1

输出:

现在我们在Python中编译上述代码,在成功编译后运行它。然后下面给出了输出 –

It is an odd number
It is an even number
It is an even number
It is an even number
It is an even number
It is an odd number
It is an odd number
It is an even number

程序代码 3:

现在我们给出Python中使用while循环确定给定列表中每个单词的字母数的代码示例。以下是代码 –

List_= ['Priya', 'Neha', 'Cow', 'To']
index = 0
while index < len(List_):
    element = List_[index]
    print(len(element))
    index += 1

输出:

现在我们将以上代码在Python中编译,并且在成功编译后运行它。然后输出如下 –

5
4
3
2

Python While循环多个条件

我们必须使用逻辑运算符将两个或多个条件表达式合并为一个while循环。这告诉Python对所有给定的条件表达式进行综合分析。

我们可以在此示例中构造具有多个条件的while循环。我们给出了两个条件和一个and关键字,意思是该循环将执行语句,直到两个条件都为布尔类型的True。

程序代码:

现在我们给出在Python中使用多个条件的while循环的代码示例。代码如下 –

num1 = 17
num2 = -12

while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop
    num1 -= 2
    num2 += 3
    print( (num1, num2) )

输出:

现在我们在Python中编译上述代码,并在成功编译后运行它。然后输出如下 –

(15, -9)
(13, -6)
(11, -3)

让我们来看一个使用OR操作符的多个条件的另一个示例。

代码

num1 = 17
num2 = -12

while num1 > 5 or num2 < -5 :
    num1 -= 2
    num2 += 3
    print( (num1, num2) )

输出:

现在我们在Python中编译上面的代码,并且在成功编译后运行它。然后输出如下 –

(15, -9)
(13, -6)
(11, -3)
(9, 0)
(7, 3)
(5, 6)

我们还可以在while循环中组合多个逻辑表达式,如此示例所示。

代码

num1 = 9 
num = 14 
maximum_value = 4
counter = 0 
while (counter < num1 or counter < num2) and not counter >= maximum_value: # grouping multiple conditions
    print(f"Number of iterations: {counter}") 
    counter += 1

输出:

现在我们将上述代码编译为Python,并在成功编译后执行它。然后输出如下 –

Number of iterations: 0
Number of iterations: 1
Number of iterations: 2
Number of iterations: 3

单语句while循环

与if语句的语法类似,如果我们的while从句只包含一条语句,那么它可以与while关键字写在同一行上。

以下是一行式while从句的语法和示例 –

# Python program to show how to create a single statement while loop
counter = 1
while counter: print('Python While Loops')

循环控制语句

现在我们将详细讨论循环控制语句。我们将看到每个控制语句的一个例子。

continue语句

它将Python解释器的控制返回到循环的开头。

代码

# Python program to show how to use continue loop control

# Initiating the loop
for string in "While Loops":
    if string == "o" or string == "i" or string == "e":
         continue
    print('Current Letter:', string)

现在我们将以上代码编译成Python,并在成功编译后运行它。然后得到的输出如下 –

输出:

Current Letter: W
Current Letter: h
Current Letter: l
Current Letter:  
Current Letter: L
Current Letter: p
Current Letter: s

break语句

当达到跳出语句时,它会停止循环的执行。

代码

# Python program to show how to use the break statement

# Initiating the loop
for string in "Python Loops":
    if string == 'n':
         break
    print('Current Letter: ', string)

输出:

现在我们在python中编译上述代码,并在成功编译后运行它。然后输出如下 –

Current Letter:  P
Current Letter:  y
Current Letter:  t
Current Letter:  h
Current Letter:  o

Pass语句

Pass语句用于创建空循环。Pass语句还用于类、函数和空控制语句中。

代码

# Python program to show how to use the pass statement  
for a string in "Python Loops":  
    pass  
print( 'The Last Letter of given string is:', string)   

现在我们将上述代码编译成Python,并在成功编译后运行它。然后下面是输出结果 –

输出:

The Last Letter of given string is: s

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程