簡體   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