定义使用函数内部列表范围的函数

时间:2018-12-02 16:01:47

标签: python

运行此程序时出现错误(第1行),我不知道如何解决。我想要一个函数遍历列表中的所有状态,如果找到了,通知用户。谢谢!

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)

2 个答案:

答案 0 :(得分:1)

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')

功能表:

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')

答案 1 :(得分:1)

您编写的不是真正的python,您应该了解这些语言的基本方面,例如编写字符串,函数和循环。

此外,在编写可能会成为int / float变量的数字或小写文本时,应始终考虑用户问题。

所以这是最适合您的解决方案:

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)