Harvey Johnson
Harvey Johnson

Reputation: 65

Why does Python print the else statement here?

The output of the below code is

Hello
Hola

Why does it print the "Hola"? Shouldn't the else statement be exempt when passing 'en' into the function?

def greet(lang):
    if lang == 'en':
        print("Hello")
    if lang == 'fr':
        print('Bonjour')
    else:
        print('Hola')

greet('en')

Upvotes: 2

Views: 989

Answers (2)

ItzJvs
ItzJvs

Reputation: 307

Because it runs the first statement of if but you haven't used '{}' here and condition is true

i.e lang =='en'

so it prints hello then first if statements doesn't have else statement so it goes to next if which is false because lang is not fr so it printing else statement also..

overall you are checking two conditions first will print Hello and next will print else statement which is Hola

to print only Hello you should use nested if-else statement here

Upvotes: 1

programandoconro
programandoconro

Reputation: 2709

You need to use elif instead.

def greet(lang):
    if lang == 'en':
        print("Hello")
    elif lang == 'fr':
        print('Bonjour')
    else:
        print('Hola')

greet('en')

Upvotes: 5

Related Questions