为什么我的While循环退出?

时间:2015-07-02 13:41:12

标签: python while-loop

我的评论说明了我的推理,但显然我有些不对劲。我的代码直接跳到了#34;你的总债务是......"

# Dictionary of Bills

expenses = {'mortgage':[], 'personal':[], 'power':[], 'insurance':[], 'water':[], 'food':[], 'savings':[], 'fuel':[], 'phone':[], 'internet':[], 'credit':[], 'emergencies':[]}
totalDebt = 0
switch = "A"

while switch == switch.isalpha(): # Condition is true, switch is a letter  
for each in expenses: # Iterates through each bill  
    debt = input("%s: "%each) # User input   
    if debt.isdigit(): # checks to make sure they only enter numbers  
        debt = int(debt) # Converts debt to its integer value  
        totalDebt = totalDebt + debt # adds debt to keep a running total.  


    else: # User entered something other than a number  
        print("Only enter digits!")  





print("Your total Debt is: $%i" %totalDebt)

input("Press Enter to continue: ")

print("What is this fortnights Income?")

2 个答案:

答案 0 :(得分:11)

你的情况在这里没有任何意义:

while switch == switch.isalpha(): # Condition is true, switch is a letter  

switch.isalpha()会返回TrueFalseswitch本身将不等于这两个值中的任何一个,因此整个表达式始终为False。删除相等测试:

while switch.isalpha():  # Condition is true, switch is a letter  

请注意,您的代码实际上永远不会更改switch,所以现在您的循环将永远继续。

答案 1 :(得分:0)

时间是假的

>>> switch
'A'
>>> switch.isalpha()
True
>>> switch == switch.isalpha()
False

您必须使用switch.isalpha()allown