【问题标题】:while loop input Yes/No (Python 3)while 循环输入是/否(Python 3)
【发布时间】:2019-06-07 18:59:51
【问题描述】:

这是代码:

quiz = str(input("would you like to answer some questions \n choose y/n"))

quiz = quiz.lower()
while quiz != 'y' or quiz != 'n':
    print("please choose 'y' or 'n'")
    input("y/n?")

这是我尝试使用 str() 的代码的一部分,即使没有 or 操作数,它也无法正常工作,顺便说一句我正在使用 python v3.7

1) 如果可以请修复代码

2) 如果你知道其他一些更有效的代码告诉

注意:如果输入是 y。 # 例如 错误是" ValueError: float: Argument: y is not a number "

【问题讨论】:

  • quiz = quiz.lowercase() ... str 调用是不必要的,while 条件中的or 应该是and
  • and 怎么样?或quiz not in ('y', 'n').
  • 不是lower() 而不是lowercase()
  • 是的 Xosrov,对不起,我的代码中的 lower() 我犯了错误

标签: python python-3.x while-loop operands


【解决方案1】:
//This code is for explanation 

quiz = str(input("would you like to answer some questions \n choose y/n"))

quiz = quiz.lower()

while quiz != 'y' and quiz != 'n': //here you are using != that will result false this logic works fine with !

//while quiz == 'y' or quiz == 'n': //will work for or

print("please choose 'y' or 'n'")

input("y/n?")

//this code will work 

quiz = str(input("would you like to answer some questions \n choose y/n"))

quiz = quiz.lower()

while quiz != 'y' and quiz != 'n':

   print("please choose 'y' or 'n'")

   input("y/n?")

我希望这会有所帮助。

您可能对流程图或算法感兴趣,请点击此链接:https://www.edrawsoft.com/explain-algorithm-flowchart.php

您可能也有兴趣进一步了解python,请点击此链接:https://www.python.org/about/gettingstarted/

谢谢。

【讨论】:

  • 是的 ValueError 仍然存在有没有办法完成它
  • 我添加了最后一部分,请复制下面的代码注释说明 //此代码将起作用并将其粘贴到 onlinegdb.com/online_python_compiler 共享代码中没有值错误
【解决方案2】:

输入寻找一个整数,原始输入将接收一个字符串。尝试使用

raw_input(y/n)

这应该清除ValueError

【讨论】:

  • 对不起,错过了 op 使用的是 3
【解决方案3】:

也许是这样的?

def check_input(predicate, msg, error_string="Illegal Input"):
    while True:
        result = input(msg).strip()
        if predicate(result):
            return result
        print(error_string)

result = check_input(lambda x: x in ['yes', 'no'],
                                   'Yes or no?')
print(result)

盗自here

【讨论】:

    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2020-02-15
    相关资源
    最近更新 更多