美文网首页python
python(11):让用户选择何时退出与使用标志

python(11):让用户选择何时退出与使用标志

作者: Z_bioinfo | 来源:发表于2022-04-06 15:18 被阅读0次

1.让用户选择何时退出

可使用while循环让程序在用户愿意时不断地运行,如下面所示。我们在其中定义了一个退出值,只要当用户输入的不是这个值,程序就接着运行

#让用户选择何时退出
prompt = '\ntell me something,and i will repeat it back to you :'
prompt += " \nenter 'quti' to end the program."
message = ""
while message != 'quit':
    message = input(prompt)
    print(message)
tell me something,and i will repeat it back to you : 
enter 'quti' to end the program.hello everyone
hello everyone

tell me something,and i will repeat it back to you : 
enter 'quti' to end the program.quit
quit
#改进程序,不打印最后的quit
prompt = '\ntell me something,and i will repeat it back to you :'
prompt += " \nenter 'quti' to end the program."
message = ""
while message != 'quit':
    
    message = input(prompt)
    if message != 'quit':
        print(message)
tell me something,and i will repeat it back to you : 
enter 'quti' to end the program.hello everone
hello everone

tell me something,and i will repeat it back to you : 
enter 'quti' to end the program.quit

2.使用标志

在要求很多条件都满足才运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量背称为标志,充当了程序的交通信号灯。可以让程序在标志位true时继续运行,并在任何事件导致标志的值为false时让程序停止运行。这样while语句中就只需检查一个条件---标志的当前值是否位true,并将所有测试都放在其他地方,从而让程序变得更为整洁。

#使用标志
#使用标志
prompt = '\ntell me something,and i will repeat it back to you :'
prompt += " \nenter 'quit' to end the program."
active = True#将变量active设置为true,让程序最初处于活动状态。
while active:
    message = input(prompt)
    if message == 'quit':#如果输入的时quit,变量active变为false,终止while循环
        active = False
    else:#输入的不是quit,将输入作为一条消息打印出来
        print(message)
tell me something,and i will repeat it back to you : 
enter 'quit' to end the program.hello
hello

tell me something,and i will repeat it back to you : 
enter 'quit' to end the program.quit

相关文章

  • python(11):让用户选择何时退出与使用标志

    1.让用户选择何时退出 可使用while循环让程序在用户愿意时不断地运行,如下面所示。我们在其中定义了一个退出值,...

  • Python while 循环

    让用户选择何时退出 示例输出: 使用标志 示例输出: 使用 break 退出循环 在循环中使用 continue ...

  • day20/30 认知训练营

    20/30 忠诚的限度,何时退出,何时发声 Book 《退出、呼吁与忠诚》 退出是典型的经济选择,它不针对某个人,...

  • 停止线程

    1.使用退出标志,设置标志位,使线程正常退出,当run方法完成后线程终止 2.使用interrupt()方法终止线...

  • 线程的开启与停止

    开启:start方法 停止: 1)使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。 2)使用sto...

  • Python基础篇-为什么要学习Python

    人们为何使用Python Python用户反映,之所以选择Python的主要因素有以下几个方面: 1、软件质量 P...

  • Python-第一节课笔记串烧

    1.在Ubuntu中进入与退出Python环境 python3--->进入 exit()--->退出 2.此条无名...

  • PYTHONPATH在supervisor命令中

    supervisor使用root账号运行,如何让执行的程序使用普通用户,且使用普通用户安装的python包? 这里...

  • JAVA终止线程的方法

    如何正确地停止一个线程 方法如下: 使用退出标志,使线程正常退出,也就是当 run 方法完成后线程终止 使用 in...

  • 普通用户切换到root用户

    使用命令:sudo -i 退出root用户:exit

网友评论

    本文标题:python(11):让用户选择何时退出与使用标志

    本文链接:https://www.haomeiwen.com/subject/kfmajrtx.html