所以我有一个代码来预测用户的账单。我把它放在循环上,以便它不断重复,直到用户不想继续。
这是我的代码:
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()
所以我的问题是:
我哪里做错了? 另外,我在这里过度工程吗?
答案 0 :(得分:5)
您必须将'status'声明为全局变量才能将值更新为
你的kill方法中"status = False"
。
你可以在这做两件事:
1.将状态声明为全局变量
2.从kill方法
您可以查看有关如何使用全局变量的教程。我不会为你提供代码(为了你自己的优点)。
答案 1 :(得分:3)
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
这将创建一个名为status
的 local 变量,并设置该变量。同名的全局变量不受影响。
在函数中添加global status
,以便它使用全局函数:
def kill() :
global status
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
答案 2 :(得分:1)
我认为你应该使用不那么复杂的方式:
试试这个模型
===>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
答案 3 :(得分:0)
两次修订:
global status
kill()
confirm == "n"
,请在输入时将n
转换为较低试试这个:
def kill() :
confirm = input("Again? (Y/N) : ").lower()
if confirm == "n":
global status
status = False