血干了是什么颜色| 手麻去医院挂什么科| 陶渊明是什么朝代| 梦见水代表什么| 什么中药补气血效果最好| 6.20什么星座| 打羽毛球有什么好处| 隔桌不买单是什么意思| 藤原拓海开的什么车| 肠胃炎吃什么好| dbm是什么单位| 脸黑的人适合穿什么颜色的衣服| 为什么老是胃胀气| 铁观音是什么茶| 爱琴海在什么地方| gl值是什么意思| 老年人吃什么增强免疫力| 心脏疼痛挂什么科| 为什么拼音| 花开两朵各表一枝什么意思| 荨麻疹吃什么药好的快| 痱子粉什么牌子好| 爱情是什么颜色的| 什么水果不能一起吃| 甲油胶是什么| 腿水肿是什么原因| score是什么意思| 玉米芯有什么用途| 咳嗽吃什么食物| 看肝脏挂什么科| 子宫内膜异位症吃什么药| 神经衰弱什么症状| 1992属什么| 眼睛为什么会散光| 输尿管结石挂什么科| 中秋吃什么| 贫血什么症状| 身上遇热就痒是什么病| 急性青光眼是什么症状| 怡字属于五行属什么| 口腔溃疡吃什么维生素| 什么叫业力| 鸟飞到头上什么预兆| 嘴里发咸是什么原因| 痔疮出血用什么药| 三伏天什么时候最热| 儿童办护照需要什么证件| 何弃疗是什么意思| 闰月鞋买什么颜色| 脚趾头抽筋是什么原因引起的| 促甲状腺激素高是什么意思| 为什么总打喷嚏| 被cue是什么意思| 中秋吃什么| 唐筛主要检查什么| 小孩记忆力差什么原因| 看到壁虎是什么征兆| 西门子洗衣机不脱水是什么原因| 知了猴什么时候出来| 芳心是什么意思| 头麻是什么原因| 小白龙叫什么名字| 吃饭睡觉打豆豆是什么意思| 玉米什么季节成熟| 甲母痣挂什么科| 佛心是什么意思| 什么的东风填词语| 情何以堪是什么意思| 仓鼠可以吃什么水果| 海竹是什么| 五液是指什么| 经常脚抽筋是什么原因| 结余是什么意思| beauty是什么意思| 黄芪什么味道| 破涕为笑什么意思| 头寸是什么意思| 鼠冲什么生肖| 查肾功能挂什么科| 螳螂吃什么东西| ex是什么的缩写| 什么是割礼| 718是什么星座| 尖嘴鱼叫什么鱼| 淋巴结在什么位置| 绿树成荫是什么季节| 紫色代表什么| 白矾是什么东西| 欣赏一个人是什么意思| 什么样的人可以通灵| s是什么m是什么| 全员加速中什么时候播| 屁多肚子胀是什么原因| 儿童咳嗽挂什么科| 河豚为什么有毒| 小路像什么| 绅士是什么意思| 孕妇吃红薯对胎儿有什么好处| 早上起来口干口苦是什么原因| 广式腊肠炒什么菜好吃| 吃什么助睡眠| 胃幽门螺旋杆菌吃什么药| 膂力是什么意思| 玉露茶属于什么茶| 1998年属虎是什么命| 神奇的近义词是什么| sd值是什么意思| 水痘长什么样子的图片| 连奕名为什么娶杨若兮| 什么水果含钾| 搞破鞋什么意思| 带状疱疹挂什么科室| 心脏彩超ef是什么意思| 什么的瞬间作文| 甘油三酯高是什么原因| 擦边球是什么意思| 心跳过速是什么原因| 不孕不育查什么项目| 双子座有什么特点| 中耳炎是什么症状| 3月15号是什么星座| 眉头有痣代表什么| 柏树长什么样子| 什么食物含维生素b| 青椒炒什么好吃| 什么不可什么四字词语| 风是什么结构| 生理期吃什么水果比较好| 性病是什么症状| t细胞是什么| 2333是什么意思啊| 网球ad是什么意思| 凌晨三点半是什么时辰| 杂交金毛犬长什么样子| 月牙是什么| 怀孕梦见蛇是什么意思| 手指甲上有竖纹是什么原因| 锌补多了有什么症状| 什么补血最快| 流口水吃什么药最好| 驻马店古代叫什么| 病毒性肠胃炎吃什么药| 为什么口臭| 什么是射频治疗| 厦门为什么叫厦门| 尖锐湿疣挂什么科| 下架是什么意思| 烧心吃点什么药| 梦见打架是什么意思| 直接胆红素偏高是什么意思| o型血有什么好处| 12年义务教育什么时候实行| 脚心热吃什么药| 皇后是什么意思| 口苦口干吃什么药好| 载歌载舞的载是什么意思| 泡沫尿吃什么药| 蜻蜓为什么点水| 什么伤口需要打破伤风| 腿部抽筋是什么原因引起的| 钾高了会出现什么症状| 耳朵痒是什么预兆| 官能是什么意思| 结石用什么药| hvr是什么意思| 211是什么意思| 气滞血瘀是什么意思| 肠易激综合症什么症状| 闺六月是什么意思| 宫颈囊肿是什么原因| 风餐露宿是什么生肖| 书中自有颜如玉什么意思| 检查肝脏挂什么科| lge是什么意思| 咨询什么意思| 养胃早餐吃什么好| 呆若木鸡的意思是什么| 抽血化验能查出什么| 裂帛是什么意思| 女生适合喝什么茶| 长寿花什么时候扦插| 盆腔炎吃什么药| 核心是什么意思| 梦见种菜是什么意思| 手串19颗代表什么意思| 经常吃辣椒有什么好处和坏处| 站久了脚后跟疼是什么原因| 肌肉跳动是什么原因| 腿麻木是什么原因引起的| 莲子吃了有什么好处| 霉菌用什么药| 冬至有什么忌讳| 什么米最贵| 3月19日什么星座| 小孩咳嗽吃什么药效果最好| 接骨木莓是什么| 蜜枣是什么枣做的| 胃食管反流吃什么中成药| 菩提子是什么| 911是什么电话| 何必是什么意思| 医德是什么| 低回声斑块是什么意思| 鸽子红鼻头喂什么药| 钻牛角尖是什么意思| 天仙配是什么剧种| 死间计划到底是什么| rh是什么血型| 什么是铅中毒| 鹤是什么生肖| 脉细是什么意思| 备孕期间要注意什么| 风水是什么意思| 妄念是什么意思| 什么叫腺样体肥大| bic是什么意思| 麦乳精是什么东西| 王维有什么之称| 易是什么意思| 梦见自己请客吃饭是什么意思| 忘带洗面奶用什么代替| 胆红素高说明什么| 救世主是什么意思| 肌酐指标高说明什么| 缺维生素d有什么症状| 吃什么容易上火| 查凝血酶能查出什么病| 万里长城是什么生肖| 眼底照相是检查什么| 背上长痘是什么原因| 腺体肠化是什么意思| 头疼想吐吃什么药| 小分子肽有什么作用| 小孩子流鼻血是什么原因| 白细胞低是什么原因引起的| 做亲子鉴定需要什么东西| 怀孕有积液是什么原因| 变爻是什么意思| 左卵巢囊性回声什么意思| 津津有味的意思是什么| 百合和拉拉有什么区别| 仓鼠喜欢吃什么| 小人痣代表什么意思| 鱼缸什么材质的好| 缺氯有什么症状怎么补| 什么叫猥亵| 信任是什么意思| 血热吃什么中成药| 碟中谍是什么意思| 一个人自言自语的说话是什么病| 清热败火的败是什么意思| 什么是脂肪瘤| 道心是什么意思| 随喜功德是什么意思| 头晕吃什么| 吴亦凡属什么生肖| 成双成对是什么数字| cook是什么意思| 八项规定的内容是什么| 近视是什么原因造成的| 刚愎自负是什么意思| 叶酸对人体有什么好处| 梦到知了猴是什么意思| 杜鹃花什么时候开| 百度
Bytes

再现涨价潮 奢侈品代购忙囤货

Last Updated: 29th September, 2024
百度 按照《京津冀协同发展规划纲要》有关“六河五湖四库”的治理要求,未来将按照“一河一策”原则,重点推进北运河、潮白河、永定河等流域综合治理,构建河湖蓝网系统;还将加强库滨带河滨带治理,逐步改善河湖水质。

The Python While Loop ?? repeatedly executes a block of statements ?until a specified condition :thinking: becomes false. Once the condition becomes false, the first line after the Loop executes.

A while loop is a type of indefinite iteration . The while loop continues looping ?as long as the condition remains true. When the condition becomes false, the Loop terminates and the first statement after executing the loop body.

While loop in Python

What is While Loop in Python?

"A while loop in Python is a control flow statement that allows a block of code to be executed repeatedly based on a given Boolean condition. In other words, the while loop will keep iterating and running the code block inside of it until the specified condition evaluates to False.”

While Loop Syntax in Python

while condition:
    statements
  • A while loop in Python repeats a code block while an expression is true.
  • The while keyword starts the Loop.
  • An expression follows that evaluates to true or false.
  • The indented statement after the expression is the loop body.
  • The body repeats while the expression is true.
  • The expression checks the loop condition.
  • The body contains the code that runs on each iteration of the Loop.

Working of While Loop:

A while loop in Python continually executes a code block if a specified condition is true. The Loop will run the code block repeatedly until the condition becomes false. Once the condition is false, the program exits the while loop and continues.

The condition for the Loop can be any expression that evaluates to true or false. True is any non-zero value. The Loop can also be terminated early using the break statement. While loops are a helpful control structure that allows a program to execute a set of statements multiple times. They run the code block within the Loop repeatedly until the defined condition is no longer met.

Example of Python While Loop

# Initialize counter
counter = 0

# While loop
while counter < 10:
    print(counter)
    # Increment counter
    counter += 1

This code is an example of Python while Loop. The code initializes a counter variable to 0, then prints the counter value and increments the counter by 1 until the counter is no longer less than 10. The output of this code will be a list of numbers from 0 to 9.

While Loop with Else

Let's further discuss while Loop with else. Let's check the syntax. A while loop with else executes a block of code as long as a given condition is true. Once the condition becomes false, the else block of code is executed. The else block of code is executed only if the condition is false. This is useful for ensuring that certain code is executed at least once or after the while loop ends.

Syntax

while <condition>:
    <code to execute>
else:
    <code to execute>

Example:

i = 0
while (i <= 100 and i % 7 != 0):
  i += 1
else:
  if (i % 7 == 0):
    print("The first number divisible by 7 is", i)
  else:
    print("No number is divisible by 7")

This code uses a while loop with an else statement to find the first number divisible by 7 between 0 and 100. The while loop checks if the value of i is less than or equal to 100 and is not divisible by 7, and if it is not, then it increments the value of i by 1. The else statement checks if the value of i is divisible by 7; if it is, then it prints the value of i. If the while loop fails to find any number divisible by 7, then the else statement prints that no number is divisible by 7.

Single Statement While Loop in Python

while condition:
    statement

Example:

i=0
while i < 5:
    print(i)
    i += 1

This while loop will execute the print(i) statement repeatedly if the condition i < 5 evaluates to True. On each iteration of the Loop, the value of i is incremented by 1 using the i += 1 statement. The Loop will continue printing the value of i and incrementing it until i reach the value of 5. At this point, the condition i < 5 will become False, and the Loop will exit, proceeding to the first statement after the while loop. In summary, this while loop will print the numbers 0 through 4, and then the Loop will terminate.

The Infinite While Loop in Python

The infinite while loop in Python continuously executes the code inside the Loop until the user stops it. This Loop runs endlessly unless the user explicitly ends the Loop or an error occurs. The Loop can perform tasks that need constant looping, like checking for user input or monitoring a system.

Example:

while True:
    print("Data scientists are like artists, except instead of paint and canvas, they use data and algorithms to create a masterpiece.")

An infinite while loop continually executes in Python until a specified condition is met. For example, the Loop below will print "Hello World" repeatedly until the Loop is manually stopped. This Loop is useful when code needs to run until certain criteria are satisfied, such as continually accepting user input.

Sentinel-Controlled while Loop

A?sentinel-controlled loop runs until it encounters a specific value, known as the sentinel value, which signals the loop to terminate. This is particularly useful when the number of iterations is not known in advance.

Example:? While Loop with User Input Validation

The while loop is particularly useful when you want to keep prompting a user until they provide valid input. This is a common use case for interactive programs.

# Initialize the sum and count
total = 0
count = 0

# Get the first input from the user
number = int(input("Enter a number (-1 to stop): "))
 
# Sentinel-controlled while loop
while number != -1:
	total += number
	count += 1
	# Prompt the user to enter another number
	number = int(input("Enter another number (-1 to stop): "))
 
# Display the result
if count != 0:
	print("Total sum:", total)
	print("Average:", total / count)
else:
	print("No numbers were entered.")

# Output (Sample Run):
Enter a number (-1 to stop): 10
Enter another number (-1 to stop): 20
Enter another number (-1 to stop): 30
Enter another number (-1 to stop): -1
Total sum: 60
Average: 20.0

In this case, the loop continues until the sentinel value -1 is entered, signaling the end of input.

While Loop with Boolean Values

You can use Boolean values directly as conditions for while loops, allowing them to run based on logical True or False states.

Example:

keep_running = True
while keep_running:
    user_input = input("Type 'exit' to stop: ").lower()
	if user_input == 'exit':
        keep_running = False
	else:
    	print("You typed:", user_input)
 
print("Loop has ended.")

In this example, the loop continues as long as keep_running is True. When the user inputs "exit," the keep_running variable is set to False, causing the loop to terminate.

Control Statements in Python with Examples

Loop control statements alter the normal flow of execution. When execution exits a scope, all automatically created objects within that scope are destroyed.

You can control the flow of while loops using break, continue, and else statements.

1. Python While Loop with a Break Statement

The break statement is used to exit a loop prematurely, even if the loop's condition is still True.

number = 1
 
while number <= 10:
	print("Number:", number)
	
	if number == 5:
    	print("Breaking the loop as number reached 5")
    	break
	
	number += 1

# Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Breaking the loop as number reached 5

2. Python While Loop with a Continue Statement

The continue statement skips the remaining code inside the loop for the current iteration and moves on to the next iteration.

number = 0
 
while number < 5:
	number += 1
	
	if number == 3:
    	print("Skipping number 3")
    	continue
    
	print("Number:", number)

# Output:

Number: 1
Number: 2
Skipping number 3
Number: 4
Number: 5

3. Python While Loop with an Else Statement

The else clause can be attached to a while loop and executes when the loop condition becomes False.

number = 1
 
while number <= 3:
	print("Number:", number)
	number += 1
else:
	print("Loop ended. Number is now greater than 3.")

# Output:
Number: 1
Number: 2
Number: 3
Loop ended. Number is now greater than 3.

While Loop with Python Lists

You can also use while loops to iterate through the elements of a list. This can be useful when you want to perform operations on list items based on certain conditions or to process the list dynamically.

Example: Iterating Through a List

Here’s an example that uses a while loop to print each element in a list until all elements have been processed.

# Initialize a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
 
# Initialize the index
index = 0
 
# While loop to iterate through the list
while index < len(fruits):
	print("Fruit:", fruits[index])
	index += 1

# Output:

Fruit: apple
Fruit: banana
Fruit: cherry
Fruit: date
Fruit: elderberry

In this example, the loop continues until index is equal to the length of the list, allowing you to access each fruit by its index.

Example: Modifying List Elements with a While Loop

You can also modify elements in a list while iterating through it using a while loop.

# Initialize a list of numbers
numbers = [1, 2, 3, 4, 5]
 
# Initialize the index
index = 0
 
# While loop to double each number in the list
while index < len(numbers):
    numbers[index] *= 2
	index += 1
 
print("Doubled numbers:", numbers)

# Output:

Doubled numbers: [2, 4, 6, 8, 10]

In this example, each number in the list is doubled as the loop iterates through the list.

Common Pitfalls with While Loops

  1. Infinite Loops: Forgetting to update the loop variable can result in an infinite loop.
  2. Incorrect Use of continue: If used improperly, continue can cause unintended skips in loop execution.

Use Cases for While Loops

  • Data Validation: Prompting a user for input until a valid response is provided.
  • Game Loops: Maintaining game logic that continues running until an exit condition is met.
  • Monitoring Processes: Checking the status of a background process until it completes.

Conclusion

This lesson provides an overview of Python while Loop, which repeatedly executes a code block until a specified condition becomes false. The lesson covers the syntax ???? of the while loop, how it works, and provides examples ?? of its use, including while loops with else statements ??, single statement while loops, and infinite while loops ??.

Key Takeaways

  1. A while loop executes a code block repeatedly until a specified condition is met.
  2. The Loop continues until the condition becomes false.
  3. While loops can iterate over lists, strings, collections, and more.
  4. If the condition is initially false, the loop body will not execute.
  5. Using a proper condition in the while loop is essential to avoid an infinite loop.

Quiz

  1. What is the purpose of a while loop??
    1. To iterate multiple times through a loop?
    2. To evaluate a condition before proceeding?
    3. To execute a block of code until the condition is false?
    4. To repeat a set number of times

Answer: C. To execute a block of code until the condition is false.

  1. How is a while loop entered in a program?
    1. By typing the keyword “while”?
    2. By calling the loop function?
    3. By setting a condition?
    4. By defining a loop variable

Answer: A. By typing the keyword “while”.

  1. When does a while loop stop executing?
    1. When the condition is false?
    2. When the condition is true?
    3. When a break statement is encountered?
    4. When the loop is exited

Answer: A. When the condition is false.

  1. What is the output of the following code?
Loading...

a. [1, 4, 9]?

b. [1, 2, 3]?

c. [2, 4, 6] d. [1, 3, 5]

Answer: A. [1, 4, 9]

Module 3: Loops and Iterations in PythonWhile Loop in Python

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

? 2025 AlmaBetter
腰酸是什么原因女性 海南简称是什么 名媛是什么意思 孕妇用什么驱蚊最安全 西柚是什么水果
挑眉是什么意思 四时感冒什么意思 visa是什么 上海话册那是什么意思 疑神疑鬼是什么意思
什么补血补气最好最快 经常恶心干呕是什么原因 si是什么元素 直落是什么意思 swisse是什么意思
羊羹是什么做的 治疗阳痿早泄用什么药 西洋参有什么用 什么牌子的麦克风好用 鱼油对身体有什么好处
屁股又叫什么fenrenren.com 拉肚子为什么肛门痛hcv8jop2ns2r.cn 黄金芽属于什么茶hcv7jop4ns8r.cn 腰间盘突出是什么原因引起的hcv8jop6ns0r.cn 什么邮箱最好用最安全hcv8jop1ns6r.cn
什么什么的大树hcv7jop4ns6r.cn 脖子长痘是什么原因引起的hcv7jop9ns4r.cn 南京为什么叫金陵bysq.com 小巧玲珑是什么意思hcv9jop1ns5r.cn 外阴苔藓用什么药膏hlguo.com
孕妇梦见血是什么预兆aiwuzhiyu.com 吃什么补肾气hcv8jop0ns2r.cn 心里紧张吃什么药缓解hcv8jop3ns3r.cn 梨不能和什么一起吃hcv9jop0ns1r.cn 麻薯是什么做的bjhyzcsm.com
m是什么意思huizhijixie.com 心肝血虚吃什么中成药hcv8jop8ns6r.cn 100a是什么尺码hcv8jop8ns2r.cn 乙肝两对半定量是什么意思hcv8jop2ns9r.cn 右耳痒是什么预兆hcv7jop9ns2r.cn
百度