Defining a function that uses range of a list inside the function
我在运行此命令时(在第1行)收到一个错误,我不知道如何修复它。我想让一个函数遍历列表中的所有状态,如果找到了,通知用户。谢谢!
1 2 3 4 5 6 7 8 | def find_state(in range(0,len(stateslist))) stateslist = [AL, AK, AZ, AR, CA, CO, CT] if state == stateslist return:"Yes, this state is in the US." state = input("Input the state ID you are checking. (I.E. CO)") print(find_state) |
您正在编写的不是真正的Python,您应该了解语言的基本方面,例如编写字符串、函数和循环。
此外,在编写可能成为int/float变量的数字或以小写形式编写文本时,应该始终考虑用户的问题。
所以这是最好的解决方案:
1 2 3 4 5 6 7 8 | def find_state(state): stateslist = ["AL","AK","AZ","AR","CA","CO","CT"] if state.upper() in stateslist: return"Yes, this state is in the {}.".format(state.upper()) return"State not found" state = find_state(input("Input the state ID you are checking. (I.E. CO)")) print(state) |
1 2 3 4 5 6 7 8 | stateslist = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT'] state = input("Input the state ID you are checking. (I.E. CO)") if state in stateslist: print('Great, it is in!') else: print('No, no such state') |
函数形式:
1 2 3 4 5 6 7 8 9 | def test_state(state): return state in ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT'] state = input("Input the state ID you are checking. (I.E. CO)") if test_state(state): print('Great, it is in!') else: print('No, no such state') |