【问题标题】:my while loop skips an if statement and goes straight to the else statement [duplicate]我的while循环跳过一个if语句并直接进入else语句[重复]
【发布时间】:2019-10-19 07:33:18
【问题描述】:

我有一个 while 循环,它似乎跳过了我的第一个 if 语句并直接转到 else 语句。我已经三次检查了代码,它似乎是正确的,但它仍然不会承认我的第一个 if 语句。 (程序中有很多代码没有包含在本题中)

我尝试将 else 语句移动到不同的索引,并重新配置 initialize_objects() 函数以返回主列表而不是 None。它们似乎都没有做任何事情,因为我没有收到错误,无论如何它只是运行底部的 else 语句。

def initialize_objects():
        global jackson_checking, jackson_savings, jackson_business, master_list



        jackson_checking = CheckingAccount('Jackson', 4100)
        jackson_savings = SavingsAccount('Jackson', 100000)
        jackson_business = BusinessAccount('Jackson', 15000)


        master_list = [[jackson_checking, 1, 1], [jackson_savings, 1, 2], [jackson_business, 1, 3]]


        return None

    initialize_objects()

    while isSessionOn is True:
        print('Welcome to 24-hour ATM service.')
        print('insert your card.')


        # Card reading the customer info representation
        customerID = input('Enter your customer id number: ')
        print("\n")


        cust_accounts = []
        for i in master_list:
            if i[1] == customerID:
                cust_accounts.append(i[2])
                isCustomer = True 

        if isCustomer is True:
            isAccountSelected = False


        else:
            print("cannot find your record.")
            print("Please get your card.")
            print("Closing this session...")

我期望发生的是if customerID == 1,然后程序应该转到 isAccountSelected 下面的另一个 while 循环(不包括在这个问题中)。相反,当我输入 1 作为 customerID 的输入时,它会直接移动到底部的 else 语句并继续询问另一个 CustomerID...

看起来像这样:

Welcome to 24-hour ATM service.
insert your card.
Enter your customer id number: 1


cannot find your record.
Please get your card.
Closing this session...
Welcome to 24-hour ATM service.
insert your card.
Enter your customer id number: 1


cannot find your record.
Please get your card.
Closing this session...
Welcome to 24-hour ATM service.
insert your card.
Enter your customer id number:

【问题讨论】:

  • 按照习惯,你不应该使用is True,而是使用== True。您只想在特定情况下使用is
  • python 输入返回字符串,但是你想和整数比较!

标签: python while-loop scope


【解决方案1】:

这是因为 Python 中的 input 总是返回一个字符串。所以当用户输入1作为他们的ID时,Python程序实际上将customerID变成了字符串"1"。因此,当您尝试比较 1=="1" 时,它总是会失败,并且总是会转到 else 块。

【讨论】:

  • 我认为这仅在 Python 3 中是正确的,但这很可能是问题
猜你喜欢
  • 2018-01-11
  • 2015-11-08
  • 2012-06-18
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 2016-10-22
相关资源
最近更新 更多