【问题标题】:Loop until a specific user input [duplicate]循环直到特定用户输入[重复]
【发布时间】:2011-12-28 04:46:58
【问题描述】:

我正在尝试编写一个猜数程序,如下所示:

def oracle():
    n = ' '
    print 'Start number = 50'
    guess = 50 #Sets 50 as a starting number
    n = raw_input("\n\nTrue, False or Correct?: ")
    while True:
        if n == 'True':
            guess = guess + int(guess/5)
            print
            print 'What about',guess, '?'
            break
        elif n == 'False':
            guess = guess - int(guess/5)
            print
            print 'What about',guess, '?'
            break
        elif n == 'Correct':
            print 'Success!, your number is approximately equal to:', guess

oracle()

我现在要做的是让这个 if/elif/else 命令序列循环,直到用户输入“正确”,即当程序规定的数字大约等于用户数字时,但是如果我不知道用户数我想不出我该如何实现和 if 语句,并且我尝试使用“while”也不起作用。

【问题讨论】:

    标签: python loops numbers


    【解决方案1】:

    作为@Mark Byers 方法的替代方案,您可以使用while True:

    guess = 50     # this should be outside the loop, I think
    while True:    # infinite loop
        n = raw_input("\n\nTrue, False or Correct?: ")
        if n == "Correct":
            break  # stops the loop
        elif n == "True":
            # etc.
    

    【讨论】:

    • +1 类似于我的更新。我认为这里使用input也是错误的。
    • @MarkByers:将其更改为raw_input。从print 语句的外观来看,OP 使用的是 Python 2。
    • 您能告诉我为什么在输入 True 或 False 后代码现在终止了吗?
    • Err... 也许是因为你在那里放了一个 break 语句?!当它遇到 break 语句时,您认为到底会发生什么?也许您应该阅读 Python 教程...
    • 对不起,我太笨了,我已经太久了哈哈,谢谢你的帮助:)
    【解决方案2】:

    您的代码将不起作用,因为您在第一次使用之前没有为 n 分配任何东西。试试这个:

    def oracle():
        n = None
        while n != 'Correct':
            # etc...
    

    一种更易读的方法是将测试移到以后并使用break:

    def oracle():
        guess = 50
    
        while True:
            print 'Current number = {0}'.format(guess)
            n = raw_input("lower, higher or stop?: ")
            if n == 'stop':
                break
            # etc...
    

    Python 2.x 中的input 也读取一行输入,然后评估它。你想使用raw_input。

    注意:在 Python 3.x 中,raw_input 已重命名为 input,旧的 input 方法不再存在。

    【讨论】:

    • +1,虽然使用None 表示“无价值”会更符合pythonic。
    • 您能告诉我为什么在输入 True 或 False 后代码现在终止了吗?
    猜你喜欢
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2018-09-13
    • 1970-01-01
    • 2020-08-15
    相关资源
    最近更新 更多