Python中退出While循环的三种方法举例
•
Python
Python中退出While循环的三种方法举例
在Python学习及编程应用中,常会使用while循环,对while循环条件设置不当可能导致进入死循环,本文将举例说明三种退出while循环的方法。
1.直接使用input函数
利用input函数使得输入值传递到while之后的条件判断句中,使while后的结果为False。
举例:
程序1:
Prompt_sentence_1='\n 请输入一段文字:' Prompt_sentence_2='若要退出请输入Esc!' Your_paragraph='' while Your_paragraph !='Esc': Your_paragraph=input(Prompt_sentence_1) print(Your_paragraph) print(Prompt_sentence_2)
运行结果举例

2.使用if-else语句和input结合
使用input将输入的值,通过if判断后,修改while后的判断标志符。
举例
程序2:
Prompt_sentence_1='\n 请输入一段文字:' Prompt_sentence_2='若要退出请输入Esc!' Your_paragraph='' flag=True while flag: Your_paragraph=input(Prompt_sentence_1) if Your_paragraph=='Esc': flag=False else: print(Your_paragraph) print(Prompt_sentence_2)
在本程序中使用了标志符flag。
| 特别注意:True 和False的首字母大写,否则运行出现无法识别问题! |
|---|
运行结果

3.使用break,与input和if-else语句结合
使用input将输入的值,通过if条件判断后执行或不执行break,实现while循环的中断。
举例
程序3
Prompt_sentence_1='\n 请输入一段文字:' Prompt_sentence_2='若要退出请输入Esc!' Your_paragraph='' while True: Your_paragraph=input(Prompt_sentence_1) if Your_paragraph=='Esc': break else: print(Your_paragraph) print(Prompt_sentence_2)
运行结果:

总结:
通过本文的学习可知,while循环退出主要有三种方式:
(1)直接使用input函数;
(2)使用if-else语句和input结合
(3)使用break,与input和if-else语句结合;
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/a4e16a9871.html
