So I have a code that project the user's bill. I put it on a loop so that it keeps repeating itself until the user don't want to continue.
here is my code:
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()
So my questions are :
- If I enter "n" when the code prompt me, the script won't stop and kept going back to plan_option.
- even though the code stops (eventually), it kept prompting me "Again? (Y/N) : " before it kills itself.
Where did I do wrong? Also, am I over-engineering here?
4 Answers 4
You have to declare 'status' as a global variable inorder to update value to
"status = False" in your kill method.
You can do 2 things here:
1. Declare status as global variable
2. Return "status" (which is a local variable) from kill method
You can check the tutorials on how to use global variables. Am not going to provide you the code (for your own good ofcourse).
3 Comments
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
This creates a local variable named status, and sets that. The global variable of the same name is unaffected.
Add global status in the function so that it uses the global one instead:
def kill() :
global status
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
2 Comments
kill() one more time.I think that you should use less complicated way:
try this model
===>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
Comments
Two revisions:
- Use
global statusinkill() - If you are comparing
confirm == "n", then convertnto lower while taking input
Try this:
def kill() :
confirm = input("Again? (Y/N) : ").lower()
if confirm == "n":
global status
status = False
status, it would be better ifkill()returned a status value.