Python while循环不会结束

Python while循环不会结束,python,Python,因此,我有一个代码,项目用户的账单。我把它放在一个循环中,这样它就会不断地重复自己,直到用户不想继续 这是我的密码: status = True def kill() : confirm = input("Again? (Y/N) : ") if confirm == "n": status = False while(status): plan_option = input("Which plan are using ? (a/b/c/d/e):

因此,我有一个代码,项目用户的账单。我把它放在一个循环中,这样它就会不断地重复自己,直到用户不想继续

这是我的密码:

status = True

def kill() :
    confirm = input("Again? (Y/N) : ")
    if confirm == "n":
        status = False

while(status):
    plan_option = input("Which plan are using ? (a/b/c/d/e):   ").lower()
    if plan_option == "a" :
        print("Your current bill is : $90")
        kill() 
    else :
        data_amount = float(input("How much data have you used?          "))

print("===========================") 

def plan_b(x) :
    if x < 10 :
        print("Your current bill is : $60")
    elif x > 10 :
        total = 60 + x*10
        print("Your current bill is : $", total)

def plan_c(x) :
    if x < 5 :
        print("Your current bill is : $40")
    elif x > 5 :
        total = 40 + x*12
        print("Your current bill is : $", total)

def plan_d(x) :
    if x < 2 :
        print("Your current bill is : $30")
    elif x > 2 :
        total =  + x*15
        print("Your current bill is : $", total)

def plan_e(x) :
        total = x*18
        print("Your current bill is : $", total)


if plan_option == "b" :
    plan_b(data_amount)
elif plan_option == "c" :
    plan_c(data_amount)
elif plan_option == "d" :
    plan_d(data_amount)
elif plan_option == "e" :
    plan_e(data_amount)

kill()
因此,我的问题是:

如果在代码提示时输入n,脚本将不会停止并继续返回到plan_选项。 即使代码最终停止了,它还是会再次提示我?是/否:在它自杀之前。 我哪里做错了?
另外,我在这里是否过度工程化了?

您必须将“status”声明为全局变量,以便将值更新为 在kill方法中status=False

你可以在这里做两件事: 1.将状态声明为全局变量 2.返回状态,它是kill方法的局部变量

您可以查看有关如何使用全局变量的教程。当然,我不会为你自己的利益提供代码

这将创建一个名为status的局部变量,并设置该变量。同名的全局变量不受影响

在函数中添加全局状态,以便它使用全局状态:

def kill() :
    global status
    confirm = input("Again? (Y/N) : ")
    if confirm == "n":
        status = False

我认为您应该使用不太复杂的方式:

试试这个型号

===>here your function a()<===

def a():
    print("A plan in action")


while True:
    ===> your loop code <===


    your_input = input("> ")
    your_input = your_input.upper()


    if your_input == 'N':
        print("\n** You escaped! **\n")
        break
    elif your_input == "A":
        print("\n** Plan A lunched ! **\n")
        a()
        ===>you can use 'break' to stop the loop here <=== 
    else:
        continue
两项修订:

在kill中使用全局状态 如果您正在比较confirm==n,则在获取输入时将n转换为lower 试试这个:

def kill() :
    confirm = input("Again? (Y/N) : ").lower()
    if confirm == "n":
        global status
        status = False

相关:与其使用全局状态,不如kill返回一个状态值。谢谢!它现在停止了,但即使循环停止了,它还会跳吗?是/否:在它自杀之前再做一次。这是为什么?@YukaLangbuana这不是你最初的问题。请将您的问题集中在一个特定的问题上。@YukaLangbuana这可能是因为您在最后一行中再次呼叫kill谢谢!它现在停止了,但即使循环停止了,它还会跳吗?是/否:在它自杀之前再做一次。为什么?因为你的程序的最后一行是再次调用kill。
def kill() :
    confirm = input("Again? (Y/N) : ").lower()
    if confirm == "n":
        global status
        status = False