【问题标题】:How to restart a python program via user input (for someone that is a novice) [duplicate]如何通过用户输入重新启动python程序(对于新手)[重复]
【发布时间】:2015-12-01 01:18:33
【问题描述】:
print(
        """
 __   __     __                         
| |  | |    | |                          
| |  | | ___| | ___ ___  _ __ ___   ___  
| |/\| |/ _ \ |/ __/ _ \| '_ ` _ \ / _ \ 
\  /\  /  __/ | (_| (_) | | | | | |  __/
 \/  \/ \___|_|\___\___/|_| |_| |_|\___| 
"""
.strip())

print("\t\t\t\tto the pHinator 9001")

ph = input("\nPlease enter a pH value:")

if ph == "7":
    print("\nA pH value of 7 is NEUTRAL")

if "0" < ph < "7":
    print("\nA pH value of less than 7 is ACIDIC")

if "14" > ph > "7":
    print("\nA pH value of more than 7 is ALKALINE")

if ph < "0":
        print("\nAn error occurred. Value must be between 0 and 14")

if ph > "14":
        print("\nAn error occurred. Value must be between 0 and 14")

cont = input("\nPress 1 to enter a new value, Press 2 to exit.")

if cont == "1":
    (RESTART)
if cont == "2":
    input("\n\nPress the enter key to exit.")
    exit

这是我第一次尝试制作一个合适的 python 程序,我环顾四周,但找不到一个有用的答案,我知道如何应用于我的程序,谢谢 :)

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    如果我是你,我会将整个程序包装成一个函数。即

    def func_name():
        print("\t\t\t\tto the pHinator 9001")
    
        ph = input("\nPlease enter a pH value:")
    
        if ph == "7":
            print("\nA pH value of 7 is NEUTRAL")
    
        if "0" < ph < "7":
            print("\nA pH value of less than 7 is ACIDIC")
    
        if "14" > ph > "7":
            print("\nA pH value of more than 7 is ALKALINE")
    
        if ph < "0":
                print("\nAn error occurred. Value must be between 0 and 14")
    
        if ph > "14":
               print("\nAn error occurred. Value must be between 0 and 14")
    
        cont = input("\nPress 1 to enter a new value, Press 2 to exit.")
    
        if cont == 1:
            func_name()
        if cont == "2":
            input("\n\nPress the enter key to exit.")
            exit
    
    func_name()
    

    还要确保您不应该比较字符串。将“0”改为0等。

    【讨论】:

    • 我已经按照你的建议做了,但是我的程序没有出现,不确定发生了什么。
    • 你必须递归地做。即 if cont == 1 应该嵌套在 func_name() 中。还要确保您比较的是整数而不是字符串。 "14" > "7" 没有意义,因为它们都是字符串。它应该是 14 和 7 而不是“14”和“7”。 cont == "1" 与 cont == 1 也是如此
    • @J.Hogg 另外,请确保您最初调用该函数。缩进之外的某个地方。我将编辑上面的代码使其更相似
    • 修复了一半,现在运行良好,但是按 1 只是结束程序而不是重新启动它。(我已经修复了字符串比较)
    • @elephant 见accepted answer on the duplicate question; “Recursion Will Blow Your Stack”,以及如何正确执行此操作的指南。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多