在while循环中遇到无限循环错误

时间:2020-05-16 00:27:15

标签: python python-3.x

empty_Carton = ''

print("Is the milk carton in the fridge empty? y/n")

input(empty_Carton)

while (empty_Carton != 'y') or (empty_Carton != 'n'):
    if empty_Carton == 'y':
        """Branch here"""
    elif empty_Carton == 'n':
        """Branch here"""
    else:
        print(empty_Carton + " is not a valid input. Type: 'y' or 'n'")

当我运行此代码时,它会进入并在输入正确的代码时陷入无限循环,处于“ else”状态 输入“ y”

我试图四处移动代码并更改比较运算符,但最终仍然陷入无限循环。

2 个答案:

答案 0 :(得分:2)

第一个问题是 inventory_parts_themes <- inventories %>% inner_join(inventory_parts, by = c("id" = "inventory_id")) %>% arrange(desc(quantity)) %>% select(-id, -version) %>% inner_join(sets, by = "set_num") %>% inner_join(themes, by = c("theme_id" = "id"), suffix = c("_set", "_theme")) all_theme_names <- dplyr::pull(inventory_parts_themes, name_theme) all_theme_names[grep("^[sS].*", all_theme_names)] 永远不会被定义为empty_Carton以外的任何东西,您可以使用以下方法解决此问题:

""

请注意,empty_Carton = input("Is the milk carton in the fridge empty? y/n") 函数将要打印的字符串并返回用户输入的字符串。

下一个问题是您的input调用仅进行一次(在input循环之上),因此while的值永远不会更新,并且循环会永远运行。实际上,empty_Carton的值应仅在循环的顶部进行设置,这样循环将至少执行一次,但将继续执行直到输入有效值为止。

最后,由于empty_Carton不能同时是empty_Carton'y',因此'n'必须始终不等于这些选项中的至少一个,因此您的{{1 }}条件始终为empty_Carton。您可以通过将while替换为True或替换为

来解决此问题
or

将所有内容放在一起,我们会得到类似的东西:

and

答案 1 :(得分:-1)

在while循环之前,您只输入了一次输入。因此它将运行无限次。改为编写一个函数,然后在您的while empty_Carton not in ('y', 'n'): # do stuff 条件下调用该函数,或仅使用empty_Carton = '' while empty_Carton not in ('y', 'n'): empty_Carton = input("Is the milk carton in the fridge empty? y/n") if empty_Carton == 'y': print('y') elif empty_Carton == 'n': print('n') 语句。

else
相关问题