繁体   English   中英

if / else语句出现问题

[英]Issue with if/else statement

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

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

请注意缩进。 我认为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!')

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

正确缩进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!')

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

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!')

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM