【问题标题】:Conditional statement not checking the actual condition in a list条件语句不检查列表中的实际条件
【发布时间】:2021-11-16 00:08:30
【问题描述】:

我编写了一个代码来将某些字符串作为输入,并用这些输入形成一个列表,然后在列表上使用条件语句,但无论输入是什么,列表似乎都绕过了条件。

我希望有人能告诉我我在这里犯了什么错误。

while done == 'n':
    if data == 'y':
        # Input for databases
        data_n = input('How many databases would you like to download? (Max 4 as of now): ')

        n = int(data_n)
        i = 0
        name = ['a']*n

        print('Available databases as of now: \n Baltic wave analysis and forecasts (bw) \n Global wave analysis and '
              'forecasts (gw) \n Baltic sea physics analysis and forecast (bp) \n Global ocean 1/12\u00b0 physics '
              'analysis and forecast (gp)')

        for i in range(0, n):
            name[i] = input('Enter the name of the database you would like to download: ')

        # Input for the location data
        while done == 'n':
            if 'bw' or 'bp' in name:
                print('Max range for longitudes in Baltic sea: 9\u00b0 to 30\u00b0')
                print('Max range for latitudes in Baltic sea: 53\u00b0 to 66\u00b0')
                longitude_min_b = input('Enter west limit: ')
                longitude_max_b = input('Enter east limit: ')
                latitude_min_b = input('Enter south limit: ')
                latitude_max_b = input('Enter north limit: ')
            elif 'gw' or 'gp' in name:
                print('Max range for global longitudes: -180\u00b0 to 180\u00b0')
                print('Max range for global latitudes: -80\u00b0 to 90\u00b0')
                longitude_min_g = input('Enter west limit: ')
                longitude_max_g = input('Enter east limit: ')
                latitude_min_g = input('Enter south limit: ')
                latitude_max_g = input('Enter north limit: ')
            else:
                print('Not a valid input.')
            done = input('Done? (Y/N): ').lower()

当我运行代码并输入一些任意字符串值时会发生这种情况。

How many databases would you like to download? (Max 4 as of now): 2
Available databases as of now: 
 Baltic wave analysis and forecasts (bw) 
 Global wave analysis and forecasts (gw) 
 Baltic sea physics analysis and forecast (bp) 
 Global ocean 1/12° physics analysis and forecast (gp)
Enter the name of the database you would like to download: a
Enter the name of the database you would like to download: c
Max range for longitudes in Baltic sea: 9° to 30°
Max range for latitudes in Baltic sea: 53° to 66°
Enter west limit: 

提前谢谢????

【问题讨论】:

  • 我自己还没有在 python 中测试过这个,但我认为问题是你需要 ('bw' in name) 或 ('bp' in name) 使用any 的等效检查将作为好吧,但问题是非空字符串的计算结果为True
  • @Shffl 它有效。非常感谢您的回答。

标签: python if-statement while-loop conditional-statements


【解决方案1】:

您必须将 if 条件更改为

if 'bw' in name or 'bp' in name:
      #code
elif 'gw' in name or 'gp' in name:
      #code

【讨论】:

  • 那行得通。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多