【问题标题】:Issue with if/else statementif/else 语句的问题
【发布时间】:2014-09-26 17:01:22
【问题描述】:

我对编码还很陌生,遇到了一个我无法弄清楚或找不到答案的问题。

基本上每次用户在 raw_input 中输入 yes 时,它都会吐出 'if' 字符串,但不会排除 'else' 字符串。

我假设它是因为延迟正在干扰,我没有正确设置它,因为在代码中它会运行(如果、For、Else),也许 For 阻碍了代码,我不知道。将不胜感激一些帮助! :)

import sys
import time
string = 'Hello comrade, Welcome!\n'
for char in string:
    sys.stdout.write(char)
    sys.stdout.flush()
    time.sleep(.03)
time.sleep(1)
x=raw_input('Are you ready to enter the fascinating Mists of Verocia? ')
if x == 'yes':
   string = "Verocia was a mystical land located just south of Aborne"
for char in string:
    sys.stdout.write(char)
    sys.stdout.flush()
    time.sleep(.03)
else:
    print ('Please restart program whenever you are ready!')

【问题讨论】:

  • 你的缩进是错误的,因为它目前写的 if 没有 else - else 属于 for 循环,只要不使用 break 就会执行在循环内部。
  • Python 是缩进敏感的!

标签: python if-statement for-else


【解决方案1】:

请注意缩进。我认为 for 循环应该在 if 语句中。

if x == 'yes':
    string = "Verocia was a mystical land located just south of Aborne"
    for char in string:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(.03)
else:
    print ('Please restart program whenever you are ready!')

【讨论】:

  • 啊,谢谢朋友们! :)
  • 不要使用string作为变量名。
【解决方案2】:

您必须缩进 for 循环。 Python 中的循环有 else 子句 - 它在循环运行时执行,而不发出 break

【讨论】:

    【解决方案3】:

    正确缩进for循环,你会得到你的结果。

    import sys
    import time
    strWelcome = 'Hello comrade, Welcome!\n'
    for char in strWelcome :
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(.03)
    time.sleep(1)
    x=raw_input('Are you ready to enter the fascinating Mists of Verocia? ')
    if x == 'yes':
       str1 = "Verocia was a mystical land located just south of Aborne"
        for char in str1:
            sys.stdout.write(char)
            sys.stdout.flush()
            time.sleep(.03)
    else:
        print ('Please restart program whenever you are ready!')
    

    【讨论】:

    • 不要使用string作为变量名。
    【解决方案4】:

    您的代码中存在缩进问题。应该是:

    import sys
    import time
    string = 'Hello comrade, Welcome!\n'
    for char in string:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(.03)
    time.sleep(1)
    x=raw_input('Are you ready to enter the fascinating Mists of Verocia? ')
    if x == 'yes':
       string = "Verocia was a mystical land located just south of Aborne"
       for char in string:
         sys.stdout.write(char)
         sys.stdout.flush()
         time.sleep(.03)
    else:
        print ('Please restart program whenever you are ready!')
    

    【讨论】:

      【解决方案5】:

      在您的示例中,else 条件连接到 for 语句。 else 套件在 for 之后执行,但前提是 for 正常终止(而不是中断)。

      【讨论】: