Home > other >  If else problem, when i run the code its not correctly output it
If else problem, when i run the code its not correctly output it

Time:06-26

Hi I learning python and have question?

If I input Joe, it print found and not found. If I input mark it print only found,

The other names or whatever I input it's say correctly, not found, yet I wonder why when I input Joe it's also print not found(else function)

a, b = 'joe','mark'
name = input("enter a name:")

if name == a:
    print("found")

if name == b:
     print("found")
     
else:
   print("not found")

*note I tried to write the code also like this

If name == a or b:
   Print("found")
Else:
  Print("not found")

Thanks I only few hours learning python

CodePudding user response:

You can do this in a few ways:

One, as @Nin17 said, just change the 2nd if to an elif:

a, b = 'joe','mark'
name = input("enter a name:")

if name == a:
    print("found")

elif name == b:
     print("found")
     
else:
   print("not found")

The second way would be to use the or operator, as you tried to do. Remember that both arguments on the sides of the or operator should be boolean values:

a, b = 'joe','mark'
name = input("enter a name:")

if name == a or name == b:
    print("found")
     
else:
   print("not found")

CodePudding user response:

"Else" refers to the second condition. It is not respected, so the result of the code block "Else" is displayed. Just do it:

a, b = 'joe','mark'
name = input("enter a name:")

if name == a:
    print("found")

elif name == b:
    print("found")
 
else:
    print("not found")`

CodePudding user response:

What you wrote:

The else keyword will only try to find a contradiction with the last if. Hence, you have here two condition blocks: a group consisitng of the first if alone, and a group consisting of the both the second if and the else.

What happens:

Know that Joe, as any other name, will only try his chance once per block. So Joe goes True in the first block and prints "found", then False in the second block and prints "not found".

How to correct it:

If you want to unite these two condition blocks into one, so that Joe does not try his chance in the second if, replace the second if by elif, which basically means else if.

CodePudding user response:

Solved the problem, I only learn code few hours, solved it and thanks for the answers , it was elif, but there is always few ways to write the same code

CodePudding user response:

a, b = 'joe', 'mark'
name = input("enter a name:")

if a in name or b in name:
    print("found")

else:
    print("not found")

Use operator "in" for this.

  • Related