My code is here:
import time
idk = input("Hey whats ur name dude ")
print(idk)
time.sleep(1.2)
print("Hmmmm")
time.sleep(1.4)
print("thats a cool name dude")
time.sleep(2)
print("hey", idk)
time.sleep(1.1)
print("uh")
time.sleep(1.4)
dot = input("you know, the last time I actually coded was like a year ago :/. ya think i can still code? (yes/no/maybe) ")
if dot == "yes":
time.sleep(0.7)
print("thx. ill try my best")
if dot == "no":
time.sleep(0.7)
print("ok. i will reteach myself i guess")
if dot == "maybe":
time.sleep(0.7)
print("we will see i guess :]")
else:
print("RESPOND WITH WHAT I TELL U TO RESPOND WITH U IDIOT >:-( ")
In the final part, there is an else statement. whenever I run this and I choose the "yes" or "no" option the else statement appears even though it is not supposed to. By the way, this doesn't happen in the "maybe" option. I don't think that this is an indentation error. I looked through it. I am really confused.
CodePudding user response:
What is happening here is that the else statement is only affecting the if "maybe". What you need to do here is to only write one if statement and then write elif statements for the rest:
if dot == "yes":
...
elif dot == "no":
....
elif dot == "maybe":
...
else:
....
Otherwise, if you input "yes", the code will check first if there are any "yes" and print the yes response, but, when it gets to the "maybe" it checks that the statement is false an therefore runs what is inside the else statement.
Sorry if this is formatted wrong, I'm writing on a phone.
CodePudding user response:
Your elif
only pairs with your final if
statement, which is why the final else statement executes when you select the yes or no options. You can use elif
for the no and maybe options to make all conditionals part of the same control flow.
https://docs.python.org/3/tutorial/controlflow.html
CodePudding user response:
You should use elif
instead of if
.
So when you enter yes it goes to the next if
and sees it's not no then it goes to the next if
and it's not maybe so it prints the else
message.
CodePudding user response:
You should use elif
in this case, since the else
only applies to your last check at the moment:
if dot == "yes":
time.sleep(0.7)
print("thx. ill try my best")
elif dot == "no":
time.sleep(0.7)
print("ok. i will reteach myself i guess")
elif dot == "maybe":
time.sleep(0.7)
print("we will see i guess :]")
else:
print("RESPOND WITH WHAT I TELL U TO RESPOND WITH U IDIOT >:-( ")