简体   繁体   中英

Issue with if/else statement

I'm fairly new to coding and I've come across a problem I can't figure out or find an answer to.

Basically everytime the user enters yes into the raw_input it spits out the 'if' string but then doesnt exclude the 'else' string.

I'm assuming its because the delay is interfering and I havent set it out correctly because in the code it goes (If, For, Else), maybe the For is hindering the code, I don't know. Would appreciate some help! :)

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

Please mind the indentation. I think the for loop should be inside the if statement.

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

You have to indent the for loop. Loops in Python have else clause - it is executed when the loop runs through, without break issued

Indent the for loop correctly, you will get your result.

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

There is an indentation problem in your code. It should be:

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

in your example, the else condition is connected to the for statement. The else suite is executed after the for, but only if the for terminates normally (not by a break).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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