我正在制作一个程序,在一个酒窖电话计划中,用户有400分钟,他们可以每月20美元使用。然后,如果用户,一个月使用超过400分钟,他们每分钟收费5美分超过他们计划的400分钟。询问用户他们本月使用的分钟数,然后计算他们的账单。确保你检查一下这个人是否输入了一个负整数(然后你应该打印出“你输入一个负数”)。
我的代码:
def main():
# the bill will always be at least 20
res = 20
# again is a sentinel
# we want the user to at least try the program once
again = True
while again:
minutes = int(input("How many minutes did you use this month? "))
# error correction loop
# in the case they enter negative minutes
while minutes < 0:
print("You entered a negative number. Try again.")
# you must cast to an int
# with int()
minutes = int(input("How many minutes did you use this month? "))
# get the remainder
remainder = minutes - 400
# apply five cent charge
if remainder > 0:
res += remainder * 0.05
print("Your monthly bill is: ","$",res)
det = input("Would you like to try again? Y/N: ")
again = (det == "Y")
main()
如果我输入600,我会得到正确的答案,即30美元。当它要求再次出现时,我输入Y表示是,并输入低于500的任何值,我得到的答案是35美元,这是没有意义的。再次,如果你键入y并输入更低的价格,价格就会上涨。似乎当分钟下跌时价格上涨,但如果分钟上涨,价格会上涨。
我做错了什么。谢谢你的时间。
答案 0 :(得分:2)
您需要将res
移动到循环内部,以便重置。像这样:
#!/usr/bin/env python3.6
def main():
# again is a sentinel
# we want the user to at least try the program once
again = True
while again:
res = 20 # Reset this variable
minutes = int(input("How many minutes did you use this month? "))
# error correction loop
# in the case they enter negative minutes
while minutes < 0:
print("You entered a negative number. Try again.")
# you must cast to an int
# with int()
minutes = int(input("How many minutes did you use this month? "))
# get the remainder
remainder = minutes - 400
# apply five cent charge
if remainder > 0:
res += remainder * 0.05
print("Your monthly bill is: ", "$", res)
det = input("Would you like to try again? Y/N: ")
again = (det == "Y")
main()
你拥有它的方式,res
只是永远递增,永远不会被重置为20。
答案 1 :(得分:1)
您不会在每次尝试之间重置res
,因此每个循环都会被添加到。{1}}。看起来您希望每个循环彼此独立,因此这种行为是无意的。
在while again:
下方,重置res
会将其重新分配给20.您可能甚至不需要首先在循环外声明res
,因为它看起来它只在循环范围内使用过。