Python 中的算法故障排除

Troubleshooting an algorithim in Python

在我的 Python 代码中,我试图让用户从打印列表中输入其中一个操作系统,然后让算法吐出它在指定元组中的索引。然而,即使我从列表中输入一个操作系统,它 returns 我发出的错误消息:

“请 select 下次从列表中选择一个选项。”

我该怎么做才能解决这个问题?

下面是代码:

print("""Operating systems available: 

Windows 10
Linux Mint
Mac OS 11
Android Oreo
Android Pie
Android 11
iOS 14
""")

desired_string = input("From the above list, what operating system would you like to use?: ")

my_tuple = ["Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"]

def linear_search(desired_string, my_tuple):
    for each_item_index in range(len(my_tuple)):
        if desired_string == my_tuple[each_item_index]:
            return each_item_index
    return -1


if desired_string != ("Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"):
    print("please select an option from the list next time.")
    quit()

else:
    search = linear_search(desired_string, my_tuple)

    print(search) 

开始使用这个,

if desired_string != ("Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"):
    print("please select an option from the list next time.")
    quit()

!= 它检查值和数据类型。在上面的例子中是 (string != tuple) It's True

使用这个,

if desired_string not in ("Windows 10", "Linux Mint", "Mac OS 11", "Android Oreo", "Android Pie", "Android 11", "iOS 14"):
    print("please select an option from the list next time.")
    quit()

in 关键字用于检查 list/tuple 中的元素是否存在 return True 否则为 False。

not in 它是 in 的倒数,如果元素存在它 return False。如果元素不存在于 tuple/list 中,它 returns True