+ 13
Why is my else statement in python running even if my if statement is true
else statement misbehaving
10 Respostas
+ 16
@Elric Your code will have a better code readability and a faster speed if you store the variables into an array.
members = [names here]
i = input()
if i in members:
print(wow)
else:
print("no)
@Hasan As Elric said try to use elif too, because after one false statement, it will jump straight to else...
+ 8
x="mohammad"
y="abbas"
z="zainab"
a="ali"
b="adnan"
s="samira"
h="hasan"
i=input("")
if i==x:
print("jahesh")
if i==y:
print("monkey")
if i==z:
print("debbeh")
if i==a:
print("tays")
if i==b:
print("dad")
if i==s:
print("mom")
if i==h:
print("king")
else:
print("not a family member or wrong spelling")
this is my code that i'm trying to do
+ 8
even better thanks again
+ 8
worked just fine thank you ,you are a life saver been googling go an hour
+ 8
thanks gami. I was going to include them in to an array. its not a code that I'm trying to develop though ,I was just learnning fooling around so I know I learnt the if else statement correct . yet I learned a lot more from you guys so thanks again .
+ 8
elric don't worry about that I figured it out when you first posted it
+ 7
thanks I'll try just that seems like a logical solution
+ 5
you need to write:
else if
for each of the the statements.
what is happening currently is the last if I==h is not true then it runs the else statement.
you can test that by inputting hassan and it will not print the last statement :)
+ 5
to expand, you are after a switch type statement. python does not have that directly so you need multiple if else statements. change your code to the below:
x="mohammad"
y="abbas"
z="zainab"
a="ali"
b="adnan"
s="samira"
h="hasan"
i=input("")
if i==x:
print("jahesh")
elif i==y:
print("monkey")
elif i==z:
print("debbeh")
elif i==a:
print("tays")
elif i==b:
print("dad")
elif i==s:
print("mom")
elif i==h:
print("king")
else:
print("not a family member or wrong spelling")
+ 4
@gami, that is totally correct, I was going to post that but as Hasan is just starting out I kept it with his example that he provided. @hasan, take note of Gami's example. using pythons :in' statement would be a very neat way to do the same thing. if you are just learning how to do a switch type statement the keep with what you have to practice.
also note I used the wrong syntax, it should be 'elif' not 'else if'! I'll edit to correct now!