Python 发出if/else语句

Python 发出if/else语句,python,if-statement,for-else,Python,If Statement,For Else,我对编码相当陌生,遇到了一个我想不出或找不到答案的问题 基本上,每次用户在原始输入中输入yes时,它都会弹出if字符串,但不会排除else字符串 我假设它是因为延迟在干扰,我没有正确地设置它,因为在代码中,如果,For,否则,可能For阻碍了代码,我不知道。谢谢你的帮助!: import sys import time string = 'Hello comrade, Welcome!\n' for char in string: sys.stdout.write(char) s

我对编码相当陌生,遇到了一个我想不出或找不到答案的问题

基本上,每次用户在原始输入中输入yes时,它都会弹出if字符串,但不会排除else字符串

我假设它是因为延迟在干扰,我没有正确地设置它,因为在代码中,如果,For,否则,可能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中的循环have 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正常终止而不是中断时才执行。

缩进是错误的,因为当前写入的if没有else-else属于for循环,只要循环内部没有使用中断,就会执行。Python是缩进敏感的!啊,谢谢朋友们不要将字符串用作变量名。不要将字符串用作变量名。