Python中退出While循环的三种方法举例 | 您所在的位置:网站首页 › while函数什么时候结束的 › Python中退出While循环的三种方法举例 |
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)运行结果举例 使用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的首字母大写,否则运行出现无法识别问题!运行结果 使用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语句结合; |
CopyRight 2018-2019 实验室设备网 版权所有 |