-1

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

基本上每次用户在 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!')
4

5 回答 5

2

请注意缩进。我认为 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!')
于 2014-08-04T09:00:37.347 回答
0

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

于 2014-08-04T09:01:15.590 回答
0

正确缩进 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!')
于 2014-08-04T09:03:05.903 回答
0

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

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!')
于 2014-08-04T09:03:41.853 回答
0

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

于 2014-08-04T09:03:58.100 回答