Issue with if/else statement

136 Views Asked by At

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

There are 5 best solutions below

1
terekhov.e.a On BEST ANSWER

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!')
0
volcano On

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

1
Sesha On

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!')
0
sgp On

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!')
0
user3883259 On

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).